Amplifyjs GET request with body - javascript

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.

Related

Bad Request error when posting data using jQuery in IE only

I've written a small single-page application using Knockout.js and Sammy.js, plus jQuery for posting data back to the server.
This works fine in Firefox, but all my POSTs are getting a "400 Bad Request" response in IE.
I've used Fiddler to see what's going on, and the only difference I can see is that IE includes the hash in the Referer header, but I don't think that should cause a problem.
Here's my jQuery post:
$.ajax({
type: 'POST',
url: '/App_Presentation/BDM/RdmUserCategoryService.svc/GetUserCategoryUsersByCategory',
data: '{ "categoryId" : "' + this.params.catId + '" }',
contentType: 'application/json; charset=utf=8',
dataType: 'json',
success: function (data) {
self.editCategoryData({
CategoryID: ko.observable(categoryId),
CategoryName: ko.observable(categoryName),
UserList: ko.observableArray([])
});
self.editCategoryData().UserList(data.d);
}});
The method on the server doesn't get hit, and the success callback doesn't get hit either. When I add an error callback, the only information I get is the "Bad Request" error message.
Has anyone got any ideas?
So anyone else viewing this may try a solution to this problem. Try removing charset from your contentType. It worked for the problem above.
It could have to do with slight encoding differences between the two browsers, WCF may reject the incoming request given the encoding of the request doesn't actually match the encoding specified in the contentType. While this isn't a sure fire solid answer. It's the best I have.
Final Code:
$.ajax({
type: 'POST',
url: '/App_Presentation/BDM/RdmUserCategoryService.svc/GetUserCategoryUsersByCategory',
data: '{ "categoryId" : "' + this.params.catId + '" }',
contentType: 'application/json'
dataType: 'json',
success: function (data) {
self.editCategoryData({
CategoryID: ko.observable(categoryId),
CategoryName: ko.observable(categoryName),
UserList: ko.observableArray([])
});
self.editCategoryData().UserList(data.d);
}});

Issue posting a large amount of data when using json in a query string

I'm posting four JSON objects to the server using a jQuery ajax request. Each object can be up to 30k characters. When all of the parameters are large the last parameter or even the last two parameters do not show up on the server. Everything works fine when the parameters are smaller though.
In chrome's network tab I see all of the parameters in their entirety. In fiddler I see the parameters in their entirety but the parameters that don't show up on the server will not have a name.
Fiddler
The structure of my request is as follows:
var formData = "json0=" + JSON.stringify(json0) + "json1=" + JSON.stringify(json1); //etc
$.ajax({
type: 'POST',
url: url,
data: formData,
success: function (result) {},
error: function() {}
});
I wouldn't think there would be a limit on a POST but it's acting like the data is being truncated for some reason. Server side I'm in Java using ParameterAware to retrieve the data but I think the issue is before it gets there since fiddler doesn't have the parameters' names.
Query strings are not made for large amounts of data, you should pass your data to your Ajax call in an object:
$.ajax({
type: 'POST',
url: url,
dataType: "JSON",
data: {
json0: json0,
json1: json1
// etc
},
success: function (result) {},
error: function() {}
});
Have a look at this article discussing the maximum length of query strings.
jQuery AJAX documentation: http://api.jquery.com/jQuery.ajax/

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);
});
});

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

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

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

Categories

Resources