Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send HTML form data as JSON to server?

Tags:

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.

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

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

like image 720
Em Ji Madhu Avatar asked Nov 15 '16 12:11

Em Ji Madhu


People also ask

Can I send form data as JSON?

Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.

How do I save HTML form data to JSON file?

stringify($("#emails_form"). serializeArray()); If you want to store formData in a JSON file, you need to post it to the server (e.g. per AJAX) and save it. But in that case, you can simply post the form und convert it to JSON on the server itself.

How can I convert form data to JSON?

How to Convert Form Data to JSON With Object. fromEntries() Note: For both methods, we can use JSON. stringify() to convert the object into a JSON string, which we can then use to send JSON encoded data to APIs.


1 Answers

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.

like image 74
Andrea Avatar answered Nov 03 '22 00:11

Andrea