[英]jQuery serialized data not being inserted into the database
我正在進行三件事。
我正在使用以下HTML表單向jQuery發送信息。
<div id="note_add_container">
<form id="note_add" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="location" placeholder="location" />
<button id="submit_note">Add note!</button>
</form>
</div>
這是我用來將此類序列化信息發布到數據庫中的jQuery腳本。
$('button').click(function () {
$.ajax ({
type: "POST",
url: "post.php",
data: $('#note_add').serialize(),
success: function(){
alert("Done");
}
});
});
這是將信息插入數據庫的PHP。
$name = $_POST['name'];
$location = $_POST['location'];
$sql = "INSERT INTO get (name, location)
VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($link));
}
這是行不通的。 我單擊按鈕,沒有任何反應。 警報不會觸發。 誰能為我的代碼無法正常工作向我提供正確的指導?
這是行不通的。 我單擊按鈕,沒有任何反應。 警報不會觸發
您完全確定點擊處理程序有效嗎? 您必須確保它首先起作用,例如,
$('button').click(function () {
alert('It works');
});
如果有效,則可以繼續。 否則,檢查其是否在DOMReady
$(function(){ ... })
以及是否加載了jquery.js
。
假設它有效,
您如何知道您的PHP腳本返回什么? 您只需假設它“應該起作用”,即可在這里:
success: function(){
alert("Done");
}
success()
方法實際上包含一個變量,該變量是來自服務器端的響應。 應該改寫成
success: function(serverResponse){
alert(serverResponse);
}
至於PHP腳本,
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($link));
}
您只能通過“回顯”錯誤消息來處理故障。 當mysqli_query()
返回TRUE
時,您將無法處理這種情況。 您應該發送類似1
,表示成功。
最后,您的代碼應如下所示:
$('#submit_note').click(function() {
$.ajax ({
type: "POST",
url: "post.php",
data: $('#note_add').serialize(),
success: function(serverResponse) {
if (serverResponse == "1") {
alert('Added. Thank you');
} else {
// A response wasn't "1", then its an error
alert('Server returned an error ' + serverResponse);
}
}
});
});
PHP:
$sql = "INSERT INTO get (name, location)
VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
die(mysqli_error($connection));
} else {
die("1"); // That means success
}
/**
* Was it $connection or $link?! Jeez, you were using both.
*
*/
您在$.ajax
調用中指定的回調函數僅在從服務器收到響應時才會觸發。 由於在將數據插入數據庫后,您再也不會從服務器將任何內容發送回客戶端,因此客戶端永遠不會調用alert("Done");
。 在您的PHP文件中添加一行,以在成功插入SQL之后向客戶端發送響應。 響應可以像說{'status': 'success'}
的JSON對象一樣簡單。
您應該采用更好的方式來處理表格。 serialize()有幫助,但最好將數據處理為JSON字符串。 使用JSO時,還需要在ajax調用中設置dataType。
$('#note_add').submit(function (event) {
event.preventDefault();
var formdata = $('#note_add').serializeArray();
var formobject = {};
$(formdata).each(function (event) {
formobject[formdata[event].name] = formdata[event].value;
});
var data = {
action: "formsend",
json: JSON.stringify(formobject)
};
//* * send with ajax * *
function sendajax(data) {
var deferred = $.ajax({
method: "post",
url: "ajax.php",
dataType: "json",
data: data
});
return deferred.promise();
}
sendajax(formdata).done(function (response) {
console.log(response);
if (response.success == true) {
alert("Done!");
}
})
});
趕上PHP
if(isset($_POST['action']) && $_POST['action'] == 'formsend') {
$data = json_decode($_POST['json'];
// here you can now access the $data with the fieldnames
$name = $data->name;
$location = $data->location;
// Write to the database
$sql = "INSERT INTO get (name, location) VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
die('Error: '.mysqli_error($link));
}
if (mysqli_affected_rows($connection) > 0) {
echo json_encode(array("success" = > true, "message" = > "data is submitted"));
} else {
echo json_encode(array("success" = > false, "message" = > "an error occurred"));
}
}
將以下行添加到您的php文件中,以將響應發送回去:
HttpResponse::setCache(true);
HttpResponse::setContentType('text/html');
HttpResponse::setData("<html>Success</html>");
HttpResponse::send();
flush();
如下更改ajax調用以查看結果:
$('#submit_note').click(function () {
$.ajax ({
type: "POST",
url: "post.php",
data: $('#note_add').serialize(),
success: function(respData) {
console.log('Response:', respData)
alert("Done");
}
});
});
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<title></title>
</head>
<body>
<div id="note_add_container">
<form id="note_add" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="location" placeholder="location" />
<button id="submit_note">Add note!</button>
</form>
</div>
<div id="response"> </div>
</body>
<script type="text/javascript">
$("#submit_note").click(function() {
var url = "post.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#note_add").serialize(), // serializes the form's elements.
success: function(data)
{
$('#response').empty();
$('#response').append(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
</html>
post.php
// Insert here your connection path
<?php
if((isset($_REQUEST['name']) && trim($_REQUEST['name']) !='') && (isset($_REQUEST['location']) && trim($_REQUEST['location'])!=''))
{
$name = addslashes(trim($_REQUEST['name']));
$location = addslashes(trim($_REQUEST['location']));
$sql = "INSERT INTO get (name, location) VALUES ('".$name."', '".$location."')";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($link));
}
echo "1 record added";
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.