jquery - 2 ajax calls simultaneously - php

I want to run 2 AJAX calls simultaneously. I tried the below code but it waits for ajax ({export.php}) to finish and then ajax({display.php}) is run.
I want to run these 2 AJAX calls at the same time. For example, while export.php is running it should also run display.php at same time. How can I do this?
When I click on a button it calls export.php to convert the database table to a CSV file. I also want to show the progress bar i.e. how many records have finished, 1%, 2%... 100%. That percentage value is written in the display.php file so to make a progress bar I need to run the 2 AJAX calls simultaneously.
$('.tocsv').on('click', function() {
var display = setInterval(function() {
$.ajax({
url: 'display.php',
method: 'get',
success: function(data) {
console.log(data);
}
});
}, 500);
$.ajax({
url: 'export.php',
method: 'post',
success: function() {
clearInterval(display);
}
});
});
Edit
The problem was in display.php file i had written session_start(). I just deleted that line and changed ajax code to this
url: 'display.php?file=<?=session_id()?>',
success: function (data) {
$('#res').html(data);
}
});
but why it doesn't work when i write session_start() ?

In AJAX the first alphabet A is for "Asynchronous". So calling asyn way is not the issue here. The problem is with making ajax request inside the setInterval. I am very sure that you server is not responding in the time delay you have given i.e. 500ms and you are flooding your server with multiple request every half second. By the time one request is completed you have made at least 4 or 5 request to your server which is the root cause of you issue. Remove setInterval and if you want you call to be made after 0.5 sec use setTimeout.

Related

Multiple ajax requests at the same time

I have a form that is validated then submitted with the following handler :
submitHandler:function (form) {
$.ajax({
url: 'long_process.php',
type: 'POST',
data: $(form).serialize(),
success: function (result) {
// ... Redirect ...
}
});
//start polling
(function poll() {
setTimeout(function () {
$.ajax({
url: "get_progress.php",
success: function (data) {
console.log(data);
//Setup the next poll recursively
poll();
},
});
}, 3000);
})();
}
long_process.php takes about 30s to finish and in the meantime I'd like to track the progress via get_progress.php which echo the percentage of processing done.
When launching this script I get in the console (edited):
1 POST long_process.php
2 GET get_process.php (3 seconds later)...
...stuck here until long_process.php finishes THEN
3 GET get_process.php (3 seconds later)...
4 GET get_process.php (3 seconds later)...
...
but none of the get_progress.php return any values until the long_process.php is finished.
How can I achieve multiple simultaneous ajax request ? Ultimately this will be used to display a progress bar.
If you are using sessions in your PHP then the one call will block the other, because PHP won't allow two requests to use the same session space at the same time. Your two requests are probably firing, but you are not getting a request to the second until the server finishes with the first.
To solve this:
Option 1: Don't use sessions in the first script that you are calling or, if you must, then unlock the session using session_write_close(). After calling this, of course, you can't write any session variables.
Option 2: If reading and writing session variables is essential then don't use session variables in the second AJAX call and don't declare a session start. Have your first script put it's status somewhere else for you to read (in a DB, a file on /tmp) and then have the second script read the status from there.
Hope that helps!

In a web application many jQuery+Ajax+PHP processes not running parallel in the same client

In a web application that interacts with one server, there is a jQuery Ajax call with a PHP script that takes about 20 seconds to execute.
$(document).ready(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'createPDF.php',
data: str,
success: function(response) {
showPDF(response);
}
error: function() {
console.log('ERROR WHEN CREATING PDF');
}
});
});
In the meantime a user ask to the application to get a list (getList.php) through another jQuery Ajax independant from createPdf.
$(document).ready(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'getList.php',
data: str,
success: function(response) {
showList(response);
}
error: function() {
console.log('ERROR WHEN GETTING LIST');
}
});
});
The problem is that getList.php only starts executing once createPDF.php finishes.
The application works with sessions, and tests have been done in separate clients, in which case both requests run parallel, but in the same computer they don't.
In this scenario how to run both requests parallel?
Thank you
Basically what is happening is that on your server the session file is locked by the first script, e.g. saveFiles. After that script has completed its task, the session is unlocked again. Unfortunately your script getList wants to access the same session, since it is locked, getList will have to wait until it is unlocked.
One solution for this is to call session_write_close() after all writing to session data has been done, that will cause the session file to be unlocked and be used by the next script. That call should obviously happen as soon as possible after session_start() to minimize the waiting time for other requests.
For a more detailed explanation have a look at https://stackoverflow.com/a/6933294/2442804

