I have a couple of jQuery Ajax requests, which have to be synchronous, but they keep locking/freezing the browser, until the response is received. My main problem is, that until the response is received I have to display a spinning icon, but due to the freezing the spinner is not displayed and even if it miraculously is it doesn't animate.
This is the event displaying the spinner and sending the request:
$(document).on('click', '#open-button', function () {
var input = "some text";
var wrapper = $('#wrapperWindow');
wrapper.children().animate({
opacity: 0
}, 500);
wrapper.children().remove();
wrapper.append('<div id="loading-spinner" style="display:none;"></div>');
var spinner = $('#loading-spinner');
spinner.css({
backgroundImage: 'url("img/loading.gif")',
opacity: 0
});
spinner.show();
spinner.animate({
opacity: 1
}, 500);
var dataForTab = requestData(input); //<-- the request
if (dataForTab.length > 0) {
//do stuff
}
});
The request:
function requestData(input) {
var result = null;
$.ajax({
async: false,
type: "POST",
url: "/some/url?input=" + input,
dataType: "json",
retryLimit: 3,
success: function (json) {
result = json;
},
error: function (xhr, err) {
console.log(xhr);
console.log(err);
}
});
return result;
}
Until the request returns the received JSON data, everything stops moving. How can I fix this please?
That's the essence of synchronous requests, they are locking. You may want to try to move the requests to a web worker. Here's an example (not using XHR, but it can give you an implementation idea)
A web worker is implemented in a separate file, the scripting can look like:
onmessage = function (e) {
var result = null;
$.ajax({
async: false,
type: "POST",
url: "/some/url?input=" + input,
dataType: "json",
retryLimit: 3,
success: function (json) {
result = json;
postMessage({result: result});
},
error: function (xhr, err) {
postMessage({error: err});
}
});
}
Depending on your use case you can use something like
task.js Simplified interface for getting CPU intensive code to run on all cores (node.js, and web)
A example would be
// turn blocking pure function into a worker task
const syncWorkerRequest = task.wrap(function (url) {
// sync request logic
});
// run task on a autoscaling worker pool
syncWorkerRequest('./bla').then(result => {
// do something with result
});
You should not be doing this though, unless you need to do some heavy data processing, please use async requests.
Related
I have tried ways to search for a solution but I can't seem to find the right combination of words or something... here goes:
I have an ASP.NET MVC application that users scan inventory/package barcodes into. Every time someone scans an item, I make an async request and then display a popup message with information about the package. This part works as expected and does not block the application during the request:
$.ajax({
type: 'GET',
dataType: 'json',
async: false,
url: '#Url.Action("SingleOrderLookup")?trackingNumber=' + trackingId,
success: function (result) {
if (result.success) {
var audio = findAudio(result.model, audioClips, saturdayAudio);
suppressDefaultSound = true;
var titleText = result.model.displayPromptText;
if (result.model.isRefrigerated) {
isRefrigerated = true;
titleText = "<p style='color: blue;'>(REFRIGERATED)</p>" + "<p>" + result.model.displayPromptText + "</p>";
}
swal.fire({
title: titleText,
text: "Place in route for " + result.model.displayPromptText,
type: "success",
showCancelButton: false,
confirmButtonText: "Sorted",
cancelButtonText: "Cancel",
timer: 1750,
preConfirm: function () {
return new Promise(function (resolve) {
resolve();
}, 1000);
}
}).then(result => {
if (result.value) {
}
});
var dupe = findOrderByTrackingNumber(trkNumbers, result.model.trackingId);
if (!dupe) {
trkNumbers.push({ trackingNumber: trackingId, depotId: result.model.destinationHub });
pkgCount++;
if ($("#divUpdatePickup").is(":hidden"))
$("#divUpdatePickup").show();
AddLogToTable(trackingId);
} else {
//audible feedback that duplicate was scanned
//if (!trkBin) PlayAudio(2);
//PlayAudio(2);
}
//playing audio
if (isRefrigerated) {
setTimeout(function () {
if (audio) playByteArray(audio);
}, 1500);
PlayRefrigerate();
} else {
if (audio) playByteArray(audio);
}
}
if (result.nullRoute) {
addToTrkNumbers = false;
Swal.fire({
title: "NO ROUTE DEFINED",
text: "Unable to match order to a route!",
type: "warning",
showCancelButton: false
});
}
}
});
However, I want the page to make another async call to populate a variable with an array of objects, transparently and without blocking the user from making scans and receiving information back from the async calls from the above code. This call should occur immediately when the page is loaded, and it could take more than a minute or two to receive all the data expected from this call. Once the response is back, the collection variable (zipSort[]) should be populated. The data in this variable will contain a "cache" of elements that the page can query against to avoid having to make individual server-side calls after each scan (in essence, I want to "front-load" data needed for the scan events and once completed, individual calls to the server should not be necessary since this variable should contain 99% of the IDs expected to be scanned).
This is where I'm having an issue and it's probably due to a lack of understanding of how async calls/JS promises work. Here is the code I have so far for this:
//array to hold data on expected tracking number scans
var zipSort = []
async function getCheckinGroup(zipSort) {
console.log("Fetching complete check-in group...");
var url = '/SortFacility/HubManager/GetOrders';
var promise = new Promise((resolve,reject) => {
$.ajax({
type: "GET",
url: url,
cache: false,
async: true,
contentType: "application/json",
success: function (result) {
if (result.success) {
console.log("Retrieval success");
try {
zipSort = result.model;
resolve(result.model);
} catch (ex) {
reject("Some error?");
}
} else {
reject("Some error?");
}
},
error: function (ob, errStr) {
reject("Something went wrong");
}
});
});
return promise;
}
//don't want this to hold up execution of the rest of the code, so zipSort[] should
//remain empty and get set transparently when the ajax response is returned:
getCheckinGroup(zipSort);
Every version of code I'm trying out from articles and tutorials I have read holds up the UI and keeps users from being able to scan items while the response hasn't been returned. What am I missing? How should I change this so that (a) users can begin scanning immediately once the page has loaded and receive information from individual async calls to the DB, and (b) zipSort[] can be populated with the totality of any data potentially needed for these scans, and once populated, scan events trigger a lookup on that variable instead of continued individual calls to the database?
Any help would be appreciated!
Edit: tried simply adding this call in-line and no matter where I put it, it blocks the other code from running until response is received, even though async is set to true:
$.ajax({
type: "GET",
url: url,
cache: false,
async: true,
contentType: "application/json",
success: function (result) {
console.log("Data received.");
zipSort = result.model;
}
});
Thanks everyone for your help. I found this little gem, which solved my problem:
https://josef.codes/c-sharp-mvc-concurrent-ajax-calls-blocks-server/
Applying [SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)] to my controller class enabled concurrent async ajax calls.
So I have an array that contains data that needs to be sent as part of the payload for POST requests that need to be made. Now, these need to be made sequentially, since I need to display the particular payload , then the result(the result being the response that is returned after making the POST request with the payload), then the next payload, then the next result and so on, on my page. I was just wondering what would be the best approach to accomplish this.So this is how I'm approaching it at the moment:
for (var i = 0; i < quotesList.length; i++) {
var response = $.ajax({
type: "POST",
url: url,
data: JSON.stringify(quotesList[i]),
success: add_to_page,
},
timeout: 300000,
error: function(){
console.log("Some Error!")
},
contentType: "application/json"
})
Obviously, the issue here that arises is there's no guarantee in terms of the getting that sequence right and also I wasn't quite sure how exactly to keep a track of the payload since trying to add it as a part of the success function only gets me the last element in the last(presumably the last request thats fired)
You can try something like below.
let quotesListIndex = 0;
function sendAjaxCall() {
if (quotesListIndex < quotesList.length) {
var response = $.ajax({
type: "POST",
url: url,
data: JSON.stringify(quotesList[quotesListIndex++]),
success: function () {
//... Add code here
sendAjaxCall(); // Call the function again for next request
},
timeout: 300000,
error: function () {
console.log("Some Error!")
},
contentType: "application/json"
})
} else {
return;
}
}
Add one global variable to track the index. and call function recursively. Once the index reached the array size then return from function.
What I am trying to do:
1. Initially gives an ajax request to the server based on some inputs
2. The server returns a job id generated by RQ (Python-rq)
3. Based on the job id ajax request made to a url constructed with the jobid regularly till a valid response is obtained
What I have:
$.ajax({
type: "POST",
url: "/start",
data:{crop: valueCrop, state: valueState, variablemeasure: valueVariable, unit:unitMeasure, from:yearFrom, to:yearTo},
success: function(results) {
console.log(results);
var jobId='';
jobId = results;
function ajax_request() {
$.ajax({
type: "GET",
url: "/results/" + jobId,
dataType: "json",
success:function(xhr_data) {
if (xhr_data == {"status":"pending","data":[]}){
console.log("Waiting for response");
setTimeout(function() { ajax_request(); }, 2000);
} else {
console.log(xhr_data);
}
},
error:function(error) {
console.log(error)
}
});
}
},
error: function(error) {
console.log(error)
}
})
Is this even possible? I am not getting any output at all on the console although the rq says the job is finished. I think it is not entering that if loop. When I visit the "/results/jobId" url I am able to see the result.
Please help.
I see a few bugs in this code. First of all, you have defined the function ajax_request(). But you are not calling it. You can call it at the end of its definition.
Secondly, this code is problematic:
if (xhr_data == {"status":"pending","data":[]})
The object notation creates another object which is definitely not equal to xhr_data.
You can do:
if (xhr_data.status === "pending")
I have the following code:
var User = {
get: function (options) {
var self = this;
$.ajax({
url: options.url,
success: function (data, response) {
self.nextPageUrl = data.pagination.next_page;
options.success(data, response);
}
});
},
nextPage: function (success) {
this.get({
url: this.nextPageUrl,
success: success
});
}
}
User.get({
url: 'https://cache.getchute.com/v2/albums/aus6kwrg/assets',
success: function (data, response) {
// Through `data.pagination.next_page` I can get the URL
// of the next page.
}
});
User.nextPage({
success: function (data, response) {
// Here I want to make the same request but using the next_page
// based on the next related to the previous' one.
}
});
The problem
Basically, I want to perform the nextPage() operation based on the antecessor request (User.get()), but due to its asynchronousity, the nextPage() method doesn't know the this.nextPageUrl property—it returns undefined as expected.
Finally, the question is: can someone think in a way to keep the current syntax flow but solving this approach? Actually, is there a way?
And no, I'm not available to make a synchronous request.
General knowledge
I thought to use an event mechanism to deal with this: when the request is made and .nextPage() is called, then try to listen to an event to be emitted for x seconds, then I expected the this.nextPageUrl property to be available in that event-based scope.
What do you guys think?
DISCLAIMER: The logic of next_page is preprocessed by the server and only then is sent to the client. I have no option to use an increment/decrement behavioral operation.
If you want to play with this problem, click here for the jsFiddle.
jsFiddle Demo
There are a couple of options. You could bind the setter of the property to also call the nextPage, you could poll from calling nextPage every n milliseconds until the nextPageUrl property was populated, you could use a promise, you could use a nextPageQueue.
I think that a queue may be the simplest form of completing this. I also think it may be useful to have User store some local variables in this situation, and that the use of a function object may be more inline with that.
It would look like this
var User = new function(){
var pageQueue = [];
var get = this.get = function (options) {
$.ajax({
url: options.url,
dataType: 'JSON',
success: function (data, response) {
options.success(data, response);
var nextPageUrl = data.pagination.next_page;
if( pageQueue.length > 0 ){
pageQueue[0](nextPageUrl);
pageQueue.splice(0,1);
}
}
});
};
var nextPage = this.nextPage = function (options) {
pageQueue.push(function(nextPageUrl){
get({
url: nextPageUrl,
success: options.success
});
});
};
};
and your calls would not change.
User.get({
url: 'https://cache.getchute.com/v2/albums/aus6kwrg/assets',
success: function (data, response) {
// Through `data.pagination.next_page` I can get the URL
// of the next page.
console.log('get');
console.log(data);
console.log(response);
}
});
User.nextPage({
success: function (data, response) {
// Here I want to make the same request but using the next_page
// based on the next related to the previous' one.
console.log('next');
console.log(data);
console.log(response);
}
});
You can grab a reference to your User object before making the asynchronous request.
var User = {
get: function (options) {
var self = this;
$.ajax({
url: options.url,
success: function (data, response) {
self.nextPageUrl = data.pagination.next_page;
options.success(data, response);
}
});
},
You can modify your get method and eliminate your nextPage method entirely:
var User = {
url: 'https://cache.getchute.com/v2/albums/aus6kwrg/assets',
get: function (options) {
var self = this;
self.pageXhr = $.ajax({
url: self.nextPageUrl ? self.nextPageUrl : self.url,
dataType: 'JSON',
success: function (data, response) {
self.nextPageUrl = data.pagination.next_page;
self.pageXhr = false;
options.success(data, response);
}
});
}
}
Then whenever you call User.get, it will either call the current page or the next page. I am not sure about the context of when you want to get the subsequent pages, but if you need the requests to be queued you can wait for the existing request to finish before triggering the next request. For example:
if (self.pageXhr) {
self.pageXhr = self.pageXhr.then(function() {
return $.ajax({
url: self.nextPageUrl ? self.nextPageUrl : self.url,
dataType: 'JSON',
success: function (data, response) {
self.nextPageUrl = data.pagination.next_page;
options.success(data, response);
}
});
});
}
I have implemented an ajax polling function that I need to call continuously until the polling results come back with my expected results. In order to accomplish this, I am using setTimeout to introduce a delay so that the function doesn't just hammer the server with requests until it gets the results.
Let me preface this by saying that I have already found the way I need to implement the code to get the expected behavior I need. But, my question is in regards to the solution I found. I want to know why the solution worked with the timeout correctly, while the other one did not.
Here is the working code that successfully sets a timeout and polls for the result:
function makeRequest(url, data, requestType, successCallback, errorCallback, doneCallback) {
$.ajax({
url: url,
type: requestType,
data: data != null ? JSON.stringify(data) : '',
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (successCallback) successCallback(success);
},
error: function (error) {
if (errorCallback) errorCallback(error);
},
done: function() {
if (doneCallback) doneCallback();
}
});
}
function pollForResult(Id) {
setTimeout(function () {
makeRequest('/Transaction/TransactionResult/' + Id,
null,
"GET",
function(result) {
//success code here
}, function(error) {
//error callback implementation here
if (error.status === 404) {
pollForResult(Id); //results not ready, poll again.
} else {
alert("stopped polling due to error");
}
}, null);
}, 2000);
}
Here is the code that doesn't properly set a timeout and just continually hits the server with requests:
function pollForResult(Id) {
makeRequest('/Transaction/TransactionResult/' + Id,
null,
"GET",
function(result) {
//success code here
}, function(error) {
//error callback implementation here
if (error.status === 404) {
setTimeout(pollForResult(Id), 2000); //results not ready, poll again.
} else {
alert("stopped polling due to error");
}
}, null);
}
So, my question is this: what is it about the second block of code that makes it continually poll the server for results instead of waiting the 2 seconds to poll again?
I suspect, although I haven't tried, that this would work properly in the second block of code:
setTimeout(function(){ pollForResult(Id); }, 2000); //results not ready, poll again.
setTimeout(pollForResult(transactionId),2000);
This code immediately calls pollForResult and assigns its return value to be the function called when the timeout occurs.
This is desired behaviour, because you might have a function that builds a closure and passes that to the timeout. However it seems to catch out a lot of people...
As you said, function() {pollForResult(transactionId);} will work just fine.