How to handle a long request? - javascript

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.

Related

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

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.

Call post on external Rest API with Ajax

I am new to angular, and I'm trying to make a call to a Rest API and get its response. My issue is that my JavaScript keeps getting stuck on the Ajax call. I'm not sure if it's the data I am sending or the syntax of the Ajax call. I tried to alert 'Hello world' and that worked, then I alerted the JSON array and that was formatted correctly, but when I do the Ajax post, I don't get any response at all.
Any insight would be nice, thank you.
test.html
<button onclick="myFunction()">Post it</button>
test.js
function myFunction() {
var postData = [{"logintype":"1","user":"Administrator","password":"12345","controlid":"999","host":"192.168.2.164"}
];
$.ajax({
url: '192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
};
You have specified a relative URL, where I think you intended to specify an absolute URL. If the current page URL is http://localhost/myapp/, and you request 192.168.2.164/isapi/rip.dll/rest/session, that URL is resolved as http://localhost/myapp/192.168.2.164/isapi/rip.dll/rest/session.
If 192.168.2.164 is the ip address of the server you are trying to hit (and not a directory relative to your current path on your server), you will need to add // to the beginning of the URL to make it absolute (well, schema-relative at least):
$.ajax({
url: '//192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
Your issue has nothing to do with angular. What I will refer you to is the angular docs description of how to do a POST request and a small example of the syntax taken from the docs.
Learn to use $http or something similar if you want to develop with angular. https://docs.angularjs.org/api/ng/service/$http
Small example:
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

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);
},
});

Slow GET request using the Spring controller

Here are the two ways of implementation, that describe the issue.
The first one is the method that works really slow. It tries to get data from server, but the request is pending too long, only after that it returns data and everything's fine (except the terrible synchronous perfomance).
asyncMethod: function(doSmth, param) {
var resp = $.ajax({
type: 'GET',
async: false,
url: 'url'
});
data = resp.responseText;
doSmth(param, data);
}
Here is the same method, but it's asynchronous. The perfomance problem is eliminated here. But it executes the part in success only when page is reloaded. Probably reload stops some executions that were the bottleneck of the previous code sample.
asyncMethod: function(doSmth, param) {
var resp = $.ajax({
type: 'GET',
url: 'url',
success: function () {
data = resp.responseText;
doSmth(param, data);
}
});
}
I don't need to use asynchronous request, if the synchronous one works fast (but now it doesn't). There seem to be some executions, that make the request remain pending for too long. I don't see the execution that may be a bottleneck. Maybe it's somewhere in the libraries that are used, but no other requests are active when resp is being processed.
What are the ways to fix the problem or to analyze it? An advice would be appreciated.
There are two main culprits if a response is sat on "pending" for too long:
The application code that is fulfulling the ajax request is taking longer than expected
Simple network latency (not much that can be done about that in the application layer)
If you have access to the code that is fulfilling the request then I'd start there. Also, it's probably not a network issue if this request is taking an unusually long time compared to all your other requests
Have you tried the async method like this:
asyncMethod: function(doSmth, param) {
$.ajax({
type: 'GET',
url: 'url',
success: function (response, status) {
doSmth(param, response.responseText);
}
});
}

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

Categories

Resources