Wrapped $.ajax issue - javascript

$.ajax is wrapped into new 'get' function.
If there is only one 'get' invoke in js file, it is fine.
But 2 calls in row fail.
More precise,
first call fails with "Uncaught ReferenceError: process is not defined",
second one is successful, BUT in success function it has data for first 'get' invoke.
As I can guess, there is some issue with 'this'/context. Could you explain it to me?
(function() {
"use strict";
function get(url, success, error) {
$.ajax({
type: "GET",
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'process',
url: url,
success: success,
error: error
});
}
get('XXX',
function(data, textStatus, jqXHR) {
console.log("SUCCESS PING 1");
console.log(data);
},
function(jqXHR, textStatus, errorThrown) {
console.log("ERROR PIND 1");
});
get('YYY',
function(data, textStatus, jqXHR) {
console.log("SUCCESS PING 2");
console.log(data);
},
function(jqXHR, textStatus, errorThrown) {
console.log("ERROR PING 2");
});
})();
/*
===========================================
===============console=====================
===========================================
1. ERROR PIND WAR
2. Uncaught ReferenceError: process is not defined
at db?callback=process&_=1485184752755:1
3. SUCCESS PING DB
4. Object {data for first call here}
*/

First of all, It's better do NOT specify a custom callback name ('jsonpCallback' parameter)
http://api.jquery.com/jQuery.ajax/
jsonpCallback Type: String or Function() Specify the callback function
name for a JSONP request. This value will be used instead of the
random name automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests. As of jQuery 1.5, you can also use a function for this
setting, in which case the value of jsonpCallback is set to the return
value of that function.
The thing is, that jQuery creates global function in window object with specified name and later remove it.
I didn't manage to get full picture of what going on inside jQuery library, but
the issue is definitely caused by fact that it tries to call function that just has been removed.
Removing jsonpCallback param resolve an issue

Related

Error or fail not being reached when Ajax fails to fetch JSON

