使用AJAX返回PHPerror handling

我有一个用PHP和AJAX驱动的页面,当用户提交我的一个表单时,我检查了getData.php脚本中的错误。

这个例子是如果用户提交带有默认值的表单我想知道是否有办法传回这些错误或触发AJAX在用户提交时触发错误或者如果我需要在之前进行error handlingAJAX电话

$('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 'alert("Error");/script>' } 

第2部分

使用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")); } 

您的代码有几个问题:

  • $companyName未在任何地方定义
  • 您应该使用预准备语句而不是将数据放入SQL查询中
  • 您应该将整个AJAX PHP代码放在一个try..catch块中
  • 在AJAX PHP代码的最后,写一些JSON
  • 我不明白为什么你试图重定向一个AJAX调用,通常你会告诉客户端进行重定向。

例如,我会像这样写你的PHP代码:

 try { if(!isset($_POST['info'])) throw new Exception('Post info was not set'); $info = $_POST['info']; if($info == 'Info Here') throw new Exception('Invalid value for info'); $conn = mysqli_connect(); if(!$conn) throw new Exception('Database connection failure'); $companyName = '?????'; $query = 'INSERT INTO leads VALUES(0, ?, 1, NOW(), 3)'; $stmt = mysqli_prepare($query); if(!$stmt) throw new Exception('Could not query database'); mysqli_stmt_bind_param($stmt, 's', $companyName); mysqli_stmt_close($stmt); $id = mysqli_stmt_insert_id($stmt); mysqli_close($conn); echo json_encode(array( 'success' => true, 'new_id' => $id, )); }catch(Exception $ex){ echo json_encode(array( 'success' => false, 'reason' => $ex->getMessage(), )); }