Pass value from html form to php without submitting the form

前端 未结 5 1001

I have a text box. I want to take user input from there and pass it to PHP without using submit button. I would prefer a normal button and onclick should pass d

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 21:18

    Yes, it is called AJAX. : )

    In jQuery, for brevity:

    // or $('#textbox_autopost').blur if you want to do it when the box loses focus
    $('#textbox_autopost').change(function(){
        $.ajax({
            type: "POST",
            url: "some.php",
           data: {text:$(this).val()}
        });
    });
    

    if you want to do it via button click

    You can also do it through an A HREF (or submit button, or or something else wacky:

    
    add comment
    
    $('#inline_submit_a').click(function(evt){
        $.ajax({
            type: "POST",
            url: "some.php",
           data: {text:$('#textbox').val()}
        });
        evt.preventDefault();
        return false;
    });
    

    If you want to do it on enter:

    $('#textbox_autopost_onenter').keydown(function(evt){
        if ((evt.keyCode) && (evt.keyCode == 13))
        {
          $.ajax({
            type: "POST",
            url: "some.php",
            data: {text:$(this).val()}
          });
          evt.preventDefault();
          return false;
        }
    });
    

    Final, site-ready code:

    $(document).ready(function(){
       function submitMe(selector)
       {
            $.ajax({
              type: "POST",
              url: "some.php",
              data: {text:$(selector).val()}
            });
    
       }
       $('#textbox_button').click(function(){
          submitMe('#textbox');
       });
       $('#textbox').keydown(function(evt){
          if ((evt.keyCode) &&(evt.keyCode == 13))
          {
             submitMe('#textbox');
             evt.preventDefault();
             return false;
          }
       });
    

提交回复
热议问题