How to send HTML form data as JSON to server?

First of all i know plenty of questions out there with the same Title.. I saw so many things, but nothing works so far for me. Thats why i opened this Question.

i have TWO scenarios basically
1) defining “action” and “method” in html form.
2) without “action” and “method” in html form.

So here is the FIRST scenario,

1) I have a form with just two fields namely email and password.

here is the snippit

<form id="login-form" action="http://192.168.52.166:6000/api/2/users/login/" method="post">

<p><label for="email">Email</label>
<input type="email" name="email" id="email"></p>

<p><label for="password">Password</label>
<input type="password" name="password" id="password"></p>

<button value="Submit" type="submit">Login</button>
</form>

First when i submit form, it send all my field values as url encoded. the default content-type of a form is urlencoded. i know that. So now what i did is, added ajax to send it as json.

here is my jquery snippit,

$('form').submit(function(){

    var obj = $('form').serializeJSON();

    $.ajax({
        type: 'POST',
        url: 'http://192.168.52.166:6000/api/2/users/login/',
        dataType: 'json',
        data: JSON.stringify(obj),
        contentType : 'application/json',
        success: function(data) {
            alert(data)
        }
    });

i am using SerializeJSON library to serealize the form data to json.

now what happens is the same thing, it sends the form data as urlencoded while it suppose to send as json to server.

after the serializeJSON(); function when i alert the data, it successfully shows as json.

here is what i did

var obj = $('form').serializeJSON();
var jsonString = JSON.stringfy(obj);
alert(jsonString)

it successfully alerts me with json value of my form fields. but when i use it with ajax jquery as shown in above jquery form demo, that json string suppose to travels to server. but it is not, instead it goes as like urlencoded.

2) SECOND scenario is same as FIRST one, but this time without form’s action and method. What is happening now is my form method acts as GET even though i mentioned POST in jquery.

Note: I checked all the reports with Wireshark to check for HTTP request and Response.

Read More:   how to check if a file is gzipped or not in firefox/firebug

What am i doing wrong in here? I just want to send JSON data to server instead of URLEncoded. What i should i do?

Edit: i found out another thing. When i send form data without defining action and method in html form, i recive following request and response from server. (these responses are taken from Wireshark)

OPTIONS /api/2/users/login/ HTTP/1.1
Host: 192.168.52.166:6000
Access-Control-Request-Method: POST
Origin: http://localhost
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost/app/login.html
Accept-Language: en-US,en;q=0.8,ca;q=0.6
Accept-Encoding: gzip

HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Mon, 14 Nov 2016 00:55:42 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
Allow: POST, OPTIONS

so it seems like when i mention POST in jquery instead of in html form. it is not working.

Here is what i get when i use action and method in html form.

POST /api/2/users/login/ HTTP/1.1
Host: 192.168.52.166:6000
Content-Length: 48
Cache-Control: max-age=0
Origin: http://localhost
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: http://localhost/app/login.html
Accept-Language: en-US,en;q=0.8,ca;q=0.6
Cookie: csrftoken=M5ItY7prMtJLBZWOJAN4D9uMDs2uFz5d
Accept-Encoding: gzip

email=emjimadhu%40email.com&password=qwerty123

HTTP/1.1 201 CREATED
Server: nginx/1.4.6 (Ubuntu)
Date: Sun, 13 Nov 2016 18:11:51 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
Allow: POST, OPTIONS
Set-Cookie: csrftoken=tFSyA9OSfyBi4NHoU6FVFSD7BZOE6S1a; expires=Sun, 12-Nov-2017 18:11:51 GMT; Max-Age=31449600; Path=/
Set-Cookie: sessionid=eoaq13tgrjdmsqwcke7zbhgv92dec9c3; expires=Sun, 27-Nov-2016 18:11:51 GMT; httponly; Max-Age=1209600; Path=/

Answer Found

First of all thank you all who tried to answer.. None of the answer worked for me.. It’s cause there wasn’t a coding problem.. I read jquery Ajax as API and found out, defining other than URL encode in contentType will trigger OPTIONS flag instead of POST.. Basically what it does is browser will send a pre request with OPTIONS flag and based on servers HTTP status, it will send real request.. It’s happening cause my back end server doesn’t allow cross origin request.. That’s why I got those problems.. I found a chrome extension which allows cross origin temporarily.. That cleared my problem..

Read More:   Determine when image finished loading with JavaScript or jQuery:

Here is the link to that chrome extension

Link to chrome extension

It is highly not appropriate solution.. But if you have same situation as mine, you can use it..

My situation is I developed front end and having API to making request.. But my back end, I didn’t developed it.. So the source is far away.. While in production environment, all my files will be merged in server.. But for now, for testing, I needed to use this extension to work with my API..

your code is correct. you only need preventDefault();

$( "#target" ).submit(function( event ) {
 
   //your code

  event.preventDefault();
});

without it the form is also posted by the browser. The http trace you report regards the normal post of the browser not the ajax call.

You have to change the function as event-listener.

    $('#form').on('submit', function(event){

        var obj = $('form').serializeJSON();

        $.ajax({
            type: 'POST',
            url: 'http://192.168.52.166:6000/api/2/users/login/',
            dataType: 'json',
            data: JSON.stringify(obj),
            contentType : 'application/json',
            success: function(data) {
                alert(data)
            }
        });

       return false;
   });

Don’t submit the form and then make an Ajax request. Make the form button not of submit type, just call Ajax from it’s onclick.

Or, if you want to work less, just change the form action to some idle value “javascript://”, so that only the ajax request is actually sent to the server on the submit event:

<form id="login-form" action="javascript://" method="post">

$('#form').on('submit', function(event){

        var obj = $('form').serialize();

        $.ajax({
            type: 'POST',
            url: 'http://192.168.52.166:6000/api/2/users/login/',
            dataType: 'json',
            data: obj,
            contentType : 'application/json',
            success: function(data) {
                alert(data)
            }
        });

       return false;
   });

here is my code It will help you:

  <form name="myform" id="myform">
    <div class="form-group">
      <label for="fullName">Name:</label>
      <input type="text" name="fullName" class="form-control">
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" name="email" class="form-control">
    </div>
    <div class="form-group">
      <label for="subject">Subject:</label>
      <input type="text" name="subject" class="form-control">
    </div>
    <div class="form-group">
      <label for="mark">Mark:</label>
      <input type="number" name="mark" class="form-control">
  </form>
  <button type="submit" class="btn btn-success " id="submitform">Submit</button>


  <script>
  $(document).ready(function () {
      $("#submitform").click(function (e) {
          var MyForm = JSON.stringify($("#myform").serializeJSON());
          console.log(MyForm);
          $.ajax(
              {
                  url: "<your url>",
                  type: "POST",
                  data: MyForm,
              });
          e.preventDefault(); //STOP default action
      });
  });
  </script>

Jquery Function:

var _serializeForm = function (id) {
        var result = {};
        $.each($(id).serializeArray(), function (i, field) {
            result[field.name] = field.value.trim() || null;
        });
        return result;
    }

Provide “Id” to your Form and then use above method for json serialization

$.ajax({
        type: 'POST',
        url: 'http://192.168.52.166:6000/api/2/users/login/',
        dataType: 'json',
        data: JSON.stringify(_serializeForm('#formId')),
        contentType : 'application/json',
        success: function(data) {
            alert(data)
        }
    });

$('#btn').click(function(){

  $.post('getJSONData.jsp', $('#wForm').serialize(), function(json){

    alert(json);

  }, 'json');

});

You can’t use the http protocol within a post or get request, you must place the path of your file within your directories on your server, without making external requests, try removing http://192.168.52.166:6000/ from your request POST

  $.ajax({
        type: 'POST',
        url: 'api/2/users/login/',
        dataType: 'json', 
        data: JSON.stringify(obj),
        contentType : 'application/json',
        success: function(data) {
            alert(data)
        }
   });


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts