How to send HTML form data as JSON to the server?

First of all, I know a lot of questions with the same name. I have seen so many things, but so far nothing is working for me. That is why I opened this question.

I have two scenarios basically 1) the definition of "action" and "method" as HTML. 2) without the "action" and "method" in the form of HTML.

So here is the first scenario,

1) I have a form with two fields, namely an email address and a password.

here is a fragment

<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> 

At first, when I submit the form, it submits all my URL-encoded field values. The default content type of the urlencoded form. I know it. So now I added ajax to send it as json.

here is my piece of code,

 $('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 the SerializeJSON library to separate form data in JSON.

Now the same thing happens, it sends the form data in the form of urlencoded, while it assumes sending in the form of json to the server.

after serializeJSON(); function, when I warn the data, it is successfully displayed as JSON.

that's what i did

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

it successfully alerts me with the json value of my form fields. but when I use it with jjery ajax, as shown above in the jquery demo form, this json line assumes moving to the server. but it is not, instead it looks like urlencoded.

2) The second scenario is the same as the first, but this time without an action and a form method. What is happening now is that my form method acts like GET, although I mentioned POST in jquery.

Note. I checked all the reports with Wireshark to check for an HTTP request and response.

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

Edit: I found out one more thing. When I submit form data without defining an action and method in an html form, I get the following request and response from the server. (these answers 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 and not in HTML format. this does not work.

This is what I get when I use an action and method in an 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, thanks to everyone who tried to answer. None of the answers worked for me .. This is because there was no coding problem. I read jquery Ajax as an API and found out that a definition other than URL coding in contentType would activate the OPTIONS flag instead of POST. In fact, the browser sends a preliminary request with the OPTIONS flag and, depending on the status of the HTTP server, sends a real request. This is because my internal server does not allow cross-querying .. That's why I am having these problems .. I found a Chrome extension that allows cross-origin temporarily .. This solved my problem ..

Here is the link to this Chrome extension

Chrome extension link

This is an extremely inappropriate solution .. But if you have the same situation as mine, you can use this ..

In my situation, I developed an interface and had an API to execute the request ... But my server did not develop it ... So the source is far away ... In the production environment, all my files will be merged on the server. But now, for testing, I needed to use this extension to work with my API.

+10
json javascript jquery ajax
source share
7 answers

You must change the function as an 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; }); 
0
source share

Do not submit the form and then make an Ajax request. Make the form button not a type of submit, just call Ajax from it onclick.

Or, if you want to work less, just change the form action to some unallocated value "javascript: //", so that only an ajax request is actually sent to the submit event:

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

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> 
0
source share
 $('#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; }); 
0
source share

Jquery function:

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

Specify "Id" in your form, and then use the above method to serialize json

 $.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) } }); 
0
source share

You cannot use the HTTP protocol in a message or receive a request, you must put the path of your file in your directories on your server without making external requests, try removing http://192.168.52.166:6000/ from your POST request

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

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

-2
source share

All Articles