jQuery $.ajax call works in Chrome, but not any other browser - javascript

The following call works perfectly in Chrome, but fails in every other browser.
function getInfo(r,c,f){
return $.parseJSON($.ajax({
url: baseURL + 'somethingAPI/getInfo',
data: {
"data_r": r,
"data_c": c,
"data_f": f
},
//success: function(data){},
dataType: "json",
async: FALSE
}).response);
}
Yes, I'm using a synchronous ajax call and I believe it is necessary as I don't want any of the other JS to run without this executing and returning data. Although, I'm not entirely sure if something else should be happening with the success callback.
Anyway, in Chrome I get the response object (JSON) and can access the data within just fine.
Does anyone know what I'm doing wrong?

Regarding your point about not knowing how to avoid async: false, is this something like what you're looking to accomplish?
function getInfo(r, c, f, callback) {
$.ajax({
url: baseURL + 'somethingAPI/getInfo',
data: {
"data_r": r,
"data_c": c,
"data_f": f
},
dataType: "json",
success: callback,
});
}
getInfo('foo', 'bar', 'baz', function(response) {
console.log(response);
});

Rather than parsingJson on the ajax query, here's the syntax I use to conquer these challenges
$.ajax({
url: "pagegoeshere.php",
timeout: 30000,
type: "POST",
data: 'data1='+data1+'&data2='+data2,
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown)
},
success: function(returnjson){
var returnstuff = returnjson.returnstuff;
//Do next Javascript step here
}
});
You can run ensuing javascript/jquery in the success and "stack" events together on success of your Ajax call. That way, if it works, it proceeds. Otherwise, the error handling can occur in the provided error section in a manner that you define. I generally fire my ajax calls on a click handler, but it's certainly doable to run it in a function as you have chosen. Be sure to check your return JSON (could be mailed from your processing page, for example) to make sure it's valid JSON. Jsonlint is your friend!
I've had chrome effectively parse bad HTML and JSON while the other browsers don't on several occasions. I'd suspect it's something along those lines that's specifically causing your issues.

Related

Getting json on cross domain with jsonp using jquery

