Sync AJAX for specific case - javascript

I have 3 buttons on page.
Each one makes AJAX request by clicking on it.
These all requests should makes in async mode.
But clicking on any button in second time should:
1. Stop current request which was made clicking on this button at first time.
OR
Do Nothing.
Option#1 is prefer.
I know about abort(), but my question - how to detect that Ajax request (from certain button) is still not finished ? Here the main point is - request from certain button. I do not want stop all ajax requests. I want stop only request which was made by clicking in the same button at first time.
In my project i'm using jQuery
is this http://api.jquery.com/category/deferred-object/ can help me ? if yes can you provide any suitable example ?
Thanks

I don't believe deferred objects will do what you want. They're designed more for doing promises and aggregate callbacks. You can look into the state of an ajax call by keeping a reference to the jqXHR object returned by $.ajax though.
var ajax;
function onClick() {
if (!ajax || ajax.state() === "resolved") {
ajax = $.ajax(url);
}
}

you need to have a variable associated with each possible ajax process, which tracks whether that process is currently running. When an ajax call starts, set that variable to indicate it's running. When that ajax call completes, set the variable to indicate that the process has stopped. Then, when the user clicks the button, you can examine the variable to decide whether you need to abort() the ajax call or not.

Related

How to make sure all ajax calls got executed successfully ( not completed)

I know this question has been asked multiple times before as how to execute function when all AJAX call has been completed. We can user jquery.stop() in this case.
But my requirement is different. I want to show confirm banner when all ajax call have been executed successfully. For different pages , I have multiple AJAX calls. I do not want to put any condition on each AJAX call success method.
Can any one suggest if there is any global way.
Thanks in advance.
your are searching for global event handlers:
https://api.jquery.com/category/ajax/global-ajax-event-handlers/
http://api.jquery.com/ajaxcomplete/
anytime when you call an ajax request you "see" it via .ajaxSend() and handle response via .ajaxComplete()

Is it Possible to Perform a background PHP server task from an AJAX call that will not lockup your site?

I have a server function like this
function very_long_task($data) {}
This function is called using $.ajax() function clients-side.
The problem is that when my server-side function very_long_task() is executed the site is locked down. Meaning that if I tried to view another page of the website from a different tab or window, the website will not load until the very_long_task() function has completed.
Is there anyway to get around this either server-side or client-side?
UPDATED: 2015-11-3
The AJAX call is actually called many times because it is looping through all the elements in a list and performing an action on each of them. The very_long_task() function is then being called on each element.
For example, if there were a list of 20 elements then the very_long_task() function would be called 20 times. This does help a little bit in the overall responsiveness on that page but not on other pages.
UPDATED: 2015-11-3
Also this is built with WordPress so I can leverage some of their functions, but I have had no luck with wp_schedule_single_event since I need a return value.
https://codex.wordpress.org/Function_Reference/wp_schedule_single_event
UPDATED: 2015-11-3
Here is an updated view of my
function very_long_task($data) {
session_write_close();
// Very long task...
return $data;
}
You'll want to call session_write_close() as soon as possible.
This is because while one page has called session_start(), the session file will be locked until the page finishes execution, or until the session is closed.
If this is not done, any page calling session_start() will wait for the lock to be lifted.
UPDATE
I think I know what's going on:
your browser limits the number of simultaneous connections to a server, typically somewhere between 2 and 10.
If you're making 20 asynchronous AJAX calls, and you open the Developer Console (F12 / control-shift-I), you'll probably find that not all of them are executing simultaneously. This would certainly leave no room for additional connections.
Note, that the session_write_close() is still necessary, otherwise the ajax calls will execute serially.
SUGGESTION
So, it is best to only make one AJAX call.
If you want parallelism, you can fork child processes server-side.
You probably won't be able to use jQuery for this, because you'll want to send data from the server and flush()-ing it as it becomes available (HTTP streaming).
One solution I used in a WP importer plugin is not to use AJAX at all, but perform the long running operation, pushing out HTML and a <script> tag to update the UI.
I'm not entirely sure what you mean by "locked down" but below are some things to try:
Make sure that your AJAX is asynchronous
$.ajax({
url: '/start_very_long_task.php',
async: true
});
Make sure your PHP accommodates the expected behavior
// start_very_long_task.php
function start_very_long_task()
{
ini_set('ignore_user_abort','on');
ini_set('max_execution_time', 0)
session_write_close();
do_very_long_task();
}
function do_very_long_task()
{
// Very long task stuff
// This can recursively call itself without making
// making multiple calls to session_write_close(), etc...
}
start_very_long_task();

