Post JSON string made from JavaScript array to server with jQuery [duplicate] - javascript

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

Related

Amplifyjs GET request with body

I'd like to be able to use GET with message-body using AmplifyJS.
My question is specifically about how to achieve that with AmplifyJS.
Synthetic tests work fine (Fiddler being my test client). But when I do it through AmplifyJS, the "body" is added to the query string. (Edit: Is this a limitation of underlying jQuery "ajax" or that's AmplifyJS's choice)
amplify.request.define('trickyGet', 'ajax', {
url: 'entity/{param}',
dataType: 'json',
type: 'GET',
contentType: '???'
});
then
amplify.request({
resourceId: 'trickyGet',
data: { param: 'paramVal', data: JSON.stringify({'complex1': 'complex1Val'}) },
//data: { param: 'paramVal', data: {'complex1': 'complex1Val'}) },
success: callbacks.success,
error: callbacks.error
});
I tried all kinds of combinations with how my complex data is represented and what content-type to use.
If I change type to POST (and of course change my API end point), everything works (data is in the message-body). But with get, data is appended to query string (by AplifyJS).
amplify.js uses jQuery's ajax() method, which in turn limits how data is sent during get requests.

jQuery $.ajax done callback not firing

I have the following code :
$("#loginSubmitButton").on("click",function(){
var loginUserDetails = {
email: $("#email").val(),
password: $("#password").val()
};
//Send the AJAX request to authenticate the user
$.ajax({
type: "POST",
url: "/somewebservice/v1/users/authenticate",
data: JSON.stringify(loginUserDetails),
contentType: "application/json;charset=UTF-8",
dataType: "json",
}).done(function() {
$("#loginResult").text("Login successful");
})
.fail(function() {
$("#loginResult").text("Login failed");
});
});
As per the jquery documentation (unless I am understanding something incorrectly) I expect the done to be fired if I receive a 200 OK from my web server. However, in chrome console I can see a 200 OK response but jquery seems to fire the fail handler.
Does anyone have any idea what I might be doing wrong here?
You need to remove:
dataType: "json"
There are lots of suggestions to remove
dataType: "json"
While I grant that this works it's probably ignoring the underlying issue. It's most likely caused by a parser error (the browser parsing the json response). Firstly examine the XHR parameter in either .always() or .fail().
Assuming it is a parser fail then why? Perhaps the return string isn't JSON. Or it could be errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
{"type":"scan","data":{"image":".\/output\/ou...
In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping
dataType: json
If your server returns empty string for a json response (even if with a 200 OK), jQuery treats it as failed. Since v1.9, an empty string is considered invalid json.
Whatever is the cause, a good place to look at is the 'data' parameter passed to the callbacks:
$.ajax( .. ).always(function(data) {
console.log(JSON.stringify(data));
});
Its contents will give you an understanding of what's wrong.
Need to remove , from dataType: "json",
dataType: "json"
The ajax URL must be the same domain. You can't use AJAX to access cross-domain scripts. This is because of the Same Origin Policy.
add "dataType:JSONP" to achieve cross domain communication
use below code
$.ajax({
URL: cross domain
dataType: 'jsonp'
// must use dataType:JSONP to achieve cross domain communication, otherwise done function would not called.
// jquery ajax will return "statustext error" at }).always(function(data){}
}).always(function(data){
alert(JSON.stringify(data));
}
A few things that should clear up your issue and a couple hints in general.
Don't listen for a click on a submit button. You should wait for the submit event on the form.
The data option for $.ajax isn't expecting a JSON string. It wants a serialized string or an array with name and value objects. You can create either of those easily with .serialize() or .serializeArray().
Here is what I was thinking for your script.
$('#form-with-loginSubmitButton').on('submit', function(e){
e.preventDefault():
var $form = $(this),
data = $form.serializeArray();
$.ajax({
type: "POST",
url: "/somewebservice/v1/users/authenticate",
data: data
}).done(function(result){
console.log(result);
});
});

How to send JSON instead of a query string with $.ajax?

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

Ajax query to my webservices is returning xml in my json

I am having this exact problem as raised in this question
ASP.NET JSON web service always return the JSON response wrapped in XML
It's late and I have been sitting in this chair for 10 hours now trying to get ajax and json to work and all I got was deeply frustrated.
So does anyone know how to make my webservice not return my json object wrapped in xml? If I just do a straight dataType: "json" then I get nothing. I have to do dataType: "jsonp" to get anything back from the server at all. But once I do jsonp I get my json wrapped in xml.
Please help
Thanks
Cheryl
If you set the response type to json jQuery is then checking the response to see if it's valid JSON (and since it's XML, that's not the case)...when it's not valid, it silently fails since jQuery 1.4+.
There are 3 important bits when making your request, by default it needs to be a POST and you need to set the contentType to "application/json; charset=utf-8" like this:
$.ajax({
url: 'MyService.asmx/Method',
type: 'POST',
data: myData,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
//do something with data
}
});
Then on the server-side make sure you have the ScriptService attribute set, here's an example very minimal layout:
[WebService] //here by default when you create the service
[ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public MyObject MyMethod(int id)
{
return new MyObject();
}
}

Ajax message best practices

Say I need to use ajax to asynchronously ask the server for an xml file containing relevant data. What is the best practice on what this message should look like? Should it be a string like get_data or something similar? Should it be xml? I don't really need long polling since its a one-time (or close to it) request.
Thanks.
You can use standard a HTTP Post or Get to send the request to your server. If you don't need to specify any parameters to your server side script ( user_id, etc ) then simply appending get_data as a url parameter will work fine.
http://www.domain.com/script?get_data
If you need to send any parameters to the server in order to retrieve data it is best to encode the parameters in JSON or XML and send them as the data portion of your AJAX request. With JQuery and JSON data:
$.ajax({
type: "GET",
url: "http://www.domain.com/script",
data: { key: "value", key2: "value2" },
async: true,
dataType: "json",
success: function( data, textStatus ) {
someCallbackFucntion( data );
}
});
The message should be the url.
For example: http://www.example.com/get_data could return the data you need in the format you need (xml, json).
If you need some other data, use an other url. http://www.example.com/someotherdata
It really depends on the purpose, if everything else is XML, go for XML. Personally I perfer JSON (for the client-side at least).
In a recent implementation I made, I used a simple POST request where the key represented the type of data and the value contained the time-interval it should return.
Which could be (jQuery):
$.ajax({
type: "POST",
url: "http://www.domain.com/script",
data: { stock_value: "last_30_min", group_activity: "last_20" },
async: true,
dataType: "json",
success: function( data, textStatus ) {
someCallbackFucntion( data );
}
});
A server-side controller would then handle the request appropriately and the client-side would know what data to expect when it returned. Also the key and value would be humanly readable from both client- and server-side. Of course the time-intervals could be a timestamp or otherwise, whatever fits the need.

Categories

Resources