How to execute multiple HTTP Request to the same page from the same client

I want to run some AJAX calls at the same page from the same client.
Ajax calls start correctly but the server queued the requests and execute jsut one per time.
I've also check the start request time and the returned message time.
Studying the second one there's a difference between the requests which is multiple than the before request.
Help me please!
$("document").ready(function() {
$(".user-id").each(function() {
var id = $(this).html();
getData(id);
});
});
function getData(id) {
$.ajax({
url: 'loadOperatorDiagram.php',
type: 'GET',
data: {id: id},
async: true,
cache: false,
success: function(resp) {
$("#boxes").append(resp);
draw(id); // A javascript function which draw into a canvas
}
});
}
loadOperatorDiagram.php get some queries and its execution time is about 5 seconds. The first one ajax request response after 5 seconds, the second one after 10 and so on. But everyone starts asyncronusly and correctly with a difference of few milliseconds
If you are using sessions in php (sounds like it, otherwise you could do at least 2 simultaneous requests...), you should close it as soon as possible in your php script as php will block the session.
Just use session_write_close(); as soon as you have what you need from the session.

Optimize ajax synchronously calls

I have some ajax script that fire off about 250 synchronous PHP calls . This is my script
$(document).ready(function(){
$("#generate").html("<div class='modal'><p>Initializing...</p></div>");
$.ajax({
url:'/fetch around 250 url from database.php',
async:false,
dataType: 'json',
success: function(data){
$.each(data,function(key,val){
$("#generate").html("<div class='modal'><p>Fetching "+val.url+"</p></div>");
saveimage(val.url);
}
$("#generate").html("<div class='modal'><p>done</p></div>");
finalcreate();
},
});
});
function saveimage(){
$.ajax({
url: 'do some php work.php',
async: false,
});
}
function finalcreate(){
$.ajax({
url: 'do some php work.php',
async: false,
});
}
In the first part script fetch more than 250 urls from database and for every url script do some php calculation using another ajax call. when the loop ends script do final ajax call.
When i run this programe in firefox, it run successfully for only 40 urls, then browser shows dialog box with option of whether user want to stop this script or not, if user want to run this script then the script run again for next 40 urls , same proccess occure till the end.
How i can optimize this script, i dont want browser show option to stop this script. Please help.
Thanks
Try this:
function nextrequest() {
if (requests.length == 0) {
$("#generate").html("<div class='modal'><p>done</p></div>");
finalcreate();
return;
}
var val = requests.pop();
$("#generate").html("<div class='modal'><p>Fetching "+val.url+"</p></div>");
saveimage(val.url);
}
var requests = [];
$(document).ready(function(){
$("#generate").html("<div class='modal'><p>Initializing...</p></div>");
$.ajax({
url:'/fetch around 250 url from database.php',
dataType: 'json',
success: function(data){
requests = data;
nextrequest();
},
});
});
function saveimage(){
$.ajax({
url: 'do some php work.php',
success: function(data) {
// do something...
nextrequest();
}
});
}
function finalcreate(){
$.ajax({
url: 'do some php work.php',
});
}
You store all the URLs in a global variable, and everytime a request is done, you get the next one, until all of them are consumed, (requests.length == 0), you call the final request.
This way the user can still do something else on the page, and you can display progress everytime a request is done. Also, a good thing is that you can make 2 calls at once, or more, to make the process faster.
Ajax call needs much time to complete, as it communicates with remote server. The slowest thing there is a query to the server. You should send one batch request with all data needed to the server, that should separate the data and handle it. Everything should be completed about 250 times faster.
make some time interval for each ajax request
success: function(data){
$.each(data,function(key,val){
$("#generate").html("<div class='modal'><p>Fetching "+val.url+"</p></div>");
setTimeout(saveimage(val.url),3000);
}

How to delay ajax query?

I read a lot of questions, but they doesn't working in my case.
My situation is: my ajax query to database to insert infromation. But in my web-application user can click on buttons very quick so previous ajax query is not finished, and there is where bugs are appear.
All i need to do is a delay between queries, so future queries will do only after previous is done.
Here is a code:
$('#save').click(function(){
var user_input=$('#user').val();
var section=$('#section').val();
$('#loading_info').append('<p><img src="Images/loading.gif" alt="loading" id="loading"/></p>');
$.ajax({
url: 'submit_db.php',
type: 'POST',
data: 'section='+section+'&user_input='+user_input,
success: function(result){
$('#response').remove();
$('#loading_info').append('<p id="response">' + result + '</p>');
$('#loading').fadeOut(500, function(){
$(this).remove();
});
}
});
return false;
});
What i tested and not working: insert timeout:3000 into ajax - 1 query is ok, but after this, the whole application freezes; set timeout using ajaxSetup() - the same situation. Tested setInterval function and put ajax query to it - but after it there were no ajax, application opened an implementing php file and freezes.
This not working:
$('#save').click(function(){
var t=setTimeout(function(){
var user_input=$('#user').val();
var section=$('#section').val();
$('#loading_info').append('<p><img src="Images/loading.gif" alt="loading" id="loading"/></p>');
$.ajax({
url: 'submit_db.php',
type: 'POST',
data: 'section='+section+'&user_input='+user_input,
success: function(result){
$('#response').remove();
$('#loading_info').append('<p id="response">' + result + '</p>');
$('#loading').fadeOut(500, function(){
$(this).remove();
});
}
});
return false;
},3000);
});
And this is not working too:
$('#save').click(function(){
var user_input=$('#user').val();
var section=$('#section').val();
$('#loading_info').append('<p><img src="Images/loading.gif" alt="loading" id="loading"/></p>');
$.ajax({
url: 'submit_db.php',
type: 'POST',
timeout: 3000,
data: 'section='+section+'&user_input='+user_input,
success: function(result){
$('#response').remove();
$('#loading_info').append('<p id="response">' + result + '</p>');
$('#loading').fadeOut(500, function(){
$(this).remove();
});
}
});
return false;
});
And finally this is not work too:
$.ajaxSetup({
timeout:3000,
});
Thanks in advance
What I suggest is to create a boolean and disable any button.
Create a boolean called "buttonPressed", this is set to false. When a submit is made, you check in your code if "buttonPressed" is set to false. If this isn't set to false, skit the AJAX request, otherwise set the buttonPressed to true and do the AJAX request. When the request is done, set the buttonPressed back to false and a new buttonpress will be allowed.
The problem is propably in that: user clicks 3 times in second, and afeter 3 seconds of timeouts, three quersies and sended in one second.
Use setTimeout, but clear this timeout everytime user clicks, so every time user clicks, timer is reseted, and you don't have to worry about query "queue".
Other solution is to detect does timer working, and ignore or queue user click (queue by creating new timet with value of 3000 + rest time of the actual timer
Paul Peelen's answer is probably the best one for you, but another safe solution would be to queue your requests. It will allow your code to execute asynchronously but still sequentially and even (potentially) allows you to kill duplicate requests before they even leave the machine. The way I've done this is something like this:
Create an array to hold your requests.
When the user's action causes a request, throw it into the end of the queue.
Immediately call a queue processor. If a previous requests hasn't resulted in a response yet, do nothing -- just leave it in the queue. Otherwise, remove the first item from the queue and process it. At this point, you could also look through the other queued requests and remove duplicates, or push high-priority requests to the top of the queue.
When the response is received, send it to wherever it needs to go and tell the queue processor to process the next request.
It's actually pretty simple to build, and I'm sure there are better variations out there. If server stability is a possible issue, you should build in some sort of process to kill dead requests (zombies).
Use a sentinel variable so that only one request can happen at a time. If it makes sense for the user to be able to have more than one request going then implement a queue for the requests, where the call to process the next element in the queue happens after the previous request has been handled.

Categories