I use jQuery and Ajax to pass data to a PHP / MySQLi page.
The code and the query work as intended but I can’t find a way to handle the errors.
E. g. I want to inform the user about a potential duplicate record when the data that I pass to the PHP page already exists in my database (see comment in the code below).
I tried different approaches but my error handling is always ignored or not applied.
Can someone tell me how to do this right ?
jQuery (shortened):
$('#btnSave').on('click', function(e) {
e.preventDefault();
var vid = $.trim($('#vid').val());
var vid2 = $.trim($('#vid2').val());
var vid3 = $.trim($('#vid3').val());
var mode = 'update';
if(vid == 'new') {
mode = 'insert';
}
$.ajax({
type: 'POST',
url: 'updateVid.php',
data: {
mode: mode,
vstId: vstId,
vstId2: vstId2,
vstId3: vstId3
},
success: function(result){
alert('success');
},
error: function() {
alert('error'); // I am unable to retrieve this in jQuery / Ajax resp. to do anything here
}
});
});
PHP / MySQLi (shortened):
<?php
require_once 'me/config.php';
$postData = $_POST;
$mode = $_POST['mode'];
$vid = $_POST['vid'];
$vid2 = $_POST['vid2'];
$vid3 = $_POST['vid3'];
$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
die("Connection Error: " . $conn->connect_error);
}
if($mode == 'update') {
$stmt = $conn->prepare("UPDATE vids v SET v.vid2 = ?, v.vid3 = ? WHERE v.vid = ?");
$stmt->bind_param("sss", $vid, $vid2, $vid3);
$stmt->execute();
} else {
$vid = '99999999';
$vid2 = '99XXX999';
$stmt = $conn->prepare("SELECT vid2 FROM vids WHERE vid = ?");
$stmt->bind_param("s", $vid);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0) {
echo 'Error'; // I am unable to retrieve this in jQuery / Ajax
} else {
$stmt->close();
$stmt = $conn->prepare("INSERT INTO vids (vsid, vid2, vid3) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $vid, $vid2, $vid3);
$stmt->execute();
echo 'Success';
}
}
$stmt->close();
$conn->close();
?>
Many thanks in advance,
Tom
2
Answers
Because your AJAX call is always successful you will not get a failure. If the AJAX call fails, you will get an error.
Your PHP can fail separately, but it will not produce an AJAX error, so if you want to handle PHP errors with AJAX you have to handle them in the success function but providing a way to know the PHP failed. For example:
ALSO
Please, quit using
alert()
for troubleshooting., useconsole.log()
instead.It ‘s all about HTTP status codes. The jQuery
success
function is fired, when the http status code was 200/OK. If the returned http status code was errornous, it calls theerror
function. Knowing that you have to send http status codes within the php response header.For this please have a look at the php http_reponse_code() function.
Your
echo
output is always a valid output for jQuery. Outputting data without a status code is always a 200/OK status. As shown above, you can set the returned status with PHP. A list of HTTP status codes is shown here.