Engima Engima - 9 months ago 48
Ajax Question

Continuously Query Database PHP

I need to query a database every .5 seconds, to see if a certain field is null or not. I already have this working in Java, but as PHP does not have threads I'm not too sure how to go about it. I've seen a lot of things about AJAX but I'm finding it very hard to apply it to my situation since I've never used AJAX before.

Basically I have a 'waiting' page. It will display an image and some text that says 'Waiting for Opponent'. In the background it will need to call my checkForOpponent() function, which returns either true or false.

If checkForOpponent == true, the person will be redirected to another page. If it's false, it will continue calling the method every .5 seconds.

Answer Source

You can post to a PHP page that checks the database for you every half a second using javascript and jQuery, the JS will be in (or included in) your loading page:

var MyVar = ''; //whatever the default state is    
        dataType: 'text',
        data: {state:MyVar}, 
          console.log('data loaded: ' + data); //just to check the console
          if(data === "something i want"){
            //Opponent state is good, change whatever you want
            //Do the opposite
    }, 500);

In your checkForOpponent.php you can check for $_POST

  //query database
  //depending on returned result
  echo 'something'; //this something will be read in your JS code above and act accordingly