Can't correctly read response of API call (JS) - javascript

I'm calling an API and getting results back as expected in JavaScript. If a 400 status is returned, I call another API, which I'm doing with an if statement. However, this "if" is never triggered, I think because the way my response is getting read. My code is:
var getSearchPrimary = {
url: 'SEARCH_URL',
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
context : this,
cache : true,
timeout: 60000,
success : function(e) {
status = JSON.stringify(e.status.code);
if(status === "400"){
console.log("failed");
this.getSearchSecondary(query);
}else{
console.log(JSON.stringify(e));
}
In this case, when I do console.log(status); I get "400" so I'm really not sure why my if statement is never firing!
The response is:
{"status":{"code":"400","message":"Error: No results match the query"},"response":{"results":""}}
I've been staring at this a while now, and would really appreciate any insight!!

The "success" method is called when the request is successful. When 400 is returned, that's not a success. Use the "error" property instead to provide a function that is executed when the request fails.

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,
...

How to handle a long request?

I have an ajax request that may take a long time to return a response.
$.ajax({
type: 'POST',
url: 'some_url',
data: data,
processData: false,
contentType: false,
headers: {
"Authorization": 'Token token="'+some_token+'"'
}
}).then(function(){
do_something();
});
If the request takes a few minutes then everything works as expected. But if the response takes more than about 10 minutes; I get the following error:
jquery.js:9175 POST 'some_url' net::ERR_EMPTY_RESPONSE
But on the server, I can still see that my request is being processed. When that process is finished, I can see that it sends a Completed 201 Created ... response. But I believe since the error is encountered there is nothing listening for the response.
I would like to let the user know the process is finished.
Does any one know the 'best practice' way of handling this?
Any help would be greatly appreciated.
Since Ajax is assynchonized, I like to apply a promise. From the top of my head i believe this works like follows:
function send_ajax(url, data, some_token) {
var ajax = $.ajax({
type : 'POST',
url : url,
data : data,
processData : false,
contentType : false,
headers : {
"Authorization" : 'Token token="' + some_token + '"'
}
})
return ajax.promise();
}
send_ajax("url","data","some_token").done(function(result) {
console.log(result);
do_something();
});
The result is promised and when returns will execute the function inside done. 10 minutes does seem like an awful long time.
edit: not the solution
As I was pointed out the original Ajax call stays within its context. Meaning that the then() method will handle the returned call. My opted solution does not apply to the OP problem.
For reference, the opted solution does handle the asynchronous hurdle when the ajax logic is placed in its own function with a returned value.

Jquery ajax response not calling Success method

I am pretty much new to ajax and working on jquery ajax request. Ajax callback is not calling success method. Interaction is between cross-site domains.
My AJAX request looks like
$.ajax({
timeout: 20000,
url: 'test.com',
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
console.log('callback success');
this._cache = data;
localStorage.token = data.access_token;
} });
There are no errors in this call.
This ajax request is not calling success function.Request is returning json data. it's just success method is not getting called.
This ajax request is not calling success function.
Get request is getting fired successfully. I can even trace the response in fiddler with 200 http response.For some reason success method is not getting called.
it's returning json object, which I've traced in fiddler
You're telling jQuery to expect a JSONP response, so it is trying to execute the JSON document as if it were a JavaScript script (because that is what JSONP is). This fails because it is not JSONP.
Either return JSONP instead of JSON or (assuming the server returns the correct Content-Type) remove dataType: 'jsonp',.
ok... I came here with the same problem... and when I read that specifying datatype:jsonp never calls success as a callback per #mondjunge from a comment above, it started me thinking about some behavior I saw earlier from my code and that maybe datatype:json might have the same behavior for what ever reason here too.
So after reading this page I took out my datatype declaration from my ajax request and my servlet returned the proper data payload, returned a 200, and jquery called the success function finally and modified my DOM.
All those steps happened except the last one until I removed my datatype from my ajax call. NOT what I was expecting!
Hopefully someone else can shed some light on why this happens... for now at least the few that don't lose their minds to this issue that find this post can do this in the mean time.
Check if your ajax is executed
Check it's status. If response code is != 200, than you should add error method also, for error handling.
Try this:
$.ajax({
timeout: 20000,
url: 'test.com',
method: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
console.log('callback success');
this._cache = data;
localStorage.token = data.access_token;
},
error: function(xhr, error){
console.debug(xhr); console.debug(error);
},
});