I am working on below Ajax code in JavaScript, I am trying to pop up a dialog box when the URL could not load the JSON properly the reason may be either expired token or incorrect token, in any case, I am expecting the code to hit the error or fail but it's not happening. When the URL could load the JSON successfully, success and complete blocks are being hit as expected but nothing is being hit when URL fails. I have tried to use async: false and tried to check with a boolean variable weHaveSuccess but console.log(weHaveSuccess); which is in the last line of the code is getting executing even before success/error is being executed and it seems to me like its still loading asynchronously. I would like to know why error block is not being hit when the JSON load from URL is getting failed.
My code
function checkUser(myURL, newAccessToken, weHaveSuccess) {
$.ajax({
type: "GET",
dataType: "jsonp",
async: false,
url: myURL + newAccessToken,
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
},
success: function (data) {
console.log("Hello 2 " + JSON.stringify(data));
weHaveSuccess = true;
console.log('Message from Success ' + weHaveSuccess);
},
complete: function () {
console.log('Message from Complete ' + weHaveSuccess);
}
}).done(function (data) {
alert("Success");
console.log(data);
}).fail(function (data) {
console.log(data);
alert("Failed");
}).always(function () {
alert("In Always");
});
console.log(weHaveSuccess);
}
Thanks in advance!
AJAX requests are asynchronous. It takes time for a remote request to be made and responded to. You will have to write your post-response code within the success function or call another function from there, not within the same scope as where the call is initiated.
I am taking a bit of a guess here about what your server returns on failure. An AJAX request success means simply that a 200 OK response was received, without any consideration of the contents of the data. If an error is simply a change in the data you will need do one of the following to show an error:
Have the server set a status code header on failure, perhaps 400 Bad Request.
In the success function look within your data for whatever error response you are expecting and trigger the alert() there.
First of all the console.log(weHaveSuccess); fires first, because the $.ajax() is asynchronous while console.log is not so ajax will be triggered and return the promise when finishes, but the browser will continue with the script.
In the jQuery ajax docs says:
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation.
It's hard to debug without seeing the response, maybe you can add some info from the network or a URL?
How about if you try the following:
Add the jsonp setting to your $.ajax() function for the callback that will handle the response and console.log there:
function myCallback(data) {
console.log(data);
}
$.ajax({
type: "GET",
dataType: "jsonp",
jsonp: myCallback,
...

parse error callback function not called jquery ajax error?

I have been trying all the methods that i have seen in the stack overflow asked by other users before.But none of them are working.Please hoping any of you would point me in the right direction
$.ajax({
type: "get",
dataType:'jsonp',
params:jsonData,
jsonp:false,
jsonpCallback:"callbackfn",
headers: { "api_key": "u5FocU4xLq2rBfZ1ZSV8o81R2usYzUEM3NaCinnV"},
url: "http://localhost/url?name=xxx&email=xxxxxx#gmail.com",
success:function(){
alert("sucess function");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + " and<br> " + errorThrown);
}
});
function callbackfn(data) {
alert(data);
}
the response is {
"firstName":"John",
"lastName":"Doe"
}
Although the response is json,this rises an error
Parse error .callbackfn not called.
In order to use a custom callback function with JSONP, you must declare its scope to be global, i.e.
window.callbackfn = function(data) {
alert(data);
};
Why?
This is because successful JSONP responses return a new JavaScript file, that is, a JavaScript function call encapsulated in <script> tags. Since each script is independently evaluated in the global scope, any script's function you would like to be made available to another script must also be declared in the global scope. Thus all JSONP callback functions should be global.
EDIT
According to OP, the solution found here: Return JSONP via AWS Lambda/API Gateway did the trick. Issue had to do with an improper server-side JSONP response.
Make sure that your response from the server is a function call with the response data as the argument. It appears you are just outputting JSON, but JSONP expects a function call with the response data. Your server response should look like this:
callbackfn({
"firstName":"John",
"lastName":"Doe"
});
You have jsonp: false with a jsonpCallback and dataType: 'jsonp' - which is odd, because you are also supplying a jsonp callback. Perhaps if you don't need JSONP due to cross-origin requests, you should remove the jsonpCallback argument and just manually call that function with the response:
$.ajax({
type: "get",
dataType:'json',
params:jsonData,
headers: { "api_key": "u5FocU4xLq2rBfZ1ZSV8o81R2usYzUEM3NaCinnV"},
url: "http://localhost/url?name=xxx&email=xxxxxx#gmail.com",
success:function(data){
callbackfn(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + " and<br> " + errorThrown);
}
});

Getting "parsererror" in jquery ajax

Below is my AJAX code. Here I'm hitting a service with one value. The service is getting called successfully, but it is not going into the success method. It is going into the error method only. In the error method it is giving parsererror and message: Unexpected token S
$.ajax({
type: 'GET',
url: 'http://domin.com:9000/ramsweb/rest/DetailRest/addOrderContacts/123456/' + customerId,
success: function (data, status, xhr) {
console.log(data);
$("#loadingSpinner").hide();
},
error: function (jqXhr, textStatus, errorMessage) {
$('.ErrorMsg').html('<h5>An error has occurred</h5>');
},
fail: function (data) {
$('.ErrorMsg').html('<h5>data loading failed</h5>');
}
});
jQuery AJAX functions by default will try to detect the type of response depending on other pieces of data in your request and response (headers etc.)
Most likely, your endpoint serves it as JSON thus telling jQuery to internally do a JSON.parse. However, your endpoint may be serving an error page instead of JSON which can cause parse errors like this.

Is there any analog to a 'finally' in jQuery AJAX calls?

Is there a Java 'finally' analogue in jQuery AJAX calls? I have this code here. In my always I throw an exception, however I ALWAYS want it to go to the then() method.
call.xmlHttpReq = $.ajax({
url : url,
dataType : 'json',
type : 'GET'
}).always(function(processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {
throw "something";
}).then(function() {
alert("i want to always run no matter what");
});
I have tried to use done(), complete(), and the another always(), but nothing seems to work.
Here is JSFiddle :
http://jsfiddle.net/qv3t3L0m/
See this example:
$.ajax({
type: "GET",
dataType: dataType,
contentType: contentType,
async: TRUE,
url: $('html form:nth-child(1)').attr('action') + "?" $('html form:nth-child(1)').serialize(),
success: function(data) {
console.log("FUNFOU!");
},
error: function(data) {
console.log("NÃO FUNFOU!");
},
complete: function(data) {
console.log("SEMPRE FUNFA!");
//A function to be called when the request finishes
// (after success and error callbacks are executed).
}
});
For more informations: http://api.jquery.com/jquery.ajax/
.always() should work. See the The jqXHR Object section at http://api.jquery.com/jQuery.ajax/.
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { });
An alternative construct to the complete callback option, the
.always() method replaces the deprecated .complete() method.
In response to a successful request, the function's arguments are the
same as those of .done(): data, textStatus, and the jqXHR object. For
failed requests the arguments are the same as those of .fail(): the
jqXHR object, textStatus, and errorThrown. Refer to deferred.always()
for implementation details.
See also http://api.jquery.com/deferred.always/
The below suggestions will not work in jQuery, because jQuery's promise implementation does not handle errors thrown in methods passed to then. I am only leaving them here as an illustration of what could be possible if jQuery was promises/A+ compliant. As Bergi rightly points out, you will have to manually wrap your code in your own try catch block.
call.xmlHttpReq = $.ajax({
url : url,
dataType : 'json',
type : 'GET'
}).then(function(processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {
throw "something";
}).always(function() {
alert("i want to always run no matter what");
});
Although I'm not sure if jquery's promise supports always, an alternative would be to use then (again) and pass the same function as both successHandler and errorHandler, like this :
call.xmlHttpReq = $.ajax({
url : url,
dataType : 'json',
type : 'GET'
}).then(function(processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {
throw "something";
}).then(function() {
alert("i want to always run no matter what");
},
function() {
alert("i want to always run no matter what");
});
Just a note for those who use jQuery 3.0 and later
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
As in official documentation
There is a bug ajax is dependent on the server, need to check status with "complete" is the best, a kind of "success", "error" and others are not 100% of the PUT, POST and GET ... look at an example
$.ajax({
url: '/api/v2/tickets/123456.json',
....
....
....
complete: function(data) {
if (data.statusText == "success") {
console.log("Sent successfully");
} else {
console.log("Not Sent");
}
}
});
Sorry bad english! Cheer ;-)
if you want one code definition for all ajax requests, you can do it like this
$(document).ajaxComplete(function () {
console.log('ajax complete on doc');
})

how to get jquery ajax status code

I want to know that how can we get ajax status code in jquery.
I have this ajax block:
$.ajax{
type: "GET",
url: "keyword_mapping.html",
data:"ajax=yes&sf="+status_flag,
success: callback.success,
complete: rollup_filters(),
failure: function(){
alert("Failure");
}
}
Now in above code, in case of failure, how can i get ajax status code and some description of that status code ??
You want to use the error option to capture this. For example:
error: function (jqXHR, textStatus, errorThrown)
// Your handler here...
}
You can then use the jqXHR object to retrieve information about the failure.
From the documentation:
For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:
readyState
status
statusText
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
getAllResponseHeaders()
getResponseHeader()
abort()
First, you have a few syntax errors. The above is a method call, so it needs to follow $.ajax({ ... }); (with parenthesis).
Secondly, you want to supply the error property as part of the object, not failure (see docs for more information).
Third, when you do bind to an error, you are supplied three parameters: jqHXR, textState, errorThrow. These arguments will supply you the details of a failed AJAX call. (More specifically, try jqXHR.status)
Alternatively, you can bind to the $.ajaxError function as well.
Update To keep this more up-to-date, you should now be following the Deferred API (as of jQuery 1.5), which would make binding to an error look something like the following:
$.ajax({ /* options */ })
.done(function( data, textStatus, jqXHR ){
// here you bind to a successful execution.
.fail(function( jqXHR, textStatus, errorThrown ){
// Here you can catch if something went wrong with the AJAX call.
})
.always(function(){
// here you can execute code after both (or either) of
// the above callbacks have executed.
});
Change your failure callback to
error:function (xhr, options, error){
alert(xhr.status);
alert(error);
}
There is nothing like failure in ajax settings. Replace failure by error and you get 3 arguments in the error callback. First argument is the xhr object which has a status property in it.
$.ajax{
type: "GET",
url: "keyword_mapping.html",
data:"ajax=yes&sf="+status_flag,
success: callback.success;
complete: rollup_filters(),
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.status);
}
}

Categories

Resources