Send form data using ajax

前端 未结 7 936
遇见更好的自我
遇见更好的自我 2020-12-01 04:45

I want to send all input in a form with ajax .I have a form like this.

相关标签:
7条回答
  • 2020-12-01 05:14

    I have written myself a function that converts most of the stuff one may want to send via AJAX to GET of POST query.
    Following part of the function might be of interest:

      if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
        //Get all the input elements in form
        var elem = data.elements;
        //Loop through the element array
        for(var i = 0; i < elem.length; i++) {
          //Ignore elements that are not supposed to be sent
          if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
            continue; 
          //Add & to any subsequent entries (that means every iteration except the first one) 
          if(data_string.length>0)
            data_string+="&";
          //Get data for selectbox
          if (elem[i].tagName.toUpperCase() == "SELECT")
          {
            data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
          }
          //Get data from checkbox
          else if(elem[i].type=="checkbox")
          {
            data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
          }
          //Get data from textfield
          else
          {
            data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
          }
        }
        return data_string; 
      }
    

    It does not need jQuery since I don't use it. But I'm sure jquery's $.post accepts string as seconf argument.

    Here is the whole function, other parts are not commented though. I can't promise there are no bugs in it:

    function ajax_create_request_string(data, recursion) {
      var data_string = '';
      //Zpracovani formulare
      if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
        //Get all the input elements in form
        var elem = data.elements;
        //Loop through the element array
        for(var i = 0; i < elem.length; i++) {
          //Ignore elements that are not supposed to be sent
          if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
            continue; 
          //Add & to any subsequent entries (that means every iteration except the first one) 
          if(data_string.length>0)
            data_string+="&";
          //Get data for selectbox
          if (elem[i].tagName.toUpperCase() == "SELECT")
          {
            data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
          }
          //Get data from checkbox
          else if(elem[i].type=="checkbox")
          {
            data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
          }
          //Get data from textfield
          else
          {
            if(elem[i].className.indexOf("autoempty")!=-1) {
              data_string += elem[i].name+"=";
            }
            else
              data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
          }
        }
        return data_string; 
      }
      //Loop through array
      if(data instanceof Array) {
        for(var i=0; i<data.length; i++) {
          if(data_string!="")
            data_string+="&";
          data_string+=recursion+"["+i+"]="+data[i];
        }
        return data_string;
      }
      //Loop through object (like foreach)
      for(var i in data) {
        if(data_string!="")
          data_string+="&";
        if(typeof data[i]=="object") {
          if(recursion==null)
            data_string+= ajax_create_request_string(data[i], i);
          else
            data_string+= ajax_create_request_string(data[i], recursion+"["+i+"]");
        }
        else if(recursion==null)
          data_string+=i+"="+data[i];
        else 
          data_string+=recursion+"["+i+"]="+data[i];
      }
      return data_string;
    }
    
    0 讨论(0)
  • 2020-12-01 05:18

    can you try this :

    function f (){
    fname  = $("input[name='fname']").val();
    lname  = $("input[name='fname']").val();
    att=form.attr("action") ;
    $.post(att ,{fname : fname , lname :lname}).done(function(data){
    alert(data);
    });
    return true;
    }
    
    0 讨论(0)
  • 2020-12-01 05:22
    $.ajax({
      url: "target.php",
      type: "post",
      data: "fname="+fname+"&lname="+lname,
    }).done(function(data) {
      alert(data);
    });
    
    0 讨论(0)
  • 2020-12-01 05:28

    you can use serialize method of jquery to get form values. Try like this

    <form action="target.php" method="post" >
    <input type="text" name="lname" />
    <input type="text" name="fname" />
    <input type="buttom" name ="send" onclick="return f(this.form) " >
    </form>
    
    function f( form ){
        var formData = $(form).serialize();
        att=form.attr("action") ;
        $.post(att, formData).done(function(data){
            alert(data);
        });
        return true;
    }
    
    0 讨论(0)
  • 2020-12-01 05:30

    In your function form is a DOM object, In order to use attr() you need to convert it to jQuery object.

    function f(form, fname, lname) {
        action = $(form).attr("action");
        $.post(att, {fname : fname , lname :lname}).done(function (data) {
            alert(data);
        });
        return true;
    }
    

    With .serialize()

    function f(form, fname, lname) {
        action = $(form).attr("action");
        $.post(att, $(form).serialize() ).done(function (data) {
            alert(data);
        });
        return true;
    }
    

    Additionally, You can use .serialize()

    0 讨论(0)
  • 2020-12-01 05:33

    The code you've posted has two problems:

    First: <input type="buttom" should be <input type="button".... This probably is just a typo but without button your input will be treated as type="text" as the default input type is text.

    Second: In your function f() definition, you are using the form parameter thinking it's already a jQuery object by using form.attr("action"). Then similarly in the $.post method call, you're passing fname and lname which are HTMLInputElements. I believe what you want is form's action url and input element's values.

    Try with the following changes:

    HTML

    <form action="/echo/json/" method="post">
        <input type="text" name="lname" />
        <input type="text" name="fname" />
    
        <!-- change "buttom" to "button" -->
        <input type="button" name="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " />
    </form>
    

    JavaScript

    function f(form, fname, lname) {
        att = form.action; // Use form.action
        $.post(att, {
            fname: fname.value, // Use fname.value
            lname: lname.value // Use lname.value
        }).done(function (data) {
            alert(data);
        });
        return true;
    }
    

    Here is the fiddle.

    0 讨论(0)
提交回复
热议问题