Send HTML Form Data as JSON via Ajax

There’s a lot of confusion among new developers on which format data should be sent to server.  Some dev’s create data string manually and some use jQuery’s API methods .serialize() and .serializeArray(). Our last tutorial shows how to use serializeArray() method to send array of objects to server via Ajax. Now taking it further what if I’d want to send JSON data to server, in this post I will be doing that. this post is just a guide to all new developers understand how to leverage JSON in exchanging data between client and server.

json

First question that would surely come to your mind is why to send JSON to server? Is there any advantage of sending data as JSON? I was also puzzled by this question and after some googling around I got the answer that it depends upon what your web app does and what data you are sending? If structure of data is really complex then JSON must be used in order to reduce parsing complexity.  Sometimes you have web application that accepts/prefers JSON data coming from client end so in such cases you need to convert your form’s data in JSON and post it to server.

So serializing data as JSON, it’s easy to extend .serializeArray() method and process its output to give JSON formatted data. Below is a simple code snippet that allows you do that:

Live Demo   Download

</p>
var jsonData = {};
 var formData = $("#myform").serializeArray();
 $.each(formData, function() {
 if (jsonData[this.name]) {
 if (!jsonData[this.name].push) {
 jsonData[this.name] = [jsonData[this.name]];
 }
 jsonData[this.name].push(this.value || '');
 } else {
 jsonData[this.name] = this.value || '';
 }

 });
 console.log(jsonData);
<p style="text-align: justify;">

Above code snippet reference.

Now what? Any other way to convert form data into JSON, yes of course there are many good jQuery plugins for that. Few of them are jQuery.serializeJSON and json2.js.

Below is a simple HTML form using jquery.serializeJSON plugin:

</p>
<!DOCTYPE html>
<html lang="en">
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="jquery.serializeJSON.min.js"></script>
<script>
$(document).ready(function(){
$("#simplepost").click(function(e)
{
var MyForm = $("#ajaxform").serializeJSON();
console.log(MyForm);
 $.ajax(
 {
 url : "submit.php",
 type: "POST",
 data : {valArray:MyForm},
 success:function(maindta)
 {

alert(maindta);

 },
 error: function(jqXHR, textStatus, errorThrown)
 {
 }
 });
 e.preventDefault(); //STOP default action

});
});</script>
</body>
<div id="message"> </div>
<form name="ajaxform" id="ajaxform" method="POST">
First Name: <input type="text" name="fname" value =""/> <br/>
Last Name: <input type="text" name="lname" value ="" /> <br/>
Email : <input type="text" name="email" value=""/> <br/>
<input type="button" class="btn btn-info" id="simplepost" value="Run Code"></form>
</html>

<span style="text-align: justify;">

Above code simply sends JSON data using .serializeJSON method. You will get this code also in downloaded file so try it 🙂 Share this simple tut with your friends and followers 🙂

2 thoughts on “Send HTML Form Data as JSON via Ajax”

  1. Bro,
    You can use my jQuery plugin for above given HTML code and javascript code will be as under

    var form=$(“form”).find(“input”).formInteract();

    //To send data to server it will be

    form.postAjax(“url”, function(rsp){
    //do your stuff.
    });

    however you also can use getAjax method. or if you want to get data of form before posting it to server then get your JSON as

    var JSONData =form.get();

    //or if you want to set data to form then code would be

    form.set({fname:”Ranjeet”, lname:”Rana”});

    Oh yes there is a very powerful validation methods like Java persistence API methods are notNull, notEmpty(to validate if some element has its childelements or not), sizeMin, sizeMax, min, max, equal, email, pattern and much more.

    I would also like to get suggestions if you can.

    here is link to project.

    https://bitbucket.org/ranjeet1985/forminteract

Comments are closed.