0

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?

4
  • 1
    You are not using the ajax call correctly. Need to use .done(function() {} to get the echo value from check.php Commented Aug 4, 2016 at 16:16
  • success: function() { and here you can do whatever you want with your variables that you got from backend } Commented Aug 4, 2016 at 16:17
  • Also, var checkold = "<?php echo $old['ertek'];?>"; is not doing what you think it is. checkold will contain the literal string <?php echo $old['ertek'];?> not the value inside $old['ertek']. Please check out Ajax Documentation Commented Aug 4, 2016 at 16:18
  • Any suggestion how should I get around this? Commented Aug 4, 2016 at 16:40

1 Answer 1

2

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() );
Sign up to request clarification or add additional context in comments.

8 Comments

yea, checknew is only one value, not an array
write only echo $checknew; :)
ok so I did what milan suggested and is working now, the only problem is the page reloads every time, even if I set $checkold="1" and var checknew="1"
Why did you set Interval? That is executing every 3sec.
Even if $checknew is just a primitive value and not an array it is still a good idea to write echo json_encode($checknew);, because then it can be ensured, that it is always properly encode no matter what the content of $checknew is and in the code it is clear that the data should be returned as json. If it is $checknew is the number 1 then output of json_encode will also be 1. @phpnoob
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.