![](/img/trans.png)
[英]How to send a string along with file via ajax request to a php file?
[英]Send php request onclick via ajax
我知道這個問題已經問了很多,但是沒有一個答案與我的案子有關,我有一個按鈕,單擊它應調用javascript函數將其發送給php變量,而ajax將通過發布調用php文件並發送該變量和PHP文件更新我的表
所以這首先是onclick事件
<button class="button button6 " onclick="incrementclicks('<?php echo $id; ?>');">increment</button>
它應該將一個名為$ id的變量發送給javascript函數
<script type="text/javascript">
function incrementclicks(id) {
$.ajax({
url: "increment.php",
data: "id=" + id,
type: "POST"
});
}
</script>
和php文件increment.php(我100%確信它可以正常連接到服務器)
<?php
require_once 'dbconnect.php';
$db_handle = new DBController();
$id=$_POST["id"];
$q="UPDATE clicks SET linkclicks = linkclicks + 1 WHERE id = '".$id."'";
$result = mysql_query($q);
?>
它不會增加,我不明白我在這里做錯了什么
首先,您可以通過以下方式在php上調試代碼
echo $id;
exit();
我的問題是,您在那里丟失了一些東西。
使用此ajax方法檢查問題。如果發現錯誤,請在控制台中檢查問題
$.ajax({
url: "increment.php",
type: "post", //send it through post method
data: {
id:id
},
success: function (response) {
alert("success");
},
error: function (xhr) {
//Do Something to handle error
alert("some error found");
}
});
注意:嘗試為您的按鈕添加type =“ button”,以免重新加載
<button class="button button6 " onclick="incrementclicks(5);" type="button">increment</button>
如果有人將來有這樣的問題,我只想回答這個問題
問題是我忘了在開始時添加腳本src
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
添加此代碼后,我的代碼就可以了:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.