I Have a PHP script which need to be run in background and with the help of
ignore_user_abort(true);
Script can be run even close the browser.
But I don't want to close browser every time,
$.ajax({
type: 'POST',
url: 'myphp.php',
data: values,
success: function(re) {alert("somthing");}
});
browser always wait for AJAX response even without mentioning of success:
Is there any way to stop browser waiting time, so that user can browse website normally without waiting for finishing of php script.
handle request with
jQuery XHR
var xmlHttpRequest = $.ajax( {
//....
});
xmlHttpRequest.abort();
At the beginning of your PHP code try to put this :
ob_start();
ob_end_flush();
That will send content to your ajax script and stop it.
I didn't try so it's just an idea ;)
You could try
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
though apparently whether it works depends on the exact PHP version. Or you could just terminate the AJAX call from the client side after a while (possibly after you start receiving content).
That said, the essence of AJAX calls is that "user can browse website normally without waiting" even while they are running, so I'm not sure there is a point to what you are trying to do.
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 have made a simple chat application which uses long-polling approach using jquery,
function sendchat(){
// this code sends the message
$.ajax({
url: "send.php",
async: true,
data: { /* send inputbox1.value */ },
success: function(data) { }
});
}
function listen_for_message(){
// this code listens for message
$.ajax({
url: "listen.php",
async: true,
timeout:5000,
success: function(data) { // the message recievend so display that message and make new request for listening new messages
$('#display').html(data);
listen_for_message();
}
});
}
THIS SHOULD HAPPEN : after page loaded the infinite request for listen.php occurs and when user sends message, the code sends message to database via send.php.
PROBLEM is, using firebug i've found that send.php request which is performed after listen.php request, is remains pending. means the request for send message is remains pending.
The issue was because of session locking;
both send.php and listen.php files use session variables,
so session is locked in listen.php file and the other file (here send.php file) can't be served after the session frees from serving another file ( here listen.php).
How do I implement basic "Long Polling"?
the link above is a similar question that may help you.
it does not have to be on a database, it can be saved on a tmp file, but your problem is that you are choking the browser by performing too many requests, any one browser handles two requests at a time, which means you should really allow the browser to finish the first requests first then do the second one... and so on...
you do not need to do send.php and listen.php, because you can do it simply on one page both of them.
function check(){
$.ajax({
url : 'process.php',
data : {msg:'blabla'/* add data here to post e.g inputbox1.value or serialised data */}
type : 'post',
success: function (r){
if(r.message){
$('#result').append(r.message);
check();//can use a setTimeout here if you wish
}
}
});
}
process.php
<?php
$msg = $_POST['msg'];//is blabla in this case.
$arg['message'] = $msg;//or grab from db or file
//obviously you will have to put it on a database or on a file ... your choice
//so you can differentiate who sent what to whom.
echo json_encode($arg);
?>
obviously this are only guide lines, but you will exhaust your bandwidth with this method, however it will be alot better because you have only one small file that returns either 0 to 1 byte of information, or more if there is a message posted.
I have not tested this so don't rely on it to work straight away you need a bit of changes to make it work but just helps you understand how you should do it.
however if you are looking for long pulling ajax there are loads of scripts out there already made and fine tuned and have been test, bug fixed and many minds help built it, my advice is don't re-invent the wheel
<?
if($_POST['begin'])
{
while(1)
{
echo "1";
sleep(2);
}
die();
}
?>
<span class="answer"></span>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "exp.php",
data: "begin=1",
success: function(msg){
$(".answer").html(msg);
}
})
})
</script>
It, of course, doesn't work. What should I change to make it work? Can I avoid using setInterval, setTimeout or other functions in javascript?
By the way, what I am trying to do here is to write number 1 every two seconds.
I've never tried it, but the XMLHttpRequest interface supposedly supports streamed requests. In particular there is the .readyState==3 which denotes partial results (See spec http://www.w3.org/TR/XMLHttpRequest/#event-handler-attributes).
When you don't want to set an interval handler, then you will have to override the actual XHR callback, because the jQuery success: will really only fire on completion.
xmlHttp = $.ajax({ ... });
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState >= 3) {
alert(xmlHttp.responseText);
}
};
Note that the responseText will always contain the accumulated data. So you have to split it up on \n or something, if you want to read the latest 1.
Ok, I think I know what you want. It's weird .. but fine.
<script type="text/javascript">
$(document).ready(function() {
function fetch_a_one() {
$.ajax({
type: "POST",
url: "exp.php",
data: "begin=1",
success: function(msg){
$(".answer").html(msg);
fetch_a_one();
}
})
}
fetch_a_one();
})
</script>
<div class="answer"></div>
PHP script:
<?php
sleep(2); // way two seconds
exit(1); // print 1
?>
Minus some delay from starting the Ajax request and lag from the server, this should print '1' every 2 seconds .. no idea why you want this.
This is the wrong approach, because your success function isn't going to run until it receives a response from the server which isn't going to happen as it's in an endless loop.
You will need to handle the timings in JavaScript with, as you say, setInterval. Of course if all you're trying to do is simply print the number 1 every five seconds you don't need to make any calls to the server-side (although I presume there's something more you're trying to achieve eventually - you might want to expand on that a little).
You could look into opening a WebSocket back to the server do handle this kind of ongoing communication. Look into something like PusherApp - http://pusher.com/
You're probably going to have to use JavaScript for this. You can continually poll the server resource to get information from it, but the actual looping and delaying will need to be in JavaScript.
The reason for this is because the PHP script needs to finish processing at some point. It's not streaming output to the client, it's building output to send to the client. In the code you provide, it's forever building the output and never sending it.
You can try to flush your buffer from the PHP script to send some output to the client while still building more output, but take a look at the caveats in that link. It's not really a clean way to accomplish this and will probably cause more problems than it solves in this case. At some point the server resource needs to stop processing and commit to a response. Trying to short-circuit that basic concept of HTTP will likely be a bit of a hack.
I think the problem is, that you're writing endless PHP loop.
jQuery when starting ajax request, will be waiting for script to finish his job. However the script would never ends - so the browser will never get the full answer.
You need to use setTimeout, there is no other way - at least no other easy and safe way.
i have a php web application, where i use an authentication method. I have a script logout.php in the same directory as the index file.
I want that the code in the logout.php be executed if the used mid session decides to exit or navigate away from the page.
ive tried using
function closeIt()
{
var exit = confirm("Are you sure you want to end this chat session ?");
if(exit==true){
$.ajax({
type: "GET",
url: "logout.php",
success: function(){ alert("Done");}
});
}
}
window.onbeforeunload = closeIt;
i get the confirm box,
but i am not getting success, am i doing somethign worng or do i need a new approach all together ?
The Ajax call is performed asynchronously, so the call is made and processing is passed back to the page immediately, which then closes before the ajax call completes.
You need to make a synchronous call to make this work.
A in AJAX stands for asynchronous. You may want to use synchronous XMLHttpRequest or return false at the end of closeIt() (that should prevent closing window) and in your success function, change onbeforeunload to null and close the window with window.close()
I want to execute an ajax query when one user close the window. Ive got this code:
var $jQ = jQuery.noConflict();
$jQ(window).bind('unload', function() {
$jQ.ajax({
type: "GET",
url: "http://www.mydomain.com/post_untrack.php" ,
success: function(msg){
alert("Untrack");
}
});
});
I receive the "alert" event, but the script is not executed...
post_untrack.php:
<?php
mail("myemail#mydomain.com", "Script executed", "Hooray!!!");
?>
Any idea ?
Thanks!!!
To make this work, you need to add the property
async: false
to .ajax() options object, plus you need to execute it on onbeforeunload so in jQuery
$jQ(window).bind('beforeunload',...);
By default, ajax requests are asynchronous. So although you may start the request when the window is unloaded, it will probably get cancelled immediately and never actually sent to the user. Although you could make the request synchronous, synchronous requests really mess up the user experience by bringing the browser to a screeching halt.
More about this in this other SO question and its answers.
And of course, any ajax calls will be subject to the Same Origin Policy, if that's relevant.
is the URL being posted to on the same domain as the page that is trying to do the ajax call?
http://en.wikipedia.org/wiki/Same_origin_policy