Is there any reason you embedded data to send (edited_data
) into curly braces ?
In your first_func
POST you are sending data as JSON. But not in your second_func
POST. What format is accepted by your endpoint get_updated_data.php
?
jQuery POST form-data (traditional)
Using POST method the default contentType is 'application/x-www-form-urlencoded; charset=UTF-8'
. So if not specified other contentType you usually have two options:
- query-string
- object (key-value) which gets transformed to query-string by jQuery internally before sending
See docs jQuery ajax, Section "Sending Data to the Server":
The data option can contain either a query string of the form key1=value1&key2=value2
, or an object of the form {key1: 'value1', key2: 'value2'}
. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.
According to this you should call jQuery's ajax
function as follows:
var edited_data = "name=ravi&age=31"; // query string
// or
var edited_data = {name:"ravi",age:"31"}; // object (key-value pairs)
$.ajax({
url : "get_updated_data.php",
type: "POST",
data : edited_data,
success: function(data, textStatus, jqXHR)
{
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
}
});
jQuery POST data as JSON
You would like to send data as JSON and your PHP-endpoint expects so.
Your post-settings need these adjustments:
dataType: 'JSON'
(from your first_func)
data: JSON.stringify(data)
(from your second_func)
contentType: 'application/json; charset=utf-8'
Then best-approach is to wrap that into a function like following:
$.postJSON = function(url, data, callback) {
return jQuery.ajax({
type: 'POST',
url: url,
contentType: 'application/json; charset=utf-8', // header used by endpoint
data: JSON.stringify(data), // needed since JSON is sent in body as string
dataType: 'json', // this tells jQuery how to handle data-response
success: callback // this will be your callback-function
});
};
See also