ajax requests are Pending parallel request - javascript

What im doing is when page is loading im calling two ajax request
fetch_list_big();
fetch_list_small();
function fetch_list_big(){
$.post(...);
}
function fetch_list_small(){
$.post(...);
}
As the name suggests request in fetch_list_big() takes more time to complete than fetch_list_small.
But since fetch_list_big is called first the fetch_list_small says pending till fetch_list_big returns 200.
big.php
require_once('files_same.php'); #starts session /connection / configurations etc
#Some heavy mysql stuff #say 5 seconds
echo json(...)
small.php
require_once('files_same.php'); #starts session /connection / configurations etc
#Some light mysql stuff #say 1 seconds
echo json(...)
How can i call fetch_list_small() after fetch_list_big() in parallel way and not make it pending ?
Pending Requests
http://i.imgur.com/vj07tyI.png
The first request is huge and takes 5 second in server
The last 3 are small request and should be returned before first one but they are pending.
After First request returns 200
http://i.imgur.com/liPuO70.png
After first request returns 200 . the last 3 requests are executed.
Problem
I want all the requests to Run Parallel without locking in server (is some kind of session is getting locked ? )

I want all the requests to Run Parallel without locking in server (is some kind of session is getting locked ? )
Yes; PHP will block other scripts from accessing the session, as long as one script instance is using it. (At least for the default file-based session storage mechanism.)
You can avoid this by calling session_write_close as soon as your script(s) are done with what they need to do with the session.

You can use a callback in your fetch_list_big()
function fetch_list_big(callback){
$.post(url, function(data){
if(callback){
callback();
}
});
}
fetch_list_big(function(){
fetch_list_small();
});

Related

Ajax calls DURING another Ajax call to receive server's task calculation status and display it to the client as a progression bar

I'm trying to figure out if there's any chance to receive the status of completion of a task (triggered via an ajax call), via multiple (time intervalled) ajax calls.
Basically, during the execution of something that could take long, I want to populate some variable and return it's value when asked.
Server code looks like this:
function setTask($total,$current){
$this->task['total'] = $total;
$this->task['current'] = $current;
}
function setEmptyTask(){
$this->task = [];
}
function getTaskPercentage(){
return ($this->task['current'] * 100) / $this->task['total'];
}
function actionGetTask(){
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'percentage' => $this->getTaskPercentage(),
];
}
}
Let's say I'm in a for loop, and I know how many times I iterate over:
function actionExportAll(){
$size = sizeof($array);
$c = 0;
foreach($array as $a){
// do something that takes relatively long
$this->setTask($size,$c++);
}
}
While in the client side i have this:
function exportAll(){
var intervalId = setInterval(function(){
$.ajax({
url: '/get-task',
type: 'post',
success: function(data){
console.log(data);
}
});
},3000);
$.ajax({
url: '/export-all',
type: 'post',
success: function(data){
clearInterval(intervalId); // cancel setInterval
// ..
}
});
}
This looks like it could work, besides the fact that ajax calls done in the setInterval function are completed after "export-all" is done and goes in the success callback.
There's surely something that I'm missing in this logic.
Thanks
The problem is probably in sessions.
Let's take a look what is going on.
The request to /export-all is send by browser.
App on server calls session_start() that opens the session file and locks access to it.
The app begins the expensive operations.
In browser the set interval passes and browser send request to /get-task.
App on server tries to handle the /get-task request and calls session_start(). It is blocked and has to wait for /export-all request to finish.
The expensive operations of /export-all are finished and the response is send to browser.
The session file is unlocked and /get-task request can finally continue past session_start(). Meanwhile browser have recieved /export-all response and executes the success callback for it.
The /get-task request is finished and response is send to browser.
The browser recieves /get-task response and executes its success callback.
The best way to deal with it is avoid running the expensive tasks directly from requests executed by user's browser.
Your export-all action should only plan the task for execution. Then the task itself can be executed by some cron action or some worker in background. And the /get-task can check its progress and trigger the final actions when the task is finished.
You should take look at yiisoft/yii2-queue extension. This extension allows you to create jobs, enqueue them and run the jobs from queue by cron task or by running a daemon that will listen for tasks and execute them as they come.
Without trying to dive into your code, which I don't have time to do, I'll say that the essential process looks like this:
Your first AJAX call is "to schedule the unit of work ... somehow." The result of this call is to indicate success and to hand back some kind of nonce, or token, which uniquely identifies the request. This does not necessarily indicate that processing has begun, only that the request to start it has been accepted.
Your next calls request "progress," and provide the nonce given in step #1 as the means to refer to it. The immediate response is the status at this time.
Presumably, you also have some kind of call to retrieve (and remove) the completed request. The same nonce is once again used to refer to it. The immediate response is that the results are returned to you and the nonce is cancelled.
Obviously, you must have some client-side way to remember the nonce(s). "Sessions" are the most-common way to do that. "Local storage," in a suitably-recent web browser, can also be used.
Also note ... as an important clarification ... that the title to your post does not match what's happening: one AJAX call isn't happening "during" another AJAX call. All of the AJAX calls return immediately. But, all of them refer (by means of nonces) to a long-running unit of work that is being carried out by some other appropriate means.
(By the way, there are many existing "workflow managers" and "batch processing systems" out there, open-source on Github, Sourceforge, and other such places. Be sure that you're not re-inventing what someone else has already perfected! "Actum Ne Agas: Do Not Do A Thing Already Done." Take a few minutes to look around and see if there's something already out there that you can just steal.)
So basically I found the solution for this very problem by myself.
What you need to do is to replace the above server side's code into this:
function setTask($total,$current){
$_SESSION['task']['total'] = $total;
$_SESSION['task']['current'] = $current;
session_write_close();
}
function setEmptyTask(){
$_SESSION['task'] = [];
session_write_close();
}
function getTaskPercentage(){
return ($_SESSION['task']['current'] * 100) / $_SESSION['task']['total'];
}
function actionGetTask(){
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'percentage' => $this->getTaskPercentage(),
];
}
}
This works, but I'm not completely sure if is a good practice.
From what I can tell, it seems like it frees access to the $_SESSION variable and makes it readable by another session (ence my actionGetTask()) during the execution of the actionExportAll() session.
Maybe somebody could integrate this answer and tell more about it.
Thanks for the answers, I will certainly dig more in those approaches and maybe try to make this same task in a better, more elegant and logic way.

