I've got 2 ajax requests on one page. I ran first request and separately start second one. But second one stops working after the first has been run. And continue when first is over.
First requst take long time - something like 30 - 60 seconds and in this time I need second request to show logs what happens with first request. I try to use async: true but it's not help me.
Here it's my code
<script type="text/javascript">
var auto_refresh = setInterval( function()
{ asyncGet('log.php') }, 1000
);
function asyncGet(addr) {
$.ajax({
url: addr,
async: true,
success: function (response) {
$('#loadLog').html(response);
}
});
}
function getConn(addr) {
$.ajax({
url: addr,
async: true,
success: function (response) {
stopGet();
}
});
}
</script>
<div id="loadLog" class="lLog"></div>
and I call first ajax request in this way: getConn('main.php'); from function when press button.
Second request it's running, but not show respons before first request complete.
I wil attach image from firebug.
main.php - is request that take longer time.
log.php - is the logger that is blocked.
Would really appreciate some pointers to where I'm going wrong
This may be a problem with session. Check out this post. Suppose you may need to close session in your main.php as fast as possible.
Related
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.
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.
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);
}
I have the following link-
Grab Coupon
Where i have initialized $var3 like this
$var3 = "brand1,camp2";
The code for the function popitup2() is -
<script language="javascript" type="text/javascript">
function popitup2(id) {
$.ajax({
url: "http://jainkunal.com/wordpress/wp-content/trackclicks/clickcounter.php"+"?"+id,
success: function(){
alert( "Data Saved: " );
}
});
newwindow2=window.open('','name','height=225,width=350');
var tmp = newwindow2.document;
....some more code...
...at end...
return true;
}
</script>
Now when i click the link ex.com opens up without any alert i.e without running the php script through ajax and the javascript after that. If i remove the ajax call from the function popitup2() then the remaining javascript gets executed correctly.
Agree with previous answer that you are executing asynchronous Ajax request.
From documentation Async parameter may not work in 2 cases: Cross-domain requests or if dataType: "jsonp".
If you are doing crossdomain request, I can suggest only:
Grab Coupon
<script type="text/javascript">
function popitup2(id, link) {
$.ajax({
url: "http://jainkunal.com/wordpress/wp-content/trackclicks/clickcounter.php"+"?"+id,
context: link,
success: function(){
alert( "Data Saved: " );
window.location = $(this).attr("href");
}
....
return false;
});
With such approach we track clicking for sure.
There is another problem with such approaches, that tracking server should be fast otherwise, user will wait long time till navigate to resource.
What's happening here is that you're performing an asynchronous AJAX request, meaning that when you perform the request, the rest of your function continues to run. When the AJAX result comes back, it then fires the alert in your success function, but since you've clicked a link, you've navigated away from that page already.
Try adding an async: false to the ajax function's parameters to wait for the result to come back before continuing, like so:
$.ajax({
url: "http://jainkunal.com/wordpress/wp-content/trackclicks/clickcounter.php"+"?"+id,
async: false,
success: function() {
alert( "Data Saved: ");
}
});
You are passing two arguments to JS function. But function prototype (first line) accept only one. This lead into JS error.
i have one php file which process adding of record in Database fro array.
for example in array i have 5 items
aray an='abc','xyz','ert','wer','oiu'
i want to call one php file in j query ajax method
um = an.split(',');
var counter = 0;
if(counter < uemail.length) {
$("#sending_count").html("Processing Record "+ ecounter +" of " + an.length);
var data = {uid: um[counter]
$.ajax({
type: "POST",
url: "save.php",
data: data,
success: function(html){
echo "added";
counter++;
}
what it do, it complete all the prcess but save.php is still working
what i want after one process it stop untill process of save.php complete then it wait for next 10 sec and start adding of 2nd element.
Thanks
Not sure if I understand your issue correctly, but you may want to use synchronous (blocking) ajax calls instead of asynchronous (non-blocking). When you make asynchronous call, code execution continues immediately, leaving ajax calls "in the background". Synchronous call blocks the code execution until the request has finished.
$.ajax({ async: false, ... });
It not my place to question why you would want to do this, although want you are trying could result in a slow and unresponsive UI.
You'll want a while loop, not an if loop:
while(counter < uemail.length) {
Other solution that present themselves,
You'll want to turn off the async flag to ensure the call is complete, before executing the next line. The delay() function will also help.
$.ajax({
async: false, //ensure our requests are synchronous.
type: "POST",
url: "save.php",
data: data,
success: function(html){
echo "added"; //?? not a valid javascript function
delay(10000); //10000ms = 10 seconds.
}
counter++;
}
Also,echo is not a valid jQuery/javascript function, and your braces are somewhat unclear, and probably misssing.
I have assumed above that counter++ is outside your loop, because if it wasn't and you got a failure then it could continue forever.