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.
Related
I m new to this so please bear with me.
I want to call an API which accepts data in POST method and in json format.
Please tell me how to call ajax which will send data in post format and in json.
I have tried this :
$.ajax({
url: 'http://domain.com/api',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: formData,
success: function (response) {
}, error: function() {
alert("Error! Please try again.");
}
});
formData in the above code is in array format.
Kindly guide me.
This is how the json I get from my page send when I clicked post, I throw a different URL.
That piece of data should like to come to look like this:
api.quickpay.net/subscriptions?currency=dkk&order_id=testworld&description=MB: 6-testworld
But when I get my json back watching it like this:
{"Prices":220,"HiddenIdMedlemskab":6,"ordre_id":"6-8315042016","currency":"DKK","description":"MB: 6-8315042016"}
The json should I have shed into a url that I added earlier.
My jquery code looks like this:
$.ajax({
type: 'post',
url: '/Medlem/medlemskabet',
dataType: 'json',
data: JSON.stringify(requestData),
contentType: 'application/json; charset=utf-8',
async: true,
processData: false
});
Over on my url /Medlem/medlemskabet
That gets the dates that I need for my json to specify package price orderid etc
So my question is How do I tag my json about throwing it over to the api URL and throws it into their system.
I've built since the MVC C #
You can pass the JSON object as an argument to $.get(), and jQuery will convert the properties into URL parameters.
$.ajax({
type: 'post',
url: '/Medlem/medlemskabet',
dataType: 'json',
data: JSON.stringify(requestData),
contentType: 'application/json; charset=utf-8',
async: true,
processData: false,
success: function(response) {
$.get('api.quickpay.net/subscriptions', response);
}
});
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)}
Why is this call showing the values encoded onto the URL like so?
http://localhost:49597/api/auth?user=jon&password=123
Am using the following ajax call...
$.ajax({ url: "api/auth",
type: "get",
data: { user: "jon", password: "123" },
dataType: "json",
contentType: "application/json; charset=utf-8"
});
I want the data to be sent as json...
Because it is a GET request.
GET will send data in the querystring. If you want to avoid that, you can change your type to POST POST will send the data in the request body.
$.ajax({ url: "api/auth",
type: "post",
//other stuff
});
If it is a Login form, you should probably use POST method.
GET requests do not have a request body, therefore all info must be stored in url as query parameters. I would also recommend not authenticating users with Javascript, and would definitely make that a POST request.
Because the code specifies a request of type GET. A GET request passes the parameters via a query string. You should switch to a post if you do not want to use a query string.
$.ajax({ url: "api/auth",
type: "post",
data: { user: "jon", password: "123" },
dataType: "json",
contentType: "application/json; charset=utf-8"
});
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