简体   繁体   中英

How to fetch data from mysql on the same page without reloading using php and ajax

I have this code which suppose to fetch data from mysql, there are list of users so if you click one user it will show detail info of the user but whenever i click for example user 3 or 4 it fetch only user 1. i need help here is

fetch.php

<?php
       $connection = mysql_connect('localhost', 'root', '');
       $db = mysql_select_db('temp', $connection);
       $x = $_POST['id'];
       $safex = mysql_real_escape_string($x);
   $query = mysql_query("select * from class where id=$safex",  $connection);

   $result = "";

      $result .= "<div id='display'>";
      $result .="<table border=\"1\">";
      $result .="<tr><th>Name</th><th>Password(encrypted)</th></tr>";
        while($row = mysql_fetch_assoc($query)){
$result .= "<tr><td> {$row['name']}</td>"."<td> {$row['password']}</td></tr></p>";
}
$result .="</table>";

$result .= "</div>";
echo $result;

?>

and here is

index.php

    <?php
$connection = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('temp', $connection);
?>
<html>
<head>
<title>Fetch record using jQuery</title>
<style type="text/css">
#display {
margin : 225px;
}
</style>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$('document').ready(function(){

$('a').click(function(){
var temp = $('a').attr('myval');
$.post('fetch.php', {id:temp}, function(data){
$('#display').html(data);
});
});
});
</script>
</head>
<body>
<?php
$query = mysql_query("select * from class order by id desc LIMIT 2", $connection);
echo "<ul>";
while($row = mysql_fetch_assoc($query)){
echo "<li><a href=\"javascript:return(0)\" myval=\"{$row['id']}\"><h3>{$row['name']}</h3></a></li>";

}

echo "</ul>";

?>
<div id="display"></div>
</body>
</html>
<?php
mysql_close($connection);
?>

use mysql_fetch_array() intesd of mysql_fetch_assoc()

while($row = mysql_fetch_array($query)){
$result .= "<tr><td> {$row['name']}</td>"."<td> {$row['password']}</td></tr></p>";
}

The issue is not in database. The issue with your code is the statement

var temp = $('a').attr('myval');

Use the following code :

$('a').click(function(this){
    var temp = $(this).attr('myval');
    $.post('fetch.php', {id:temp}, function(data){
         $('#display').html(data);
    });
 });

The variable 'temp' is always fetching the first id of the anchor tag. Rest of your code is OK.

谢谢'Honza Haering',它现在正在工作,问题是我使用了var temp = $('a')。attr('myval'),但正确的是这个var temp = $(this).attr('myval')

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