Return Errors from PHP Run Via. Ajax

Return errors from PHP run via. AJAX?

I don't know about jQuery, but if it distinguishes between successful and unsuccessful (HTTP 200 OK vs. HTTP != 200) Ajax requests, you might want your PHP script respond with an HTTP code not equal to 200:

if ($everything_is_ok)
{
header('Content-Type: application/json');
print json_encode($result);
}
else
{
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
}

ajax how to return an error message from a PHP file

Here is exactly how you can do it :

The Very Easy Way :

IN YOUR PHP FILE :

if ($query) {
echo "success"; //anything on success
} else {
die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure
}

AT YOUR jQuery AJAX SIDE :

var x = $(this).text();
$.ajax({
type: 'POST',
url: 'process.php',
data: { text1: x },
success:function(data) {
alert(data); //=== Show Success Message==
},
error:function(data){
alert("error occured"); //===Show Error Message====
}
});

Display PHP errors in ajax request callback

The success and error functions in your jQuery AJAX call simply checks for the HTTP status code for the request. When PHP produces errors it does not change the status code, and so jQuery triggers the success function. If you want to use the jQuery error, you will have to change the status code. You can do this by catching the Error (PHP >= 7):

try {
$data = test();
}
catch (\Error $e) {
http_response_code(500);
echo $e->getMessage();
}

Or you could keep the status code as 200 (default) and send your response in JSON including the success and error properties you like, as well as any other things you may want to return with the request.

header('Content-type: application/json');
$response['success'] = true;
$response['error'] = null;
try {
$data = test();
}
catch (\Error $e) {
$response['success'] = false;
$response['error'] = $e->getMessage();
}
echo json_encode($response);

And make sure to remove the dataType property from the ajax request to let jQuery automatically determine the type header.

If your program is throwing errors unexpectedly, this probably means you're doing something wrong. If you expect it to throw errors, you need to catch them. This either means wrapping things in try/catch blocks or a combination of set_exception_handler(), set_error_handler() and register_shutdown_function() to accomplish this globally.

Return PHP error handling with AJAX

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

Show PHP error with AJAX. If there are no errors, show output from PHP function

You can capture the output of the getUsers function without changing the current behavior if that's what you're after. In the success output change

$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)

to

ob_start();
getUsers();
$usersList = ob_get_clean();
$responseArray = ["success" => true, "data" => $usersList];
echo json_encode($responseArray)

What this does is captures the output and stores it into a varable $usersList which you can then return as a string.

You'd be better off returning the users as an array and dealing with generating the markup on the client side IMO, but that's up to you. This is just another way to get what you have working.

More information about php's output buffer here

Jquery AJAX return from PHP

To invoke the error handler of your $.ajax, you can write the following code in PHP (for FastCGI):

header('Status: 404 Not found');
exit;

Alternatively, use header('HTTP/1.0 404 Not Found') if you're not using FastCGI.

Personally I wouldn't use this approach, because it blurs the line between web server errors and application errors.

You're better off with an error mechanism like:

echo json_encode(array('error' => array(
'message' => 'Error message',
'code' => 123,
)));
exit;

Inside your success handler:

if (data.error) {
alert(data.error.message);
}

AJAX-PHP Stay on same page if validation fails

You need to prevent the default action of form i.e. submit when input type of submit is clicked, so that your ajax process runs smoothly. In your click event add e.preventDefault();

$('#submit_form').on('click', function (e) {
//get the e as parameter
e.preventDefault();
//rest of your code.
});

ajax to return error status code

jQuery has no idea what your PHP script is supposed to be doing, so it's not looking for a "status" variable in your returned result. All jQuery knows is whether the actual HTTP request "worked". If it gets back a 200 result, that's success no matter what's in the result.

You either need to have your success handler look for cases where the HTTP request succeeded but the data says "error", or (better) have the PHP script use http_response_code() to change the HTTP status from 200 to something like 400 or 500 that will indicate an error.



Related Topics



Leave a reply



Submit