0

I was wondering if its possible to send a query to the database on the beforeunload event.

$(window).on('beforeunload',function() {
    console.log('beforeunload called. run query');
});

If so, how would I do it? I need to run a query to insert dynamic values into the database.

bjaeger
  • 85
  • 1
  • 2
  • 8

3 Answers3

1

You could try this, but beware that the onbeforeunload event is limited for certain browsers..

window.onbeforeunload = mySession;
function mySession(){
    $.ajax({
        url: "/../../myPHP.php",
        async: false,
        type: "GET"
    });
    return "WhatEverMessageYouFeelLike";
}

and your PHP executing query from AJAX handling..

$delete = "DELETE FROM MyTable WHERE id=" .$_SESSION['mySessionVariable'];
// your query..
urbz
  • 2,663
  • 1
  • 19
  • 29
  • Thanks. Is there a way to make it compatible with as many browsers as possible? – bjaeger Jul 04 '14 at 07:10
  • 1
    The `onbeforeunload` event is compatible for most commons browsers such as IE, Firefox & Chrome but I believe Safari and Opera are the exceptions in this case. **Update:** Opera version 15 and up now has support since they moved it to their WebKit engine. – urbz Jul 04 '14 at 07:14
0

Use a jQuery AJAX call. Assuming you're POSTing your data, try this:

$.post(
    'your/url',
    {
        your : "Post Vars"
    },
    function(data) {
        // not sure if you'll need to do anything here actually.
    },
    'json' // or 'html', or whatever you want your return format to be
);
Derek
  • 4,575
  • 3
  • 22
  • 36
0

I thinks the best way to use post by jQuery is $.post() method.but u can also use $.ajax

Sample way to use is

jQuery

$.post( "ajax/test.html", function( data ) {
  $( ".result" ).html( data );
});

jQuery Ajax

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
cyberoot
  • 340
  • 2
  • 18
  • $. post is asynchronous (note the "asych:false" on $.ajax). The browser won't sit around waiting for a response and server task may close before your code finishes. – Cuse70 Oct 08 '17 at 21:40