Trying to get JQuery to post JSON to a server:
$.ajax({
url: "/path/to/url",
type: "POST",
dataType: "json",
contentType: "json",
data: {"foo": "bar"},
success: function(){
alert("success :-)");
},
error: function(){
alert("fail :-(");
}
});
Problem is the data appears on the server as "foo=bar" rather than the desired "{\"foo\":\"bar\"}.
I thought specifying either the dataType or contentType params would do the trick, but no.
Anyone know the correct ajax configuration ? [or alternatively a way of serialising the 'data' parameter as JSON prior to posting ?]
Thanks!
You could use json2.js:
data: JSON.stringify({"foo": "bar"})
Datatype is for returned data. Contenttype is not applicable, see here
It can only send strings, I use JSON.stringify on my created javascript objects, in your case you could just manually code the string.
You will also need to access the string on server side, for that if you are using java I can recommened google's gson
Related
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
I am trying to send an JSON object to my webservice which is expecting JSON in the request data.
This my POST call from angularJS
$http({method: 'POST',
url: 'update.htm',
data: $.param($scope.cover),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data) {
// handle
});
Value for cover object
$scope.cover = {id:1, bean:{id:2}}
Iam getting 500 (InvalidPropertyException: Invalid property 'bean[id]' of bean class [BookBean]: Property referenced in indexed property path 'bean[id]' is neither an array nor a List nor a Map;)
In network, it is sending in this way
bean[id]:1
I think it should send like
bean.id:1
How to reslove this issue. Thanks in advance
Looks like the data is getting to the server and is causing an error there. There's a possible duplicate question that's been answered here - Post Nested Object to Spring MVC controller using JSON
Try posting your data like:
$http({method: 'POST',
url: 'update.htm',
data: $scope.cover,
}).success(function (data) {
// handle
});
so I can't seem to get my dropdown menu to work. Here's the code:
$.ajax({
url:"/json/testjson",
cache:true,
success: function(j){
console.log(j);
alert(j);}
});
This returns a valid json string:
{"data": ["test", "data"], "result": "OK"}
I can't get the success function to fire at all. There is no error anywhere (neither in the firebug log, nor in the netlog, and the response from the site is okay. The firebug parser cannot parse that JSON but the JLINT validator validates it correctly. I have tried the setting the content-type to application/json, no success. I have also tried, $.getJSON, $.get, and nothing is firing. I have also tried
Any ideas?
Thanks
Jon
Thank you HaBo - the answer was to remove the cache: true!
Thanks!
J
I believe you need to set dataType to json to make sure the data coming from the server is treated as a json object.
$.ajax({
url: "/json/testjson",
dataType: "json",
cache: true,
success: function(j) {
console.log(j);
alert(j);
}
});
Take a look at the $.ajax API.
I am using Jquery Ajax for calling the methods in controller, but i am always getting invalid json primitive error.
Below is the Code.
Client side Code
$("#something >li").each(function () {
widgetsobj.push({
WidgetId: $(this).attr("dbid"),
ColumnNumber: 2,
RowNumber: 3,
WidgetType: "Graph",
WidgetName: "ddd",
PageName : "Page1"
});
});
$.ajax({
url: "/Home/ABC",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
data: { pagename1: pagename, widgetsobj1: JSON.stringify(widgetsobj) },
success: function (data) {
alert("ss");
},
error: function (data) {
debugger;
}
});
at controller
[HttpPost, ValidateInput(false)]
public JsonResult ABC(string pagename1, List<XYZ> widgetsobj1)
{
// do something
}
Note XYZ is object with below properties.
WidgetId
ColumnNumber
RowNumber
WidgetType
WidgetName
PageName
So please let me know where i am wrong.
The thing about ajax is that it is very picky about what you send through. You need to make absolutely sure that everything is in the correct format.
i.e. you are using double quotations (") rather than single (') and so on.
The best thing to do, would be to use Firebug or a similar console to view the POST as it is executed or to use alert() to view the POST data before it is sent off. That way you can identify where the problem is.
Remember, when you use json.stringify() it is going to turn whatever you feed it into what it believes will be an acceptable JSON string and because it is just a string there could be syntax errors at any point!
From what I can see here, there may be an issue at:
data: { pagename1: pagename, widgetsobj1: JSON.stringify(widgetsobj) }
You may want to try:
data: { "pagename1": pagename, "widgetsobj1": JSON.stringify(widgetsobj) }
I got the same error. My solution was to add:
dataType: 'json',
to the ajax call. Looks like you already had that in in your ajax call. But Hope this helps someone else.
Ok, I'm a bit new when it comes to jQuery and json. If I'm using json as my return type, can I still retrieve responseText from an XMLHttpRequest object?
here's the code that i'm using:
json response: {"clients": []}
$.ajax({
type: "POST",
url: "/myurl/whatever.php",
data: myData,
dataType: "json",
success: function(msg){
status.html(msg[0]);
},
error: function(msg) {
status.html("Error: " + msg[0]);
}
});
is the use of msg[0] correct if i want to output the json response or am i missing something?
how can i still use the above code with XMLHttpRequest to get the status, responseText, etc.
thanks, all!
As far as I know, the call to $.ajax returns a XHR object, and from that the responseText can be extracted, e.g.:
var xhr = $.ajax( {
url:' someInfo.php',
data: 'which=squirrels',
asynch: true
} );
var resp = xhr.responseText;
The response text will contain a json string, which would need to be converted to an object to be of any use.
If you want to use the response as a json object directly within your success: function, do as #cloudhead suggested, and use msg. The dataType : "json" in your options takes care of the conversion for you.
If you're using json, then you get a json object back, not an XML object. You can output it directly, without using [0].