Ajax query when user closes the window? - php

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

Related

Calling PHP on another server from Javascript, and waiting for it to complete

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.

how can catch event ajax send to server, not waiting for server respond

My problem is that when user click on link on website, i using jquery to catch event click and ajax to update database
if i do something like this, it will take a litle time because of the waitting for respond form server
$.ajax({
success: function() {
...
window.href = link;
}
});
I want something like
$.ajax({
alreadysend: function() {
...
}
});
I read document ajax, but i can't find any solution for my problem.
EDIT: i solve my problem, i need to work hard on jQuery, thanks you all
It does that by default since Ajax is asynchronous! If you want code to execute regardless if the server was reached and responded, simply put your executing code after the Ajax block.
On the flip side, if you want to tell if the user already made the submit action, you can use a application-scope variable to toggle on call and completed events. (I.e set to true when the user initiates a Ajax call. On completion, set to false. Disallow the call I already true)
Simply call your code just after the call to $.ajax:
$.ajax({success: function(){
// done after server response
}});
// do something immediately after
Ajax call is asynchronous, so your script is not blocked.
Why don't you just call the function you want to call after the $.ajax line? Like this:
$.ajax({ ... });
do_things();
Edit If you want to do a redirect, you'll have to wait for the AJAX call to come back to be sure it was successful or not. If you don't care whether it was successful, and just care about it making the call at all, you can place it in the line after the $.ajax call, since the call happens asynchronously. In any case, we need some more information on what you want to achieve exactly.
I am not 100% sure of what you are trying to do, but if you want to wait for the ajax call to return before your code carries on you can set it to do so by setting async to false, although its worth noting that this is kind of counter productive and is deprecated in jQuery 1.8.
http://api.jquery.com/jQuery.ajax/
By default, all requests are sent asynchronously (i.e. this is set to
true by default). If you need synchronous requests, set this option to
false. Cross-domain requests and dataType: "jsonp" requests do not
support synchronous operation. Note that synchronous requests may
temporarily lock the browser, disabling any actions while the request
is active. As of jQuery 1.8, the use of async: false is deprecated.

Jquery PHP without response function

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.

jquery $.ajax request remains pending

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

php ajax window close problem

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()

Categories