Optimize ajax synchronously calls - php

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);
}

Related

jquery - 2 ajax calls simultaneously

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.

Jquery calling PHP function on jquery ajax success

Is it possible to call a php function on jquery ajax call.When i tried to do this i get function not defined error on php function
$.ajax({
type:"POST",
url:"x.php?z=" + id,
cache:false,
success: function(data)
{
<?php xcz(); ?>
}
});
$.ajax({
type:"POST",
url:"x.php?z=" + id,
cache:false,
success: function(data)
{
anotherFunction();
}
});
function anotherFunction(){
$.ajax({
type:"POST",
url:"anotherFile.php",
cache:false,
success: function(data)
{
//do something else;
}
});
}
That's not possible. PHP and javascript run on different computers. PHP runs on the server, and javascript runs in the browser. At the time the javascript is being executed, that server has already executed the PHP code, and has sent that the the browser.
The only way you can achieve such a thing is making an additional Ajax request.
Not possible. Because jQuery (javascript) runs on client side, php runs on server side.
When page loaded on browser, php's job is finished.
You can call just javascript's function like this approach.

How to get multiple responses from PHP file via AJAX?

My PHP file doing 2 operations: 1. Submits data from form into db table, 2. Sends email.
What I want to do is to show status messages via ajax. For example, "First operation done, please wait for second" and then when second one will be finished show the next message "Second operation done too". Now my ajax looks like that.
How can I modify it?
//add status data to form
form.data('formstatus', 'submitting');
if (validate()) {
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
dataType: "json",
data: formData,
success: function (data) {
$.notifyBar({
cls: data.status,
html: data.message
});
form.data('formstatus', 'idle');
}
});
}
in the success block you can perform another ajax call. That's the simplest. You can do it to in .success(), .ajaxSucces(), .complete(), or .then() function like this: $.ajax(...).success(...);
ideally you would embed the code in a function, by example
$.ajax({
url: formUrl,
type: formMethod,
dataType: "json",
data: formData,
success: function (data) {
notifyResponse(data);
form.data('formstatus', 'idle');
sendMail();
}
});
function sendMail() {
$.get(mailUrl, function(data) { // or $.post(...
notifyResponse(data);
});
}
function notifyResponse(data) {
$.notifyBar({
cls: data.status,
html: data.message
});
}
If you've to do two operations that have different execution times, just send two different AJAX queries, and get the responses from them.
Divide your PHP service in two parts. If the second part depends on the first, instead of sending the two requests at the same time, send the second request when the first one returns.
In other words, in your success callback, you're going to notify the user that the first operation has been completed and you proceed to call the second operation, whose success callback will inform that the second operation has been completed.

Where am i going wrong - ajax

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.

jquery repeat process once get reply from php file

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.

Categories