I try to retrieve a JSON object with jQuery from a server. Some properties of this object are arrays. When these arrays are not empty, I'm able to process my object. But when I retrieve a JSON like this one :
{"Id":144,"Identifier":"4000011","ContractId":115,"ContractName":"Test4","Meters":[],"Scans":[]}
where "Meters" and "Scans" are empty, jQuery raises an error... I query my server with this code :
$("#test").click(function () {
$.ajax({
type: "GET",
url: "/Gateway/GetDetails/144",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
...
},
error: function (jqXHR, textStatus, errorThrown) {
...
}
});
In the error handler, I can see my JSON object in the responseText property of the parameter "jqXHR". Did you encounter this problem ?
Thanks in advance !
The JSON you've supplied is valid (as confirmed by the JSON Lint tool); is it possible that the Server you are querying is returning an HTTP Error Status Code, or that an internal error is happening on the server side. You can confirm this by using a debugging proxy like Firebug, Chrome Developer tools.
I answer my own question... First I tested only with Internet Explorer 9; with an other browser, all worked as expected. After I cleared the Internet Explorer cache, the problem disappeared.
Related
This is the strangest bug I've encountered.
I submit an ajax POST that would retrieve some data.
$.ajax({
url: url,
data: data,
type: 'POST',
success: function(data){
console.log(data)
},
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}
)
In other version of IE and Chrome, the code would work fine and give the value of data which is {"success": true}.
But in IE8, data would return undefined . However, if I do JSON.stringify(data) , it would return {"success":true}.
I tried to convert the returned string to object via $.parseJSON(JSON.stringify(data) but it returned undefined again.
What can I do to get the response data as an object like I would normally in other browser?
EDIT:!! Found the solution. Apparently, the IE8 emulation of IE11 is a total crap and cannot display data correctly. Using IE8 on a virtual machine would correctly display the data and I figured out why it was undefined. Thanks for the help!
Found the solution! Apparently, the IE8 emulation of IE11 is a total crap and cannot display data correctly. Using IE8 on a virtual machine would correctly display the data and I figured out why it was undefined. Thanks for the help!
I'm not sure that you need to do that in IE8. Here is some code that I use with success in IE8 on a website that is live that is using jQuery 1.10.2:
$.ajax({
type: "POST",
crossDomain: true,
url: 'http://example.com/service/url',
data: params,
dataType: 'json',
timeout: 10000
})
.done(function( data ) {
console.log("Success");
console.log(data.success);
})
.fail(function( data ) {
console.log("Rejected");
console.log(JSON.stringify(data));
});
Hopefully this example is helpful for you to see how to handle the jQuery callback. The object that comes back is already an object if the result is actually valid JSON.
Updated this to be more generic of an answer.
I has encountered this problem when using jquery ajax on IE8 (not happen in IE9+, Chrome or Firefox). After researching for a while, still cannot figure out what was the problem.
A bit on the background, the website was built on Yii PHP framework, jQuery version is 1.8.3 (from Yii core). Here are my code:
$.ajax ({
url: url, // url = "/webapp/vote/apicreate"
type: 'post',
cache: false,
dataType: "json",
contentType: "application/json",
data: {
video_id : video_id,
vote_num : vote_num
},
success: function(response){
alert('success'); // for demonstration only
},
error: function(xhr, textStatus, err){
if (typeof console !== "undefined") console.log(textStatus);
}
}
Okay, with this I always received "Type Error: Could not complete the operation due to error 80070005". Both 'readyState' and 'status' are 0. A bit of frustration, cos I neither know what it mean nor how to fix it. Have tried to use the pure javascript solution which yields the same result...
Last thing to note is I'm on a Mac, testing IE8 using Wine. Can it be related somehow ?
Use the following steps to troubleshoot:
Change the url value to 127.0.0.1
Use alert(response.responseText) instead of 'success'
I have an issue with jQuery 1.7.2 and the ajax function, in that when I call the code below I get the following error in Firefox Firebug console:
NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments
[nsIDOMLocation.replace]
var weights= new Object();
// weight is then manipulated in here
$.ajax(
{
url: '/admin/countries/index.php',
data: ({action: 'sort', cid: cid, weights: weights}),
dataType: 'json',
success: function(data){
alert('suck-sess');
// do stuff in here
},
error: function (request, status, error) {
alert(request.responseText);
}
}
)
I'm not even certain that it's successfuly making the request as when I dump out $_REQUEST["action"] in my index.php PHP it comes through blank, when it should clearly be 'sort'.
When I execute the code I don't get the success or error alert, so I can't see where the error is coming from.
NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMLocation.replace]
This is the kind of internal errors thrown by gecko based browsers (firefox). I don't think it's related to your code. Seems to me more like a browser bug.
It turned out that weights was the problem, as you can see it was defined as a JavaScript object, however I had to use JSON.stringify(weights) to pass it through as a JSON-encoded string.
I'm pretty new to the web-dev world, and I'm having a bear of a time getting a simple jQuery.ajax call to work. Here is the call:
var url = "http://client.the_url.com/get_account_data.php";
$.ajax({
url: url,
dataType: 'json',
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:function (xhr, ajaxOptions, error){
alert("Error");
}
});
I can copy and paste the url into a browser and it renders what I would expect:
{
"id":"Level 3.xpusdscah",
"type":"Level 3",
"name":"xpusdscah",
"total":0,
"in":0,
"out":0
}
Instead, I get the Error alert every time. :/.
The php script I'm hitting starts with the header:
header('Content-type: application/json');
I was trying to pass params to the php script, but now I'm not even doing that. I would think this should be a 'no brainer', but if it is, then I have no brain. I'm trying to figure out how to use wireshark right now, but should I really need to use wireshark to debug a call that is as simple as it gets to a php file?
Can anyone help me? What I'm really hoping for is a "Well duh, you didn't do (insert obvious solution here)!
Thanks in advance,
Fledgling web developer
First, your callback function isn't helpful. It just shows the text "Error" every time. You want to actually display what the error is, like this:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:error(jqXHR, textStatus, errorThrown){
alert("Error:" + textStatus+ "," + errorThrown);
}
});
Your parameters for the error callback were named strangely. The documentation says the second param is a text error code, and the errorThrown is the HTTP status code provided by the web server. See the documentation here: http://api.jquery.com/jQuery.ajax/
Next, you'll want to grab a packet sniffer. This will allow you to inspect the packets going to and from the web server and see the error message that it is throwing. A good free option is Fiddler.
The data you're sending is not json.
var data = "login="+localLogin+"&pw="+localPassword+"&forAccount="+forAccount+"&forAccountType="+forAccountType+"&topAccount="+topAccount+"&fromDate="+fromDate+"&toDate="+toDate;
Should be something like this:
var data = '{"Key1":"' + Value1 + '","Key2":"' + Value2 .... + '""}';
And perhaps you should add the type as POST and content type like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: ....
try these:
inspect the Network tab on your console.
copy and paste the response and parse it in the console command line to verify the JSON is well formed.
show more verbose error description.
I have this jQuery code:
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
// ? :)
alert (dataString);
},
error : function(data)
{
alert("ajax error, json: " + data);
//for (var i = 0, l = json.length; i < l; ++i)
//{
// alert (json[i]);
//}
}
});
And when I use it, I get in the alert something cryptic like this: object XMLHTTPReqest
How do I actually get the value that was passed in from the AJAX?
Thanks!
In a couple ways:
console.log(data); // allows you to view your object in a tree in the console
or
alert(JSON.stringify(data)); // alerts a serialized string of the object
or in chrome/safari and firefox (firebug) set a break point and check it out.
have you tried using the Firefox plugin called FireBug? That's the first place I start as it will show you the exact structure, and data, of the json object returned.
from there it's a simple matter of coding in the object names etc.
Firefox - Download Firebug. A must for any web dev.
Chome: instead of alert, do "console.log(data);" This should spit out the object and you can view its properties in the console (hit F12 for that).
Alternatively, write "debugger;" right before your alert and the browser will pause execution. You need to have Firebug running or Chrome Dev Tools open.
I assume you're talking about the error handler.
The signature for the jQuery AJAX error handler is
error(jqXHR, textStatus, errorThrown)
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred
You cannot get the "data" returned as there is no data, just an error.
First, you're alerting dataString, not anything returned from the server, at least in the success callback. .ajax() callback signatures look like this: success(data, textStatus, jqXHR), so if you're getting real data back, it can be accessed like any JSON object, via the data parameter. In error it's error(jqXHR, textStatus, errorThrown), so if that's what you're talking about, it kind of makes sense.
Use Firebug/Chrome/proxy/etc. to make sure what you're getting back from the server is what you expect, or just log it to the console.