简体   繁体   中英

How to receive data from a database using AJAX

I use a comment box in my web page and saved user input comments. Now what I want is to display them using AJAX. I set a javascript timer to get comments one by one. But I don't know how to use AJAX to retrieve data. This is the php file

<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("continental_tourism");
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
} 

$comment_number = rand(1,$counter);
$query_comment = mysql_query("SELECT * FROM comment WHERE comment_id = '$comment_number'");
if (!$query_comment) { 
die('Invalid query: ' . mysql_error());
}   
while($result_comment = mysql_fetch_array($query_comment)) {

echo $result_comment['comment'];

}
?>

following is the script part in the main file.

function timeMsg()
{
var t=setTimeout("show_comment()",3000);
}

function show_comment(){

}

How should i write the AJAX code to the?

function show_comment()

If someone can explain the AJAX code line by line, I'll be great full.

You have to move your all php script to another php file say getdata.php and use your ajax function in your file where you want to show the data say it is index.php. (this is for easy to use code). Now your index.php file should look like

<html>
  <body>
    <div id="comments"></div>
  </body>
  <script src="include/jquery.js" type="text/javascript"></script>
  <script type="text/javascript>
    function show_comments() {
         $.ajax({
            url:getdata.php
            success:function(data){
               $("#comments").append(data);
            }
         }); 
  </script>
 </html>

I am using jquery.ajax function of jquery. This is some hint how you can do this. I hope it will help you to accomplish your task.

Use jQuery's .get() method using the link to your PHP script as URL. That should call your PHP script and your script should echo the output.

You should consider json_encode -ing your output from php script before echoing it.

And I think, instead of doing this -

$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
} 

you can query SELECT COUNT(comment_id) from comment and get the count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM