Send Form Data as JSON via AJAX with JQuery

In previous post we have seen how to send data in serialized form with ajax using searialize() method. Now we will see how to post json data with ajax using serializeArray().

Before proceed we must know what is the difference between serialize() and serializeArray(). serializeArray creates an array and serialize is used to mean a query string for HTTP request. We have seen serialize method and its functionality in our previous post.

Here with use of serializeArray we convert a form data into array. JSON.stringify is used to convert form data (mean JavaScript value) into JSON string.

Demo

[sociallocker]Download[/sociallocker]

Why we should send data as JSON? Basically this depends on structure data complexity. If we have a huge structure data then we preferred JSON because it is light weight and is used to transmit data between server and web application.

JSON(JavaScript Object Notation) is basically alternative of XML for transmit structure data and method of specifying structure data.

In simple words, JSON is data interchange format. Let us see how to send data as JSON with AJAX in PHP.

Simple form to send data as JSON with jQuery and AJAX. Let us see the snippet.

Source Code

<form id="myFormvama" method="POST">
<label>Name</label><input type="text" name="name" value=""><br>
<label>Pincode</label><input type="text" name="pincode" value=""><br>
<label>Address</label><input type="text" name="address" value=""><br>
<label>City</label><input type="text" name="city" value=""><br>
<label>State</label><input type="text" name="state" value=""><br>
<label>Country</label><input type="text" name="country" value=""><br>
<label>Phone</label><input type="text" name="phone" value=""><br>
<label>Email</label><input type="text" name="email" value=""><br>
<input type="button" name="submit" value="Send Request" id="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#msgs').hide();
$('#submit').click(function(){ 	

var formData = JSON.stringify($("#myFormvama").serializeArray());

$.ajax({
type :'POST',
url : 'res.php',
cache: false,
data: {datas:formData},
success: function(response) { 
document.getElementById('msgs').innerHTML= response;
}
})
jQuery('#msgs').slideToggle('slow')
})
})
</script>
<div id="msgs" style="height:auto;width:auto;"></div>

ReadHow to Receive JSON POST with PHP

How to POST JSON Data With PHP cURL

Simple and easy way to send data as JSON with AJAX as we have seen above. You can get complete source code instantly by a single click on download button.

If you feel useful article please share with friend and colleague.

Leave a Comment