[英]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 我有这段代码,假设是要从mysql提取数据,这里有用户列表,因此,如果您单击一个用户,它将显示该用户的详细信息,但是每当我单击例如用户3或4时,它只会获取用户1。我需要帮助这是
fetch.php 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 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()
使用mysql_fetch_array()
的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. 变量“ temp”始终会获取锚标记的第一个ID。 Rest of your code is OK. 其余代码都可以。
谢谢'Honza Haering',它现在正在工作,问题是我使用了var temp = $('a')。attr('myval'),但正确的是这个var temp = $(this).attr('myval')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.