So, I'm sending a form with ajaxForm which will send data, open spinner.gif, then on success close spinner and reload the page:
$('#form').ajaxForm({
beforeSubmit:function(){
spinnerLoad();},
success: function(data){
spinnerDone();
window.location.href ="sample.php";
}
});
Then the form is handled like this:
if (isset($_POST['save'])){
exec("/directory/script.php $args");
}
So this page, 'script.php' executes another script on DB, so it may take a long time. When there is not many data, it works fine, but whenever I have much, after a time 'script.php' wents 404, and the spinner.gif never stops.
I need to find a way to extend timeout somehow (ajax timeout option seems not suitable) or another way.
Sending the script.php page or the DB script to background is not ok - it must be finished in order to continue working.
I'll be glad to any comments/directions to look.
Related
I have a PHP script on my server that needs to be run from my clients websites using Javascript in a plain HTML page. After the script is run the HTML page will redirect. The problem is that sometimes the script doesn't run before the redirect happens.
This is the code I am using...
$.ajax({
async: false,
type: 'GET',
url: 'the_URL_of_the_PHP_on_my_server.php',
success: function(data) {
}
});
window.location="the_URL_for_the_redirect";
The PHP script on my server is to track hits/sales etc. Is there are way I can force the page to wait for the script to complete before the page redirect.
The HTML page and the PHP page are on different servers. Also, the HTML page is being used on lots of different websites, so I can't give them all permission to access my server. I'm not sure if that's causing a problem or not.
I don't need any information back from the PHP script I just need it to run.
Thank you.
The success function runs when you get a response (unless it was an error, in which case the error function you haven't defined would run).
If you want some code to run after you get a response, put it inside those functions instead immediately after the code which sends the request.
That said: The point of Ajax is to talk to the server without leaving the page. If you are going to go to a different page as soon as you have a response, then don't use Ajax. Use a regular link or form submission and then having an HTTP redirect as the response.
This is normal, that this situation happens.
because $.ajax is async and won't wait till success method
change your code to
$.ajax({
async: false,
type: 'GET',
url: 'the_URL_of_the_PHP_on_my_server.php',
complete: function(data) {
window.location="the_URL_for_the_redirect";
}
});
UPDATED
changed function success to complete
difference is =>
complete will be called not matters what happened with request
UPDATE 2
think about #Quentin variant by html redirects.
I am calling one jquery ajax request in my PHP code. This code fetch the data from database and export into the excel file. Once ajax request will success, i will get excel file popup download box. This feature is working fine in all browser.
Now, problem is when that jquery request is taking more time (7-8 minutes), excel file is created on the server, but download box is not popup and after 30 minutes i am getting timeout error.
what could be the problem, file is created on the server in 7 minutes but i am not getting any response from ajax request. I am also checked the timeout for ajax request it is set for 30 minutes.
Even if you manage to solve the timeout, making your clients wait 7 to 8 minutes without any progress feedback will be far from ideal. Better way would be to initiate the export on the server and return immediately. Once this returns you can give a progress message that says 'Export in progress..' or something. Then you can have an AJAX call that periodically checks the status of the export and returns the appropriate status message. Once exporting is done, you can change the progress feedback to 'Export complete: Download file' with Download file being a link to the excel file created on the server. you can also trigger a click on that link via code to automatically start the download.
i.e.
Assuming you have a DIV with class status which shows the export status
First AJAX call to initiate the export:
$.post({
url: '/export/',
...
success: function(data) {
$('.status').html('Export in progress. Please wait...');
}
});
Second AJAX call to poll export progress
$.post({
url: '/exportstatus/',
...
success: function(data) {
if(data=='OK') {
$('.status').html('Export complete: <a class="exportedfile" href="/path/to/exported/file">Download File</a>');
setTimeout(function() {
$('.status').find('a').click(); // trigger autostart of download
}, 1000);
}
}
});
You're doing it wrong: you don't want to force a user to be stuck on a page for more than a few seconds at most in order to get service from your app.
Instead, use a widget that will periodically query a status page (with ajax, of course) and display a message when the job is done.
(What kind of excel file is taking 7 minutes to generate? A db dump?)
Edit:
Different browsers will behave differently with long ajax requests, so don't depend on them waiting around forever even if the user is willing to. Your app will be much more robust if you decouple requesting a report generation and downloading the report.
This should give you an idea of what I'm talking about:
create_my_excel_file.php:
$_SESSION['excel_status']='generating';
create_the_excel_file();
$_SESSION['excel_status']='finished';
check_status.php:
echo $_SESSION['excel_status'];
user_interface.php:
<script type="text/javascript">
function initiateRequest(){
$.ajax('create_my_excel_file.php');
setInterval('checkForCompletion()', 5000);
}
function checkForCompletion(){
$.get('check_status.php', function(data){
if('finished'==data){
alert('Completed! Download the file now.');
location.href='file_download.php';
}
});
}
</script>
Generate the file
i've been doing a lot of ajax scripts and every time something seems to be different.
in this case i have a form that i want to post
<form id="sss">
<input id="qqq"/>
<input type="submit" id="s" href="Search!"/>
</form>
<div id="rrr"></div>
and
$('#s').click(function(){
$.ajax({
url: 'foo.php',
data: {
query: $('#q').val()
},
success: function(data) {
$('#rrr').html(data);
}
});
return false;
});
and
if(isset($_REQUEST['query'])){
print_r($_REQUEST['query']);
}
what happens is that in <div id="rrr"></div> gets loaded the print_r($_REQUEST['query']); and all the rest of the html page.
i only want to return $_REQUEST['query']
weird!?
any ideas? What this success: function(data){} actually means?
Thanks
If you are requesting the same page that you are current displaying, then your if statement doesn't stop processing, so the rest of the page is returned as well. You either need to die() afterward, or (recommended) create a separate page entirely dedicated to handling AJAX requests. Here's an example of how to properly stop processing:
if (isset($_REQUEST['query'])) {
print_r($_REQUEST['query']);
die(); // stop processing.
}
In regards to your second point, I think you might be misunderstanding the technical details of what's actually happening here:
Client requests foo.php from server. Server executes foo.php according to the logic in the page, and sends response output to browser. Browser renders the page.
Client sends AJAX request (which is nothing more than a request that happens asynchronously, i.e., separately from the browser loading a page) to foo.php?query=...
Server executes foo.php?query=... (just like it did in step (1)!), which causes the first if to trigger before returning the rest of the html in response, so the same page is returned except with the query output at the top (Try going directly to foo.php?query=... in your browser and I think you'll see what I mean).
However, instead of the response being rendered in the browser, since it was an AJAX request, the response is captured into a variable, data.
The callback function success(data) is executed, passing the exact output returned from the server as-is from the AJAX request (i.e., the variable contains the same as viewing the source of foo.php?query=... in your browser), which is then processed according to your logic. In this case, you are dumping the contents into a div, so you see the output correctly.
Please take a moment to install and run Fiddler, so you can see the exact data that is flowing back and forth as you load the page in your browser, and then watch what happens as you make an AJAX call. Perhaps it will make the data flow and results you are getting much clearer.
Hope this helps!
I have some script that takes a form and sends it to php using jquery ajaxSubmit.
Server side must copy image from one location to another.
using this code copy($img_dir_file,$mini_dir_file); is ok if u have few images.
But if u have let's say 20+ images php works slowly, and responds to ajax before finishing it's job. Thus Ajax changes content to blank page , cause result is not ready.
If you refresh page a bit later, everything is ok cause php finishes his work.
So please tell me what should I do with this problem ?
script is something like this
$('#save_edited_article').live('click',function(){
$('#edited_article_form').ajaxSubmit({
success: function(responseimage){
$('#main_content').html(responseimage) } }); });
You could use a Promise which will inform the browser when the job is complete.
Check out the jqXHR Object as part of Ajax on JQuery - you could then change your main content when the jqxhr object ( which works as a Promise) is complete :
jqxhr.done(function(){ $('#main_content').html(responseimage); });
Edit
An example using your code could be:
$("#edited_article_form").submit(function() {
var jqxhr = $.post(
"foo.php",
$("#edited_article_form").serialize()
);
jqxhr.fail(function(){ alert("fail") });
jqxhr.done(function(responseimage){ $('#main_content').html(responseimage) });
});
Disclaimer : This was written on the fly and may not compile. It is for example purposes only
Have the AJAX call check to see if it's complete, if it's not, keep polling every few seconds until it's ready.
Updated jQuery and ajaxSubmit plugin and everything works nice.
I have a File which process many other files and may take upto 30mins to process. I do an AJAX request to the file in the front end. The file outputs to another temporary file regarding the percentage of completion. And when it finishes it outputs a success message as its own XML output (not to the tmp file).
The problem i am having is, when the processing time is small .. say max upto 3mins, the AJAX request (made through jQuery) stays alive. But a time out occurs when the processing takes longer time (above 4mins). And the AJAX connection is cut. How do i prevent it and make it stay alive till the browser is closed?
You won't be able to do that. Unless it is a comet server, that can keep the connection alive at the server side and when there is any update to the data, it pushes out the contents.
In your case, the only way i can think of is doing this:
function ajax_call () {
$.ajax({
url : 'get_file_processing_output.html',
success : function (response) {
check your response, if file processing is not finished, then call ajax_call() again
if it is finished, then just do whatever you need.
},
timeout : function () {
time out then directly call ajax_call() again, maybe with a time interval would be better
}
})
}
I have a success call back above in ajax, because i feel you should response something from your server side to tell the client that the processing is not yet done.