AJAX使用从PHP生成的HTML调用的函数来更新MYSQL数据库
我有一个php页面,用于生成和显示表格.对于表格的最后一行,我想显示带有"onclick"功能的图像.这会将所选行的用户名发送到脚本,该脚本将使用AJAX更新数据库.该表显示正常,但AJAX无法正常工作.我的显示图片的php是:
I have a php page generating and displaying a table. for the last row in the table i want to display an image with an 'onclick' function attached. this will send the username for the selected row to a script that will use AJAX to update a database. The table displays fine but the AJAX is not working. my php to display the image is:
echo "<td> <img id='tblimg'
onclick='like('" . $row['Username'] . "')'
src='like.jpg' alt='like/dislike image'
width='80px' height='30px'></td>";
javascript函数是:
The javascript function is:
<script type="text/javascript" >
function like(user)
{
$.ajax(
url: "update.php",
type: "POST",
data: { 'username': user, 'liked': '1' },
success: function()
{
alert("ok");
}
);
}
</script>
这是update.php:
And here is update.php:
<?php
$con=mysqli_connect("","sam74","********","sam74");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Username = $_POST['username'];
$Liked = $_POST['liked'];
$sql = "UPDATE 'followers' SET 'Liked' = '$Liked' WHERE 'Username' = '$Username'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
此代码中有一些错误,请允许我逐行帮助您.
There are some mistakes in this code, let me help you line by line.
echo "<td> <img id='tblimg'
onclick=\'like('" . $row['Username'] . "');\'
src='like.jpg' alt='like/dislike image'
width='80px' height='30px'></td>";
javascript函数是:
The javascript function is:
先转义onclick事件的报价
Escape your quotes for the onclick event first
function like(user)
{
$.ajax({
url: "update.php",
type: "POST",
data: { 'username': user, 'liked': '1' },
success: function()
{
alert("ok");
}
});
}
将{和}添加到ajax调用
add { and } to the ajax call
从表名和字段中删除引号
Remove the quotes from table name and fields
$sql = "UPDATE followers SET Liked = '$Liked' WHERE Username = '$Username'";
在ajax成功执行以及函数启动之后,您始终可以打印一条消息,以查看函数是否正在被调用,并且如果php脚本返回了一些错误,请为此使用警报
in ajax success and after the function begins, you can always print a message to see if your function is being called, and if php script is returning some error, use an alert for that
更新
success: function(data){
alert(data); // this will print you any php / mysql error as an alert
}
更新2
像这样编写onclick选项.
Write your onclick option like this.
echo "<img onclick=\"like('" . $row['Username']. "');\"
src='like.jpg' alt='like/dislike image'
width='80px' height='30px' />";