have an ajax method, which uses post. the response should come under request payload, but it is coming as query string parameter.
Method ajax:
$.ajax({
type: 'POST',
url: '<url>',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(object)
});
Current Output:
Query String Parameter : Object
Expected output :
Request Payload : Object
Look at http://api.jquery.com/jQuery.ajax/:
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processDataoption to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
Try to change your data to something like that:
data: {obj: JSON.stringify(object)}
Related
I'm not sure why this is happening, but could use some input.
I have an object attached to the body of a POST request through jquery ajax. The object is similar to this example:
var dogData = {breeds: [{Dog: "Golden Retriever"}, "Rottweiler"]}
The AJAX request is this:
$.ajax({
type: "POST",
url: "api/dog",
data: dogData,
})
On my server using Express + bodyparser:
app.post('/dogs', function(req, res){console.log(req.body)})
When I console.log the object:
{breeds: [{Dog: "Golden Retriever", Rottweiler: true}]}
I want the same object that I initially started out with to be returned from the server. Can someone explain why the string is attached to the previous object along with a boolean value?
use jsonparser on your server and make your post with json content
$.ajax({
type: "POST",
url: "api/dog",
data: JSON.stringify(dogData),
contentType: 'application/json; charset=utf-8'
})
Body parser parses urlencoded form data.
When you send your data it will be converted to:
breeds[0][Dog]=Golden+Retriever&breeds[Rottweiler];
When bodyparser parse it, because of there is no value on Rottweiler and it exists, it will be converted to "true"
Following code:
$.ajax(serviceUrl,
{
data:
format: 'json'
id: [2,3,4]
success: (data) ->
successCallback(data) if successCallback
error: (error) ->
failureCallback(error) if failureCallback
})
Sends request with following query string parameters:
format:json
id[]:2
id[]:3
id[]:4
Is it possible to somehow avoid those brackets at the end of parameter?
By default jquery ajax uses GET method if the 'type' parameter not set.
So, the 'data' value should be converted into the part of the serviceURL. One of the popular way to send array as a parameter is to convert it into string like: id[]=2&id[]=3&id[]=4
You may send parameters as JSON object or other http content-type, but using other methods, like POST or PUT.
Semantics of GET is to retrieve a resource, POST - to create a new resource, PUT - create or modify if exists, etc.
You may use something like this to send and receive data in JSON format:
data =
format: 'json'
id: [2,3,4]
$.ajax
url: serviceUrl
type: 'post'
data: JSON.stringify(data)
contentType: 'application/json'
dataType: 'json'
Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here
Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here
Assume we use jQuery.ajax() to POST data with two parameters, game_id and player_id.
When we use jQuery.ajax(), the server receives parameters like this:{"_json"=>"game_id=4f6a593a8cb45b16c0000491&player_id=4f68ed4b8cb45b16c0000111"}
We would like the server to receive parameters like this:
{"game_id=4f6a593a8cb45b16c0000491&player_id=4f68ed4b8cb45b16c0000111"}
Essentially, ajax() makes "_json" the master key for all parameters. Is there a way to prevent this, or are we doing something wrong?
Here's some specific code:
$.ajax({
type: 'POST',
url: UPDATE_GAME_URL,
data: { "game_id" : game_id,
"player_id" : get_player_id(),
"turn_set" : JSON.stringify(turn_set) },
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
Thanks!
jQuery does not contain any code that prefixes fields with json_ so the problem is somewhere else.
However, you need to remove contentType: 'application/json; charset=utf-8' to ensure the server parses the POST data correctly - you are not posting JSON after all.
If your server does expect a JSON payload (according to the string you expect to receive it doesn't!), you would have to use data: JSON.stringify({...}) to ensure you actually send a JSON string instead of form-encoded key/value pairs.
$.ajax({
type: 'POST',
url: UPDATE_GAME_URL,
data: { "game_id" : game_id,
"player_id" : get_player_id(),
"turn_set" : turn_set },
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
You don't need to stringify the turn_set, jQuery will do it for you.