jQuery.ajaxSetup() Is Being Ignored - javascript

In a JS file I have this:
$.ajaxSetup({
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
}
});
Then further on in the file I instantiate an object that has an AJAX call in it's constructor to fill out some values.
function RequestViewModel() {
var self = this;
(...)
// Initalization Methods
$.ajax({
url:ajaxAddress + 'LoadStates',
success: function (data) {
debugger;
}
});
}
var model = new RequestViewModel();
However, when the ajax call is made in the code, 'xml' is being used as the dataType instead of JSON. This is causing my web service call to break and I always get sent to the error callback of the AJAX call. If I move the settings inside the actual AjAX call, the call works and data is returned from the server. For some reason, the global setting isn't being honored.
My question is why isn't this working? I've used this same technique several other times without this problem.
I'm using jQuery version 1.7.1.
UPDATE
It seems like the problem is on line 7517 of the jQuery file. It is doing an IF statement that is being evaulated to false and is skipping over setting the correct Content Type in the request header.

Try putting your .ajaxSetup inside a document ready wrapper.(NOT likely the cause though)
Try using jQuery.ajaxSetup instead of $.ajaxSetup
It is recommended that global event handlers not be in the ajaxSetup. move error: to $.ajaxError( instead:
jQuery.ajaxError( function (e, jqxhr, settings, exception) {
alert(settings.url + " Failed");
});
Example if you have a div with a log class (puts some text in if any error occurs:
$("div.log").ajaxError(function() {
$(this).text( "Triggered ajaxError handler." );
});
NOTE: when you refactor, make sure to remove the LAST comma.
Also, if you are using the latest version of jQuery (1.7.1 at the moment) you can simplify:
contentType: "application/json; charset=utf-8",
to
contentType: "application/json",
EDIT: quick, dirty global handler:
$(document).ajaxError(function(e, xhr, settings, exception) {
alert('error in: ' + settings.url + ' \\n'+'error:\\n' + exception);
});
EDIT2: SOME resources also put an empty data set sent as: (with quotes)
data: "{}",

Where is .ajaxSetup() being called? Are you using any other plugins? It's possible some other library is misbehaving and overwriting your options.

Related

Javascript, Cannot read property of undefined, but prints to console

I have a jQuery call which is getting the data in to a object.
I'm trying to use the object value to set as a label text from javascript, but it throws
"Cannot read property '0' of undefined."
where as it prints the value successfully to the console.
var questionData;
var optionData;
$(document).ready(function () {
$.ajax({
url: 'coaching-assessment-tool.aspx/GetCATQuestionAndOptions',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
questionData = data.d[0];
optionData = data.d[1];
console.log(questionData[0].QuestionText);
console.log("Question Data", questionData);
console.log("Option Data", optionData);
},
error: function (error) {
console.log(error);
alert('Error retrieving data. Please contact support.');
}
});
document.getElementById('firstQuestion').innerHTML = questionData[0].QuestionText;
});
I need the label text as the object value (questionData[0].QuestionText).
$.ajax() is asynchronous by default, so setting innerHTML is happening before questionData is populated. Move line 22 inside the success callback to make sure the data is available before it is used.
While it's technically possible to make the call synchronous, it's a bad idea.
$.ajax({
// ...
async: false,
// ...
});
That code would prevent any other JavaScript from executing until the ajax call is complete.
Just as an aside, some JavaScript tooling like TypeScript can help you catch those mistakes before the code executes in a browser. I've recently converted some JS to TS and been very happy with the number of bugs I've caught.
Cheers!

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/

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

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

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.

A quick question on data returned by jquery.ajax() call (EDITED)

EDIT: The original problem was due a stupid syntax mistake somewhere else, whicj I fixed. I have a new problem though, as described below
I have the following jquery.ajax call:
$.ajax({
type: 'GET',
url: servicesUrl + "/" + ID + "/tasks",
dataType: "xml",
success : createTaskListTable
});
The createTaskListTable function is defined as
function createTaskListTable(taskListXml) {
$(taskListXml).find("Task").each(function(){
alert("Found task")
}); // each task
}
Problem is: this doesn't work, I get an error saying taskListXml is not defined. JQuery documentation states that the success functions gets passed three arguments, the first of which is the data.
How can I pass the data returned by .ajax() to my function with a variable name of my own choosing.
My problem now is that I'm getting the XML from a previous ajax call! How is this even possible? That previous function is defined as function convertServiceXmlDataToTable(xml), so they don't use the same variable name.
Utterly confused. Is this some caching issue? If so, how can I clear the browser cache to get rid of the earlier XML?
Thanks!
See my comment. If you're using IE, GET AJAX requests are cached. jQuery can solve this for you by adding a random querystring variable to the request. Simply change your AJAX call to this:
$.ajax({
type: 'GET',
url: servicesUrl + "/" + ID + "/tasks",
cache: false,
dataType: "xml",
success : createTaskListTable
});
That will add the random querystring automatically, thus preventing the browser from caching the request.
Try defining your callback inline like this:
success: function createTaskListTable(data, textStatus, xhr) {
console.dir(data, textStatus, xhr);
}
If data is indeed being returned as null, you might get some insight from the other fields, especially xhr.
Note that error callbacks get called with (xhr, textStatus, errorThrown).

Categories

Resources