Well, here is the story:
I have some data need to send to server, but they should turned into JSON dataType first.
I made such ajax call:
$.ajax({
url: url, // the url I want to post to.
type: 'POST',
contenttype:'application/json; charset=utf-8',
beforeSend: //some HTTP basic auth stuff
data: {
name:'test',
key:'foo',
key2:'bar'
},
dataType:'JSON'
});
basically I'm expecting the data I send to server was:
[name:test,key:foo,key2:bar]
but what I've got was:
name=test&key=foo&key2=bar
What did I missing? How can I get those data into JSON?
To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.
To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode).
var data = {'bob':'foo','paul':'dog'};
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify(data),
dataType:'json'
});
/** Added **/
The above does not do anything with the response from the server if you need to do something then a callback will be called when the server has responded.
var data = {'bob':'foo','paul':'dog'};
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify(data),
dataType:'json',
success: function(data){
//On ajax success do this
alert(data);
},
error: function(xhr, ajaxOptions, thrownError) {
//On error do this
if (xhr.status == 200) {
alert(ajaxOptions);
}
else {
alert(xhr.status);
alert(thrownError);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With