How do I read this weird server response and get the "success" key?

I am using this jQuery basic ajax reader:
$.ajax({
url: url,
dataType: 'jsonp',
success: function (data) {
console.log('data is', data);
}
});
The full server response I get is:
jQuery17107194540228229016_1350987657731({"action":"", "type":"", "callerId":""},
{"errorCode":0,"errorDescription":"OK","success":true,"payload":null});
However, when I try to output it with the console.log('data is,data); the output I get is:
data is Object {action: "", type: "", callerId: ""}
How do I receive the other part of the server response?
ie: The part that tells me success:true:
{"errorCode":0,"errorDescription":"OK","success":true,"payload":null}
Try this, I don't know if it will help:
success:function(data, second){
console.log('data is',data, 'second is ',second);
As several people has pointed out, the success function will only return if the request is a success. But if you have some special reason why you want to use those return values, you could add an extra parameter ( I think, still haven't tested it myself ).
success callback from jquery request will always be success even if the response is a 404. As long as the server was reachable, that is always a success. Only when server is not reachable or request got lost in the way the error callback is triggered. From that perspective, you'll always have to analyze the output to see if the result is the desired (that or check the status code of the response. If it's 40x, then it's probably an error from your perspective).

Javascript object declaration in IF statement

I'm sorry about the title I'm just not sure how to describe this one.
Basically I'm using JQUERY/ajax to invoke a php script to validate some input and get some data. The returned data is encoded JSON, so i set the datatype to JSON in JQUERY and it returns an object.
I have just discovered that under certain (it has to be said unusual) conditions where a network connection is not responding in an expected way, the ajax call invokes the error option in JQUERY.
In most cases I have an error message coming back from the server, but sometimes the error is reached and no JSON has been sent back from the server side script. I haven't tracked down exactly what can provoke that network situation yet, but in any case I thought I'd just deal with it back in Javascript whilst I don't yet know.
The idea was to check to see if the expected object had been created, and if not then create it with the two expected properties and run a dialogue. This way I'd avoid repeating writing the error messages. It's not a big saving, but I wanted to try the principle.
$.ajax({
url: 'getmetadata.php',
type: "POST",
data: entereddata,
dataType: "json",
timeout: (7000), //wait 7 seconds
error: function(data)
{
// handle errors
if(data)
{
// Do nothing error message will be issued from the data object
}else{
// no message was returned. Some other error occured.
function tempdata()
{
this.errortitle = "Error title";
this.errormessage = "Error text";
};
var data = new tempdata();
};
// issue error message
runDialogue(data.errortitle,data.errormessage);
}, //ERROR
success: function(data)
{
}; // SUCCESS
}); // AJAX
in the code above, the data object should either exist or not before the "if" statement. And when I get to the runDialogue(); the object data should always exist in order to pass the errortitle and errordescription properties.
When the "data" object exists, there is no problem. What isn't working is when the "data" object does not exist, ie if fails the "if" test. The else should create the object "data" but doesn't.
What have i done wrong?
You are redefining the variable data in your else block(more specific scope) and hence the global scope variable will still be undefined.
Change var data = new tempdata(); to
data = new tempdata(); //In the else block
So, now your ajax call should look like:
$.ajax({
url: 'getmetadata.php',
type: "POST",
data: entereddata,
dataType: "json",
timeout: (7000), //wait 7 seconds
error: function(data)
{
// handle errors
if(data)
{
// Do nothing error message will be issued from the data object
}else{
/******************NOTE THE CHANGE HERE********************/
data = {
errortitle:"Error title",
errormessage:"Error text"
};
};
// issue error message
runDialogue(data.errortitle,data.errormessage);
}, //ERROR
success: function(data)
{
}; // SUCCESS
}); // AJAX
Javascript throws an error on undefined references; you can't test existence just using the object. You can use the typeof operator to test whether the data exists, or instead whether it is of type "object".
For example:
if (typeof data === "undefined")
{
// You don't really need a closure for this...
errordata = {'errortitle' : 'Error Title',
'errormessage' : 'Error Message'};
runDialogue(data.errortitle, data.errormessage);
}
When $.ajax fails (because of a HTTP error), the .error method is called and passed the following params:
error(jqXHR, textStatus, errorThrown)
So the first parameter, which you have called "data", is not "what the webserver sent you" but a jquery wrapped xmlhttprequest object. Testing it via "if" [eg if (data)] will always return true.

Categories

Resources