如何退还的jQuery阿贾克斯(使用PHP)适当的成功/错误信息? [英] How do I return a proper success/error message for JQuery .ajax() using PHP?
本文介绍了如何退还的jQuery阿贾克斯(使用PHP)适当的成功/错误信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不断收到错误警报。没有什么错与MySQL的一部分,查询被执行,我可以看到的电子邮件地址在db。
客户端:
<脚本类型=文/ JavaScript的>
$(函数(){
$(#形式subsribe_form)。递交(函数(){
变种的电子邮件= $(#邮件)VAL()。
$阿贾克斯({
网址:subscribe.php
键入:POST,
数据:{电子邮件:电子邮件},
数据类型:JSON,
成功:函数(){
警报(谢谢你的订阅!);
},
错误:函数(){
警报(有一个错误尝试重新请!);
}
});
返回false;
});
});
< / SCRIPT>
服务器端:
< PHP
$用户=用户名;
$密码=密码;
$数据库=数据库;
的mysql_connect(本地主机,$用户,$密码);
mysql_select_db($数据库)或死亡(无法选择数据库);
$ senderEmail =使用isset($ _ POST [电子邮件])? preg_replace(/[^\.\-\_\@a-zA-Z0-9]/,,$ _ POST [电子邮件]):;
如果($ senderEmail!=)
$查询=INSERT INTO参与者VALUES(CURDATE(),$ senderEmail。');
的mysql_query($查询);
则mysql_close();
$ response_array ['状态'] ='成功';
回声json_en code($ response_array);
?>
解决方案
您需要的,如果你使用JSON数据类型设置为提供合适的内容类型。在回声荷兰国际集团的JSON,把正确的标题。
< PHP
标题(内容类型:应用程序/ JSON);
回声json_en code($ response_array);
?>
附加的修正,应检查查询是否成功与否。
如果(的mysql_query($查询)){
$ response_array ['状态'] ='成功';
}其他 {
$ response_array ['状态'] ='错误';
}
在客户端:
成功:功能(数据){
如果(data.status =='成功'){
警报(谢谢你的订阅!);
}否则,如果(data.status =='错误'){
警报(上查询错误!);
}
},
希望它帮助。
I keep getting the error alert. There is nothing wrong with the MYSQL part, the query gets executed and I can see the email addresses in the db.
The client side:
<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>
The server side:
<?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 VALUES (CURDATE(),'".$senderEmail."')";
mysql_query($query);
mysql_close();
$response_array['status'] = 'success';
echo json_encode($response_array);
?>
解决方案
You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.
<?php
header('Content-type: application/json');
echo json_encode($response_array);
?>
Additional fix, you should check whether the query succeed or not.
if(mysql_query($query)){
$response_array['status'] = 'success';
}else {
$response_array['status'] = 'error';
}
On the client side:
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
Hope it helps.
这篇关于如何退还的jQuery阿贾克斯(使用PHP)适当的成功/错误信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文