Ошибка Ajax Success и Error
У меня возникли проблемы с правильной работой jQuery ajax. Он перенаправляет на страницу PHP обновление базы данных, но никогда не возвращается к script для параметров успеха или ошибки.
Мой код ниже:
$(document).ready(function(){
$("form#updatejob").submit(function() {
function textreplace(x) {return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");}
// we want to store the values from the form input box, then send via ajax below
var job = $("#job").attr("value");
var description = $("#description").val();
description.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var startDate = $("#startDate").attr("value");
var releaseDate = $("#releaseDate").attr("value");
var status = $("#status").attr("value");
$.ajax({
beforeSend:textreplace(description),
type: "POST",
url: "updatedjob.php",
data: "jobID="+ job +"& description="+ description +"& startDate="+ startDate +"& releaseDate="+ releaseDate +"& status="+ status,
success: function(){
$("form#updatejob").hide(function(){$("div.success").fadeIn();});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
return false;
});
});
И PHP:
<?php
include("connect.php");
$job = trim($_POST['job']);
$startDate = trim($_POST['startDate']);
$releaseDate = trim($_POST['releaseDate']);
$mysqlstartdate = date('Y-m-d', strtotime($startDate));
$mysqlreleasedate = date('Y-m-d', strtotime($releaseDate));
$description = trim($_POST['description']);
$status = trim($_POST['status']);
$update = "UPDATE jobs SET startDate = '$mysqlstartdate', releaseDate = '$mysqlreleasedate', description = '$description', status = '$status' WHERE jobID = '$job' ";
$rsUpdate = mysql_query($update);
// or die(mysql_error()); mysql_close();
?>
Ответы
Ответ 1
Попробуйте следующее:
$.ajax({
beforeSend: function() { textreplace(description); },
type: "POST",
url: "updatedjob.php",
data: "jobID="+ job +"& description="+ description +"& startDate="+ startDate +"& releaseDate="+ releaseDate +"& status="+ status,
success: function(){
$("form#updatejob").hide(function(){$("div.success").fadeIn();});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
Свойство beforeSend
имеет значение function() { textreplace(description); }
вместо textreplace(description)
. Свойству beforeSend
требуется функция.
Ответ 2
Вы можете реализовать логику, специфичную для ошибок, следующим образом:
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == 'Unauthorized') {
alert('custom message. Error: ' + errorThrown);
} else {
alert('custom message. Error: ' + errorThrown);
}
}
Ответ 3
Также можно использовать следующие, чтобы поймать ошибки:
$.ajax({
url: url,
success: function (data) {
// Handle success here
$('#editor-content-container').html(data);
$('#editor-container').modal('show');
},
cache: false
}).fail(function (jqXHR, textStatus, error) {
// Handle error here
$('#editor-content-container').html(jqXHR.responseText);
$('#editor-container').modal('show');
});
Ответ 4
У меня была такая же проблема, и я исправил ее, просто добавив строку dataType = "text" в мой вызов ajax. Сделайте dataType совпадением с ответом, который вы ожидаете получить от сервера (сообщение об ошибке "вставить успешно" или "что-то пошло не так" ).
Ответ 5
Это может быть старый пост, но я понял, что от php ничего не нужно возвращать, и ваша функция успеха не имеет ввода, как показано ниже, success:function(e){}
. Надеюсь, это поможет вам.
Ответ 6
Это может не решить все ваши проблемы, но переменная, которую вы используете внутри вашей функции (текст), не совпадает с параметром, который вы передаете (x).
Изменение:
function textreplace(x) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
To:
function textreplace(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
похоже, что это принесет пользу.
Ответ 7
Вы отправляете тип сообщения с данными, реализованными для получения.
ваша форма должна быть следующей:
$.ajax({
url: url,
method: "POST",
data: {data1:"data1",data2:"data2"},
...