phpnoob phpnoob - 3 months ago 12
jQuery Question

How to get a variable from a php file with javascript?

What I'm trying to do is query a variable in my check.php file and pull that variable to my index.php file, compare it to a different variable, and reload the page if they don't match.
This is what I have so far:

check.php:

some query
echo json_encode($checknew);


index.php:

var checkold = "<?php echo $old['ertek'];?>";

function checkupdates() {
setInterval(function() {
$.ajax({
type: 'POST',
url: 'check.php',
dataType: 'json'});

if (checkold != checknew){
location.reload();
}
, 3000)}
};

$( document ).ready( checkupdates );


How do I "catch" the $checknew variable from php and turn it into a variable for my function?

Answer

In your check.php you are echoing json_encode($checknew). Be specific what you are writing if it is only one value then you can simply write echo $checknew;.
And your JAVASCRIPT should be like this

var checkold = "<?php echo $old['ertek'];?>"; 

function checkupdates() {
  setInterval(function() {
    $.ajax({
        type: 'POST',
        url: 'check.php', 
        success:function(checknew){
          if (checkold != checknew){
            location.reload(); 
          }  
        }
    });

     },3000);
}

$( document ).ready( checkupdates() );
Comments