Как мне вернуть правильное сообщение об успешном выполнении/ошибке для jQuery.ajax() с использованием PHP?
Я продолжаю получать предупреждение об ошибке. В части MYSQL нет ничего плохого, запрос выполняется, и я вижу адреса электронной почты в бд.
Клиентская сторона:
<script type="text/javascript">
$(function() {
$("form#subsribe_form").submit(function() {
var email = $("#email").val();
$.ajax({
url: "subscribe.php",
type: "POST",
data: {email: email},
dataType: "json",
success: function() {
alert("Thank you for subscribing!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
});
</script>
На стороне сервера:
<?php
$user="username";
$password="password";
$database="database";
mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database");
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email'] ) : "";
if($senderEmail != "")
$query = "INSERT INTO participants(col1 , col2) VALUES (CURDATE(),'".$senderEmail."')";
mysql_query($query);
mysql_close();
$response_array['status'] = 'success';
echo json_encode($response_array);
?>
6 answers
Вам необходимо указать правильный тип контента, если вы используете тип данных JSON. Перед повторением json введите правильный заголовок.
<?php
header('Content-type: application/json');
echo json_encode($response_array);
?>
Дополнительное исправление, вы должны проверить, успешно ли выполнен запрос или нет.
if(mysql_query($query)){
$response_array['status'] = 'success';
}else {
$response_array['status'] = 'error';
}
На стороне клиента:
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
Надеюсь, это поможет.
Просто чтобы вы знали, вы можете использовать это для отладки. Это мне очень помогло, и до сих пор помогает
error:function(x,e) {
if (x.status==0) {
alert('You are offline!!\n Please Check Your Network.');
} else if(x.status==404) {
alert('Requested URL not found.');
} else if(x.status==500) {
alert('Internel Server Error.');
} else if(e=='parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if(e=='timeout'){
alert('Request Time out.');
} else {
alert('Unknow Error.\n'+x.responseText);
}
}
Некоторые люди рекомендуют использовать коды состояния HTTP, но я скорее презираю эту практику. например Если вы используете поисковую систему и предоставленные ключевые слова не дают результатов, рекомендуется вернуть ошибку 404.
Однако я считаю это неправильным. Коды состояния HTTP применяются к фактическому подключению браузера к серверу. Все, что касалось подключения, прошло идеально. Браузер сделал запрос, сервер вызвал ваш скрипт-обработчик. Сценарий вернул "нет строк". Ничего в этом нет означает "404 страница не найдена" - страница БЫЛА найдена .
Вместо этого я предпочитаю отделять уровень HTTP от статуса ваших операций на стороне сервера. Вместо того, чтобы просто возвращать некоторый текст в строке json, я всегда возвращаю структуру данных JSON, которая инкапсулирует статус запроса и результаты запроса.
Например, в PHP у вас будет
$results = array(
'error' => false,
'error_msg' => 'Everything A-OK',
'data' => array(....results of request here ...)
);
echo json_encode($results);
Тогда в вашем клиентском коде у вас будет
if (!data.error) {
... got data, do something with it ...
} else {
... invoke error handler ...
}
Для создания веб-сервиса AJAX вам понадобятся ДВА файла:
- Вызывающий Javascript, который отправляет данные как POST (может быть как GET) с помощью jQuery AJAX
- Веб-сервис PHP, который возвращает объект JSON (это удобно для возврата массивов или большого объема данных)
Итак, сначала вы вызываете свой веб-сервис, используя этот синтаксис jQuery, в файле JavaScript:
$.ajax({
url : 'mywebservice.php',
type : 'POST',
data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
dataType : 'json',
success: function (data) {
alert("The file is "+data.fichierZIP);
},
error: function(data) {
//console.log(data);
var responseText=JSON.parse(data.responseText);
alert("Error(s) while building the ZIP file:\n"+responseText.messages);
}
});
Ваш PHP-файл (mywebservice.php, как написано в вызове AJAX) должно включать что-то вроде это в конце концов, чтобы вернуть правильный статус успеха или ошибки:
<?php
//...
//I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
//$errors is a string that may contain an error message while preparing the ZIP file
//In the end, I check if there has been an error, and if so, I return an error object
//...
if ($errors==''){
//if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['ZIPFILENAME'] = basename($filename);
print json_encode($result);
} else {
//if there is an error, you should return a special header, followed by another JSON object
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['messages'] = $errors;
//feel free to add other information like $result['errorcode']
die(json_encode($result));
}
?>
Добавление в верхний ответ: вот пример кода из PHP и Jquery:
$("#button").click(function () {
$.ajax({
type: "POST",
url: "handler.php",
data: dataString,
success: function(data) {
if(data.status == "success"){
/* alert("Thank you for subscribing!");*/
$(".title").html("");
$(".message").html(data.message)
.hide().fadeIn(1000, function() {
$(".message").append("");
}).delay(1000).fadeOut("fast");
/* setTimeout(function() {
window.location.href = "myhome.php";
}, 2500);*/
}
else if(data.status == "error"){
alert("Error on query!");
}
}
});
return false;
}
});
PHP - отправить пользовательское сообщение /статус:
$response_array['status'] = 'success'; /* match error string in jquery if/else */
$response_array['message'] = 'RFQ Sent!'; /* add custom message */
header('Content-type: application/json');
echo json_encode($response_array);
У меня была та же проблема. Моя проблема заключалась в том, что мой тип заголовка был установлен неправильно.
Я только что добавил это перед моим json echo
header('Content-type: application/json');