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()
Related
I'm trying to make an async call to the same page but for some reason, the async call is not being made and hence getting "userinfo" undefined error! could someone please tell me what I'm doing wrong in this thank you!
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$( document ).ready(function() {
//getting location of the user and assigning it to the variable
$.get("http://ipinfo.io", function (response) {
var usercity=response.city;
console.log(usercity);
$.ajax({
//no need to provide url since we are making async call on the same page
type: "post",
data: {cityinfo:usercity},
});
}, "jsonp");
});
</script>
<?php
session_start();
$usercity=$_POST['cityinfo'];
echo $usercity;
?>
First, you make a regular request to the PHP page. $_POST['cityinfo'] is undefined at this stage because you don't set it. The page includes an error message telling you that.
Second, you make a JSONP request to ipinfo.io, and call a callback function when you get a response.
Third, you make a second HTTP request to the PHP page. This time you do define $_POST['cityinfo']. You have no success handler to do anything at all with the response so, although $_POST['cityinfo']; is set, you don't see any effect of that (unless you were to use the developer tools Network tab to examine the response itself).
It is important to note that this is a second, distinct request to the same URL. The JavaScript does not travel back through time and set the $_POST['cityinfo']; variable in the previous request (and it is the response to the previous request that is still displayed in the browser window).
Once my page is loaded, I perform an Ajax call to a php script, which updates my server. However this script can sometimes take over a minute to complete, and while the script is running, I am unable to perform other Ajax calls, which I need to handle - i.e the first Ajax call should not interrupt the other Ajax calls. Any idea how to do this?
First Ajax call:
$(document).ready(function () {
$.ajax({
url: "checkForUpdatesByCoach.php",
success: function(arg){
if(arg == "200"){
$('body').prepend("<div style='text-align:center;margin-bottom:-12px;' onClick='location.reload()' class='alert alert-success'>Dine hold er blevet opdateret.Tryk for at opdatere!</div>").fadeIn("slow");
}
}
});
});
Second Ajax call (a user triggered call):
$.ajax({
type: "POST",
data: {data:dataAjax},
url: "updateSwimmer1.php",
success: function(arg){
//updating UI
}
});
adeno's comment above is correct.
"in PHP only one script at a time can operate on the same session, so
as to not overwrite session data etc. So when doing two ajax calls to
PHP scripts within the same session, the second has to wait for the
first to finish"
to help speed things up you can write to and end a session early(session_write_close()) to release the session-lock and allow another script using the session to continue.
note: you can still read from your $_SESSION variable after calling session_write_close but you may no longer write to it.
you can find a good example of this here: PHP Session Locks – How to Prevent Blocking Requests
example provided from the link above:
<?php
// start the session
session_start();
// I can read/write to session
$_SESSION['latestRequestTime'] = time();
// close the session
session_write_close();
// now do my long-running code.
// still able to read from session, but not write
$twitterId = $_SESSION['twitterId'];
// dang Twitter can be slow, good thing my other Ajax calls
// aren't waiting for this to complete
$twitterFeed = fetchTwitterFeed($twitterId);
echo json_encode($twitterFeed);
?>
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.
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.
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