Laravel & Ajax - foreach json object & dealing with duplicates

im trying to make a simple notification system using Ajax and Jquery.
What i've done so far is:
Created a php file from which i load latest post and its title
Return json from php file mentioned above containing latest post and it's title
Created ajax post request that fetches the latest post from the json and its name using the data parameter in success: function(data)
Set an interval that repeats ajax call every 5 seconds
prepend the latest post title in notification div
Problems i have are:
If i set the interval on 1 minute and create 2 or more new posts it will only give the newer one (obviously since i called ->first() from my ->latest(), otherwise it wont load anything)
As i mentioned before, my setInterval is set to 5 seconds, and then it loads the latest post, and it does that every 5 seconds so i have an identical new post every 5 seconds until the newer one comes, i tried fixing it by prepending only higher id than the last one, but im not sure how reliable is that
Scripts:
Notification.php:
$post = Post::latest()->first();
$post_title = $post->title;
return response->json(array('post' => $post, 'post_title' => $post));
View with AJAX:
function getnewnotif()
{
$.ajax({
type:'POST',
url: url_to_notification.php,
success: function(data){
$('#notif').prepend(data.post_title);
}
});
}
setInterval(getnewnotif(), 5000);
You were definitely on the right track with IDs, but more reliable is likely the creation (or updated) date.
In its simplest form, when you send your request for more posts, send a "last request date" parameter. On the server, use that to only grab posts that have been created (or modified - not sure which you want) after that date. On the client, where you make the ajax calls, you'll need to remember the last date you requested data from the server, so you can use it in your next ajax call.
But that will not work perfectly well when multiple timezones are involved.
A sturdier approach is for the server to tell you it's local time. So you send your first ajax call, and along with the list of posts, the server also returns the time it sent you the data. Your javascript grabs that date, and on your next ajax call, you send that to the server. It can then return to you just new posts that were created after that date. Since it's always server date vs server date, timezones don't matter here.
Hope this helps!

AJAX requests not executing in parallel using $.when(...)

