Send JSON Data on HTML form submit
jquery, json, post
Solution
There are 2 things you need to do to send JSON to the server with a jQuery AJAX call:
The request payload should be a string containing the JSON payload (not a JavaScript object)
The "Content-Type" header in the HTTP request should be set to "application/json". This lets the server know that the request payload contains JSON data. $.post uses the default value of "application/x-www-form-urlencoded" for the "Content-Type" header. $.ajax allows you to set this header via the "contentType" option.
Try changing your code to the following:
$.ajax({
type: 'POST',
url: 'http://localhost:5000/task-groups/add',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(payload)
});
Note that $.post has a dataType parameter, but this controls the "Accept" request header, which is used to indicate the preferred format for the response.
Problem
I have a html form and that form has two fields (name , description). When a user hits submit button for that form I want to submit form data in json format. I tried the following: ``` function submitData(){ payload.name = $("#project-name").val(); payload.description = $("#project-description").val(); $.post("http://localhost:5000/task-groups/add", payload); return false; } ``` Submitdata is called when my form's button is clicked. But this is sending form data and not json data I have a python flask server running. [1] When I do: ``` payload = request.get_json() name = payload['name'] ``` It is throwing the following exception ``` File "/Users/saik/projects/mturk/server/src/index.py", line 37, in add_task_group name = payload['name'] TypeError: 'NoneType' object is not subscriptable ``` [2] However, I am able to access the data on the server side using following: ``` name = request.form['name'] ``` Is it possible to send json data on form submit, so that I can access data using [1] The reason I am trying to send JSON data on form submit is because I have a server which serves REST API for command line clients. And I would like to use same server and endpoint to serve browser based clients.