-2

I have javascript code passing id to my php script in intervals of time, once the id is not being passed (it means the user has closed the javascript page). Block in if statement should run in php script. But this scenario is not happening with me.

Code is below

JavaScript

<script type="text/javascript" src="jquery-1.11.1.js"></script>
<script type="text/javascript" >

$(function(){
    // set interval for 5 second
    setInterval(function(){
            $.ajax({url: "test9.php?id=('1')"

            });
    }, 50000);
});

</script>

PHP

<?php
while(true)
{
    $id = $_GET['id'];
    if(isset($_GET['id']))
    {
        file_put_contents('/tmp/phptest1234.txt', 'test');
    }
    else
    {
        file_put_contents('/tmp/phptest.txt', 'test');
    }
}
?>
Blunderfest
  • 1,854
  • 1
  • 28
  • 46

3 Answers3

1

If the page is closed, then the page will not send any AJAX request to your server. So that condition will not arise. So it'll be only in if, the else part will not be executed at any time.

If you want, that the get request will be called when the page will be closed without if, then you can try the following:-

<body onbeforeunload="closePage()">
</body>

And then in the closePage function make the ajax request without id:-

<script type="text/javascript" >

$(function(){
// set interval for 5 second
setInterval(function(){
        $.ajax({url: "test9.php?id=('1')"

        });
}, 50000);
});

function closePage(){
 $.ajax({url: "test9.php

 });
}
</script>
Indranil Mondal
  • 2,799
  • 3
  • 25
  • 40
0

The url should not have ('1'), you need to change the following line

$.ajax({url: "test9.php?id=('1')"

to

$.ajax({url: "test9.php?id=1"
caspian
  • 1,804
  • 14
  • 14
0

you can pass you id by AJAX data attribute, like this.

by get request

    $.ajax({

        type:'get',
        url:'test9.php',
        data:{'val':value},
        success:function(data){
              }

by post request

    $.ajax({

        type:'get',
        url:'test9.php',
        data:{'val':value},
        success:function(data){
              }
Suneel Kumar
  • 5,621
  • 3
  • 31
  • 44