-1

i have a simple javascript function which runs the meta_data.php file every second. The meta_data.php file contains a simple database query. If the return of that database query is a specific value i want to stop the execution of the meta_data.php file. So my plan is to simply clear the Interval of the function check_data in the meta_data.php file.

Is it possible to set the Interval of the function "check_data" from the meta_data.php file? If yes, how can i do this?

<script>
$(document).ready(function {
    setInterval(function check_data () {
        $('#p_data_info').load('https://demo/includes/meta_data.php')
    }, 1000);
});

Thanks for your help and time, Dave

Dave
  • 3
  • 2
  • Possible duplicate of [How do I clear this setInterval inside a function?](https://stackoverflow.com/questions/2901108/how-do-i-clear-this-setinterval-inside-a-function) – MonkeyZeus Nov 12 '18 at 20:03

1 Answers1

0

You can't stop the interval directly from PHP. It runs on the server, JS runs on the client.

The best way would be for the PHP script to return JSON rather than HTML. The JSON can contain a flag saying whether the interval should keep going or not, in addition to the HTML in another property. Then the JavaScript checks the flag and cancels the interval.

$(document).ready(function {
    var interval = setInterval(function check_data () {
        $.getJSON('https://demo/includes/meta_data.php', function(data) {
            if (data.stop) {
                clearInterval(interval);
            }
            $('#p_data_info').html(data.html);
        });
    }, 1000);
});

Another solution would be for the HTML that's returned by meta_data.php to include a <script> tag that clears the interval. Since that HTML doesn't run in the scope of this $(document).ready() function, you'll need to assign the interval to a global variable rather than a local variable.

This second solution is a poor design because it means all pages that use it must use the same global variable for this interval function.

Barmar
  • 741,623
  • 53
  • 500
  • 612