Jquery async call not working on user event

In my webpage many on-load ajax call those works fine.
Action takes time as per processing time. Means if any action that has been complete will send response and will not wait for first to finish.
But if same I am trying to do with on-lick or any user event. All ajax call works synchronously. I want these should not wait to finish the execution of first running action. All should start and complete independently.
I am using jquery 1.8 where default async= true;
Please help me here to resolve this.
Issue may be due to session lock.
more detail you can find it here
http://php.net/manual/en/function.session-write-close.php
call session_write_close function if there no session write activity in your script or function.
Such issues are observed in many concurrent ajax call and previous call has some session write activity. In this case session will be locked until it completed its execution.
If you set async to true, they will all fire at the same time.
make explicitly declaration of async = true option in each ajax call .
Useful jsfiddle link
http://jsfiddle.net/jquerybyexample/tS349/

how to check if AJAX request has been completed?

I need to add a sibling to certain HTML elements in the Vaadin application. I don't want to do this on the server side, because it's far too complicated in my case.
I wrote a javascript, that does the magic and it is executed after the page loads the first time. But then, when I click a certain button, some of the elements are loaded from backend using AJAX by Vaadin.
I subscribe for this button "click" event in the javascript. In the listener function I want to wait until Vaadin completes the request and makes the changes in the DOM. Then, I would run my function again.
Question is - how to detect when Vaadin completes its request? Setting timeout is not an answer for me.
Most AJAX library/routine provides you a callback when the AJAX is done. So basically you can set a flag before you start AJAX callback, and then call that flag when your callback is called. At other places you can then check that flag to see if your AJAX call has come back yet.
Some other AJAX library already does that for you and has something like "isInProgress()" that you can simply check anytime to see if it is has come back yet.

Is it possible to stop currently executing Javascript code?

I'm not sure if what I'm about to ask is possible or the right way of doing about things, but here goes.
I have a webpage which loads some data from a server using AJAX and displays it visually. The user has the option of using one of two buttons on the page to "scroll" through the data which is filtered by week.
The code for these buttons is something like:
$("#leftButton").click(function () {
clearCurrentlyDisplayedData();
changeFilter(1); //Or -1, or whatever.
loadAndDisplayData();
}
In this (simplified) example, loadAndDisplayData() would use AJAX calls to fetch this data and then display it on completion of the request, like:
$.get(
"web/service/address",
function (data, textStatus, jqXHR) {
//Display the data here
});
However, there is a problem when the user clicks the arrows to scroll through the data too quickly. If the buttons are clicked twice in quick succession, the data for two weeks is displayed, on top of each other.
I don't want to disable the buttons until the data is collected - since the data collection and displaying does take a little bit of time, this would kill the ability of the user to navigate through the site quickly, and would quickly become irritating.
Is it possible to kill any currently executing scripts or AJAX calls (or functions called as a result of these) when the user clicks on one of the buttons in order to prevent the loading of two sets of data? Is there any other way I can go about solving this problem?
The jqXHR object has an abort() method, which you can call to cancel an AJAX request.
However, this requires you to keep a reference to the object returned by $.get().
A prehaps easier approach would be to increment a global counter when making a request, and decrement it when a request completes. In your success handler, only show the results if the counter === 0 (e.g. theres no requests pending).
Is there any other way I can go about solving this problem?
Rather than aborting the requests, it might be better to construct the callback function inside $.get in a way that clears the data and displays the new data as a single operation - i.e., doesn't clear the data until the new data is ready.
Javascript only processes a single event/thread at a time, so each AJAX response will be processed serially as they arrive.

Categories