My script makes around 15 ajax calls to my server. I want them to execute in parallel. I am trying to use when to execute a bunch of ajax requests in parallel but for some reason it's still doing them one by one.
My code is below:
var requests = $.map(results, function(result, i) {
var suggestionContainer = $('<div class="suggestion-' + i + '">' + result + '</div>');
resultsContainer.append(suggestionContainer);
return $.get('check.php', { keyword: result }).done(function(res) {
res = JSON.parse(res);
suggestionContainer.append(generateSocialMediaList(res.social_media))
.append(generateDomainList(res.domains));
}).fail(function() {
suggestionContainer.remove();
});
});
$.when(requests).done(function() {
console.log('Complete')
}, function() {
alert('Something Failed');
});
Is there anything I'm doing wrong?
The reason why I am making 15 requests is because check.php makes a call to a third party API. The API is slow, and unfortunately there is no alternative. Making 15 parallel requests would be much quicker than 1 request and wait for check.php to complete.
The code works like so:
A request to suggestions.php is made (that's not included as it's not required to solve the problem). The results are stored in an array results.
The results (there's about 15) are returned and iterated over with map.
I insert the suggestion into the page. I then return an promise.
The requests array now contains 10-15 promises.
I use when to execute the requests in parallel (that's what I'm trying to do at least).
Upon success the DOM is updated and the results from check.php are inserted into the DOM.
Your code will execute the requests with as much parallelism as the browser allows.
Browsers used to limit concurrent requests to a single domain to 6. This may have changed.
The responses to these requests will be serviced one by one because JavaScript is single-threaded, and this is what you are observing.
Also: double-check your AJAX call is not failing. when will reject as soon as any of the promises is rejected.

jQuery: AJAX request fires multiple times until response is successfully using $.Deferreds

Problem!
While trying to perform a set of AJAX request, most of the time at least one of the request is always getting a pending response, this is resulting in a loop of requests until it gets a succesful response. Please note that I using jQuery.when, this way I can ensure that both requests have been executed.
The mentioned behaviour is resulting on:
Multiple requests to the same source
jQuery.always is executes as many times as requests performed
The interface is crashing due to multiple updates on it's DOM.
Example
var request = [];
request.push(getProductPrice().done(
function(price) {
updateProductPrice(price);
}
);
request.push(getProductInfo().done(
function(information) {
updateProductInformation(information);
}
);
jQuery.when.apply(undefined, request).always(function() {
doSomeStuff1();
doSomeStuff2();
...
...
...
doSomeStuffN();
});
function updateProductPrice(obj) {
return jQuery.get(...);
}
function updateProductInformation(obj) {
return jQuery.get(...);
}
Questions?
Is there any reason on why I am getting a pending response?
Is this problem realted to jQuery.when trying to release the AJAX request in order to fire-up the callbacks?
Facts
If I do the request to the mentioned sources via synchronous, I will never get a pending response. I am just trying to avoid the use of async: false.
Update #1
By pending status I meant the response given by the web browser to my request, which is nothing but the ajax call waiting for it's response. The main problem resides on how those AJAX request are being treated, I am noticing that the functions updateProdcutPrice() and updateProductInformation() are being called N times until the response from the server is succesful, this is resulting that the functions declared on the .always()'s callback for the requestes performed on updateProdcutPrice() and updateProductInformation() are also being called that many times.

Requesting something via ajax - how to stop other requests until this one is done

I have a php script that outputs json data. For the purposes of testing, i've put sleep(2) at the start.
I have a html page that requests that data when you click a button, and does $('.dataarea').append(data.html)
(php script returns a json encoded array. data.html has the html that i want to put at the end of <div class="dataarea">...HERE</div>.
The trouble is, if i click the button too fast (ie. more than once within two seconds (due to the sleep(2) in the php script)), it requests the php file again.
how can i make it only do one request at a time?
i've tried this (edited down to show the important parts):
amibusy=false;
$('#next').click('get_next');
function get_next() {
if (amibusy) {
alert('requesting already');
}
else {
amibusy=true;
// do the request, then do the append()
amibusy=false;
}
}
but this doesn't seem to work. i've even tried replacing the amibusy=true|false, with set_busy(), and set_not_busy(). (and made a function am_i_busy() { return amibusy; })
but none of this seems to work. what am i missing?
If you're in jQuery the amibusy would be jQuery.active which contains a count of currently active AJAX requests, like this:
if(jQuery.active > 0) { //or $.active
alert('Request in Progress');
}
Keep in mind that in jQuery 1.4.3 this becomes jQuery.ajax.active.
Disable the button in the click event and enable it again when the request is finished. Note that the request is asynchronous (i.e. "send request" returns immediately), so you must register a function that is called when the answer comes in.
In jQuery, see the load() function and the success method plus the various AJAX events which you can tap into with ajax().
I'm wondering about your "do request" logic. Whenever I've done calls like this they've always been asynchronous meaning I fire the request off and then when the response comes another function handles that. In this case it would finish going through that function after setting the callback handler and set your value of amibusy back to false again before the request actually comes back. You'd need to set that variable in the handler for your post callback.
Could you use the async variable?
http://api.jquery.com/jQuery.ajax/
asyncBoolean Default: true
By default, all requests are sent
asynchronous (i.e. this is set to true
by default). If you need synchronous
requests, set this option to false.
Cross-domain requests and dataType:
"jsonp" requests do not support
synchronous operation. Note that
synchronous requests may temporarily
lock the browser, disabling any
actions while the request is active.

Categories

Resources