使用AJAX返回PHP错误处理 [英] Return PHP error handling with AJAX
本文介绍了使用AJAX返回PHP错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个支持PHP和AJAX的页面,当用户提交我的表单之一时,我检查getData.php脚本中的错误.
I have a page powered with PHP and AJAX, when a user submits one of my forms I check for errors in the getData.php script.
此示例是如果用户使用默认值提交表单,我想知道是否有一种方法可以传回这些错误,或者如果用户提交错误或我需要执行错误,则触发AJAX引发错误在AJAX调用之前进行处理
This example is if the user submits the form with the default value I'm wondering if there is a way to pass back those errors or trigger the AJAX to fire an error if the user commits on or if I need to do error handling before the AJAX call
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/addData.php',
data: $('form').serialize(),
success: function () {
$("input").val('Info Here');
$("form").hide();
reloadInfo();
}
});
});
PHP
$info = $_POST['info'];
if($info != 'Info Here') {
$conn = mysqli_connect();
$query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)";
$result = mysqli_query($conn, $query) or die ('Error Could Not Query');
$id = mysqli_insert_id($result);
header("Location: http://localhost/manage/info.php?id=$id");
mysqli_close($conn);
} else {
echo '<script>alert("Error");/script>'
}
PART 2
推荐答案
Javascript:
Javascript:
success: function (data) {
if(!data.success) alert(data.errors); // Just for demonstration purposes
$("input").val(data.errors);
$("form").hide();
reloadInfo();
}
PHP:
header("Content-Type: text/json; charset=utf8");
if($info != 'Info Here') {
$conn = mysqli_connect();
$query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)";
$result = mysqli_query($conn, $query) or die ('Error Could Not Query');
$id = mysqli_insert_id($result);
header("Location: http://localhost/manage/info.php?id=$id");
mysqli_close($conn);
} else {
echo json_encode(array("success" => false,"error" => "Some random error happened"));
}
这篇关于使用AJAX返回PHP错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文