user2710234
user2710234

Reputation: 3225

jquery ajax / php poll database for changes

i am using thie jquery code to poll my database:

jQuery(function($){
  setInterval(function(){
    $.get( 'getrows.php', function(newRowCount){
      $('#rowcounter').html( newRowCount );
    });
  },5000); // 5000ms == 5 seconds
});

and display the results here:

<p>There are <span id='rowcounter'>xx</span> rows in the DB.</p>

but i am not sure what to put in the getrows.php file... does there need to be any html tags with an ID of rowcounter or newRowCount?

Upvotes: 0

Views: 561

Answers (4)

Aristona
Aristona

Reputation: 9361

You're simply requesting getrows.php and expecting a response from it.

You can do anything there, as long as you echo something. Like:

<?php

     echo rand(1,10);

?>

When jQuery requests this page, PHP will generate a random number, and jQuery will append it to HTML.

Basically, you can respond anything there. jQuery doesn't care what you're responding.

Upvotes: 0

ngasull
ngasull

Reputation: 4216

jQuery intelligently guesses the type of data returned by your php script (definable in your php request's script with ContentType).

A simple php script would return HTML/Text data, so you just have to "echo" your number in your PHP script. Then your newRowCount JS value will contain your PHP-echoed number.

Upvotes: 0

Oladapo Omonayajo
Oladapo Omonayajo

Reputation: 980

After getting the number of rows in your database, just do:

<?php echo $rowCount; //Or whatever value you want to show ?>

That's all

Upvotes: 1

David
David

Reputation: 219077

Looking at that code, all the PHP file needs to do is emit a number. You'd have normal data-access code like you would anywhere else, then just:

echo $someValue;

Upvotes: 0

Related Questions