В настоящее время я сталкиваюсь с проблемой при вызове ajax при попытке отправить форму в базу данных.Невозможно запустить ajax-вызов в готовом документе jQuery
Вот мой код:
<?php
include 'dbConnect.php';
include 'session.php';
?>
<form class="form" id="form" action="" method="POST">
<table class = "left">
<tr align="justify">
<td></td>
</tr>
<tr>
<td>
<p align="right">
<font size = "4">New Subject Name : <input type = "text" name = "subjectName" id = "subjectName"/>
</font>
</p>
</td>
</tr>
<tr>
<td>
<p align="center">
<input type = 'image' name = 'submit' src="images/Submit.gif" value = 'Submit' width='100' height='35'/>
</p>
</td>
</tr>
</table>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</script>
<script>
$(document).ready(function() {
// Bind to the submit event of our form
$("form#form").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: "subjectItem.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!");
});
// 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>
Я не знаю, почему он не делаешь вставить данные в базу данных после того, как пользователь нажмите кнопку отправки. Пожалуйста, укажите мою ошибку, если я сделал что-то неправильно в коде. Благодаря
Проверьте консоль на наличие ошибок. Вы видите результат строк 'console.log'? Выполняется ли ваш PHP? –
На моем console.log нет ошибки. –
У меня возникла бы соблазн разместить эту строку 'event.preventDefault();' непосредственно после этой строки '$ (" form # form "). Submit (function (event) {' Just в случае, если форма выполняет стандартную отправку HTML, а также ваш jQuery ajax call. – RiggsFolly