Search code examples
jquerypolling

JQuery polling a database and changing dom element if true


OK I created my self a validation.php this will return

{"exists":false,"data":"", "id":101}

or

{"exists":true,"data":"www.example.com/thumbnail1.jpg", "id":101}

The script is below

//no need to continue if there is no value in the POST username
if(!isset($_POST['id']))
 exit;
$var = $_POST['id'];
//initialize our PDO class. You will need to replace your database credentials respectively
$db = new PDO('mysql:host=HOST;dbname=DBNAME','USER','PASS',array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

//prepare our query.
$query = $db->prepare('SELECT * FROM cont_pic WHERE pic_id = :id');
//let PDO bind the username into the query, and prevent any SQL injection attempts.
$query->bindParam(':id', $var);
//execute the query
$query->execute();
$exists = $query->fetchColumn(6);

//return the json object containing the result of if the username exists or not. The $.post in our jquery will access it.
echo json_encode(array('exists' => !empty($exists), 'data' => $exists, 'id' => $var   ));
// echo $var;
print_r($exists);
?>

Now I got my half done JQuery polling script, I need help to make this script work. Basically what I want is if exists is true I need to replace an image with an id that's equal to the json response and replace the img src with the data in the response and stop the poll. If it's false continue polling.

setInterval(function(){
    $.ajax({ url: "validation.php", success: function(data){

    }, dataType: "json"});
}, 30000);

Many Thanks!!

A


Solution

  • var poller = setInterval(function(){
        $.ajax({ url: "validation.php", success: function(data){
            if (data.exists) {
                clearInterval(poller);
                $("#img"+data.id).attr("src", data.data);
            }
        }, dataType: "json"});
    }, 30000);