I have a very simple $.ajax call that is suppose to get the json data from a given url. Currently the url does get called and the data does get returned, however the localHsonpCallback function doesn't seem to get fired.
Here is my code.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
}
function localJsonpCallback(json) {
console.log("Fired");
if (!json.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
So as mentioned above for some reason the localJsonpCallback doesn't seem to get fired at all.
Also I should mention that in my Chrome Dev tools the request link ends up looking like this for reason
http://localhost/api/users?callback=localJsonpCallback&_=1429708885454
Any help in this question would be greatly appreciated.
Thank you.
Try the callback method as an anonymous function directly inside the parameter list.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: function(data){
console.log("Fired");
if (!data.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
});
}
If youre not appending the callback onto the url you can set the jsonp oprion to false and then, as you are doing, set the callback in the options.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonp: false,
jsonpCallback: "localJsonpCallback"
});
}
Since javascript is sequential its also a good idea to define your functions before theyre called. ie - define your callback function before your ajax call.
http://api.jquery.com/jQuery.ajax/
jsonp
Type:
String Override the callback function name in a JSONP request.
This value will be used instead of 'callback' in the 'callback=?' part
of the query string in the url. So {jsonp:'onJSONPLoad'} would result
in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the
jsonp option to false prevents jQuery from adding the "?callback"
string to the URL or attempting to use "=?" for transformation. In
this case, you should also explicitly set the jsonpCallback setting.
For example, { jsonp: false, jsonpCallback: "callbackName" }
Maybe this piece of code it will help solve your problem:
$.ajax({
type: 'GET',
url: 'http://localhost/api/users',
data:{todo:"jsonp"},
dataType: "jsonp",
crossDomain: true,
cache:false,
success: success,
error:function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
//your code here
};
This either a server side problem that the callback parameter is not used properly or the parameter name callback does not exist for the server side they are looking for something different.
You said the result is returning, what is the format? JSONP must return a script block not pure data so be sure the result is in below format.
{callbackFunctionName}({hugeDataFromServer});
Basically it is script that calls your function.
if it is not the server side that means it is more likely they are using a different name for callback parameter e.g. cb , _callback etc

Ajax jquery call to GET application/x-javascript

How do I get content of "application/x-javascript" using jquery Ajax call?
As it keep getting me null content.
What I am trying to use for now:
$.ajax({
dataType: "json",
contentType: "application/x-javascript;charset=utf-8",
url:the_url,
async:false,
success:function(r){
console.log("el result" + r) ;
response = r;
}
});
This:
dataType: "json",
tells jQuery to ignore what the server claims it is sending back and to process the result as JSON. JavaScript isn't JSON, so this breaks it.
Remove that line.
Then you should get the data in the success function.
Asides:
This:
contentType: "application/x-javascript;charset=utf-8",
claims you are sending JavaScript. You aren't making a POST request, so you aren't sending anything. Remove it.
Even if you were sending JavaScript to the server, the application/javascript MIME type hasn't been experimental since 2006, so it shouldn't have the x- prefix on it.
async:false, is a terrible idea. It locks up the JS event loop waiting for the response. You shouldn't use it.
response = r;: assigning data to globals is usually a terrible idea. Process the data in the success event handler instead.
Try this out :
$.ajax({
url: 'my/url',
type: 'GET',
data: 'test=mytest&test2=mytest2',
success: function (data) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
And read the documentation, to see what each parameter is made for :
http://api.jquery.com/jquery.ajax/

Timeout not working in ajax post request

I am not able to make ajax error callback function of after 3 seconds. I tried with timeout, but it will not switch to error callback after specified time! I am not able to get the alert Got timeout.
When I referred similar questions in this site with similar problems it didn't helped out. They all use ajax GET type. I am using jquery 1.10.1 library.
script :
$.ajax({
type: 'POST',
timeout: 3000,
url : "http://mydomain/Services.asmx/Best_Scores",
dataType: "text",
async:false,
crossDomain:true,
data: "strJsonRequest="+scoredata,
success: function (data) {
// Success code ...
},
error: function (data, textStatus, errorThrown) {
if(textStatus == "timeout") {
alert("Got timeout");
}
}
});
Any solution ?
Fix :
Change async : false to async: true
Reason :
A synchronous AJAX call blocks until the request has been finished. Implementing a timeout is not possible for technical reasons, because the AJAX call would have to be executed later.
If an AJAX call is executed later, the function somehow has to implement a blocking feature, to stop the code from running further after the AJAX call, and execute it again after a timeout - not possible.
Today, (in 2019) I still have this problem.
I have an ajax call too long (depending from Date Start-> Date End) php script.
and after some minutes I get error 500, async: true don't help.
The call is:
$.ajax({
type: "GET",
dataType: 'json',
url: 'mymscript.php',
contentType:'application/json;charset=UTF-8;',
data: $('[name="myForm"]').serialize(),
async:true,
timeout:0,
success: function(response){
...
I resolved using:
side PHP:
set_time_limit(0);
ignore_user_abort(true);
at begin of script.
echo ' ';
flush();
ob_flush();
in the middle of script (for example in main loop every day). This help to let client to don't disconnect (I think that is the main problem).
Using this I continuosly write spaces befor the final json.
Fortunately jquery trim spaces before to parse the json and, in the end, the json is valid.
So I can catch response object to know if script is ended with errors or warnings.
I Hope this help somebody.

Catch / Handle 502 Bad Gateway Error

I have to update a large collection so I am calling in a loop an web api. I use jQuery.ajax()
Something like this:
$.ajax({
type: 'GET',
url: 'http://www.somesite.com/API/API.php',
jsonpCallback: 'API_SC4',
contentType: "application/json",
dataType: 'jsonp',
data:'action=update&page='+collection[currentIndex].name+'&callback=API_SC4',
async:false,
success: function(data) {
//use data for update of collection[currentIndex]
UpdateNext(currentIndex+1);
},
error: function(e) {
//interpret error
UpdateNext(currentIndex+1);
}
});
The problem is the collection is quite large and sometimes I get a 502 Bad Gateway error and the ajax error handler is not called.
I even tried $( document ).ajaxError() but i'm doing a cross-domain jsonp call , and it seems .ajaxError() does not get called in that situation.
Is there any way to handle that error? Something at window level?
I can see the error in the Chrome development console , and I was thinking there might be a way.
Thanks
Yes, there is: statusCode. See the jQuery documentation on AJAX for details.
Simple example:
$.ajax({
statusCode: {
502: function () {
alert('Fail!');
}
}
});

What happens when wrong dataType is returned

I perform a call
$.ajax({
type: "POST",
url: url,
data: dataToPost,
dataType: "json",
success: function(data, textStatus){ /*something*/ },
failure: myHttpReqErrorHandler
});
In certain cases when things goes wrong on the server I get
Content-type:text/html; charset=UTF-8
type, and content is a real HTML page, and there is not much I can do about that. I want to manage this case on JavaScript, but when this happens no callback is called on jQuery side (neither success nor failure).
Is there a further parameter to pass to ajax to handle that?
The error handler is error: function(){}
error: myHttpReqErrorHandler
It will throw a parse error(parsererror) if the content is not a parsable json format.
Demo: Fiddle

Categories

Resources