0
我想在數據庫中發佈數據與PHP使用AJAX,但沒有發生。我檢查了開發者工具的任何錯誤,但沒有錯誤出現和POST請求發送成功AJAX後沒有工作
我測試的代碼通常沒有AJAX發佈數據,並且效果很好,但隨着AJAX什麼都沒有發生
HTML:
<form id="form_box" action="" method="post">
<h5>Body:</h5>
<textarea name="body" cols="30" rows="10"></textarea>
<div>
<input type="submit" name="sub_post" value="Post Ajax">
</div>
</form>
JS:
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
// Variable to hold request
var request;
// Bind to the submit event of our form
$("#form_box").submit(function(event){
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "/functions/post.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
// alert("Post Added successfully");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function() {
// Reenable the inputs
$inputs.prop("disabled", false);
});
// Prevent default posting of form
event.preventDefault();
});
</script>
PHP:
<?php
include_once('../includes/config.php');
$post=$db->real_escape_string($_POST['body']);
$db->query("insert into ajax(a_post) values ('$post')");
?>
嘗試使用[serializeArray](https://api.jquery.com/ serializeArray /)而不是 – Amin
'$ db-> real_escape_string()'你在使用mysql擴展嗎?如果是這樣,請記住它的破損和不安全的使用。 – Xorifelse
不,我使用mysqli –