[英]how to update a value in database using jquery when a link is clicked in php
当在php文件中单击链接时,我想增加数据库中的count字段。 因此,我将以下jquery部分添加到了我的.php文件中。 但是,它仍然行不通。 请帮忙!
<body>
<a href="http://www.google.com" id="click">click here</a>
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
code.php:
<?php
$conn=mysqli_connect("localhost","root","","sample");
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($connection);
?>
您在代码中犯了几个错误。
更新资料
您可以从ajax发送带有data
SID输入类型文本,并可以使用$sid = $_POST['sid']
在php
文件中获取值。
<body>
<a href="http://www.google.com" id="click">click here</a>
<input type="text" value="" name="sid" id="sid">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(e){
$('#click').click(function(event)
{
var sidvalue = $("#sid").val(); /*from here you get value of your sid input box*/
event.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php",
data: 'sid='+sidvalue ,
success: function() {
window.location.href = 'https://www.google.com/';
}
});
});
});
</script>
在ajax成功响应之后,您可以重定向到您想要的位置。
代码.php
<?php
$conn=mysqli_connect("localhost","root","","sample");
$sid = $_POST['sid']; // use this variable at anywhere you want.
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($conn);
?>
在code.php
的mysqli_close
您应该使用$conn
而不是$connection
。
使用此代码。 它可能会帮助您。 我刚刚在localhost中测试了所有东西。 这是完美的工作。
在点击事件被preventDefault()
时使用preventDefault()
。
<body>
<a href="http://www.google.com" id="click">click here</a>
<script>
$(function ()
{
$('#click').click(function(e)
{
e.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
在ajax成功上重定向您的链接。 像这样 -
<body>
<a href="javascript:;" id="click">click here</a>
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php",
success: function(response){
window.location="http://www.google.com";
}
});
});
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.