jQuery post form data using ajax

Javascript code snippet to submit a form using POST to server and process returned data. Here when submit button is clicked we serialize whole form and POST it to server endpoint url. For the purpose of this tutorial, the endpoint is just returning the posted params.

Post form data using Ajax without modification

We’ll use jQuery .serialize() and post it using jQuery .post(). Note this approach will not include input files.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<form id="form1" action="/api/post-dump.php" method=POST>
name1: <input type="text" name="name1" value="value1" /><br/>
name2: <input type="text" name="name2" value="value2" />
<input type="submit" name="submit" value="submit"/>
</form><br/>
Response from server:
<pre id="result" style="background-color:lightgray;"></pre>

<script type="text/javascript">
$("#form1").submit(function() {
  var action = $("#form1").attr("action");
  $.post(action, $("#form1").serialize(), function(ret) {
    $("#result").html(ret);
  });
  return false;
});
$("#form1").trigger("submit");
</script>
refresh

Post form data using Ajax with modification

We’ll use jQuery .serializeArray(), modify returned array and post it using jQuery .post(). Note this approach will not include input files.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<form id="form1" action="/api/post-dump.php" method=POST>
name1: <input type="text" name="name1" value="value1" /><br/>
name2: <input type="text" name="name2" value="value2" />
<input type="submit" name="submit" value="submit"/>
</form><br/>
Response from server:
<pre id="result" style="background-color:lightgray;"></pre>

<script type="text/javascript">
$("#form1").submit(function() {
  var action = $("#form1").attr("action");
  dataArr = $("#form1").serializeArray();
  dataArr.push({name:"name3", value: "value3"});
  $.post(action, dataArr, function(ret) {
    $("#result").html(ret);
  });
  return false;
});
$("#form1").trigger("submit");
</script>
refresh

Few points to note

  1. jQuery("#form1").serialize() will serialize form data and it will produce the following string in our example:

    name1=value1&name2=value2
    
  2. jQuery("#form1").serializeArray() will serialize form data and it will produce an array of Objects which can be modified.
  3. jQuery serialize method excludes the submit button name and value in serialized data.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments