Ajax php return error

Return errors from PHP run via. AJAX?

Is there a way to get PHP to return an AJAX error code if the PHP script fails somewhere? I was following a tutorial and typed this in to my PHP:

$return['error'] = true; $return['msg'] = "Could not connect to DB";

And all was well, until I realised it was JSON data. Is there a way to return errors using standard $_POST and returned HTML data (as in, trigger jQuery’s AJAX error: event?

4 Answers 4

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

Just be aware that this could lead to trouble on standard IIS installation/configuration, as IIS delivers a htm site and kind of overwrites your json repsonse, and your client side JSON.parse() which you may have implemented, throws an exception. Altering the web.config with the following line helped me but I am not sure whether that’s the case for all IIS config combinations:

$return = array(); $return['msg'] = "Could not connect to DB"; if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') < header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json'); die(json_encode($return)); >

You need to force your requests with $_SERVER[‘HTTP_X_REQUESTED_WITH’]. browsers like Firefox wont evaluate the response when the Accept header does not match.

Читайте также:  Source code online sources java

try this out. Hope it helps.

      #error < color:maroon; font-weight:bold; >#result    

Error: Fill in ALL fields.
'; > elseif(is_numeric($_POST['name']))< $error = '
Error: Name should NOT contain numbers.
'; > elseif(!is_numeric($_POST['age']))< $error = '
Error: Age should ONLY contain numbers.
'; > else< $result = '
Hi '.$_POST['name'].', you are '.$_POST['age'].' years old.
'; > echo $error; echo $result; ?>

For simple transfer of data from PHP to AJAX, Json encoding or key value pairs are not always necessary. It can be simply done using string handling.

A sample code explaining this functionality is below.

$query = "SELECT email FROM login WHERE email = '". mysqli_real_escape_string($conn,$email) ."' AND password = '". mysqli_real_escape_string($conn,$pass) ."'" ; $result = mysqli_query($conn,$query); $row=mysqli_fetch_row($result); $row_cnt = mysqli_num_rows($result); $s_email = $row[0]; if ($row_cnt == 1) < $response="success"; >else < $response = "Invalid Credentials"; >$conn->close(); $_SESSION["email"]= $s_email; echo $response;

This code shows how a ‘success’ response is sent back to ajax calling the php code. Further in ajax the following could be done to retrieve the response.

$.ajax(< type : 'POST', data : , url : 'login.php', success: function (data) < if(data == 'success')< //the value echoed from php can be stored in the data variable of ajax window.location.assign('upload.php'); >else < alert(data); >>, error: function ( xhr ) < alert("error"); >>);

The above concept can be extended to return MULTIPLE VALUES also. This method allows simple tranfer of data from PHP to AJAX in a string format.

We have to follow a simple step of echoing everything we need to send as a response from the php to ajax, seperated by a unique seperator.

echo $response.#; echo $email.#; echo $password.#; echo "Hello".#; echo "World";

Then the variable data in ajax could be simply retrieved as in the above example and a simple function like,

data, being the variable within ajax. The res array can then be used within js for whatever purpose we need.

Источник

AJAX: how to return an error from PHP

I have a form for a user to upload a profile picture and show them live validation without refreshing. I am trying to use AJAX but it does not seem to reach the PHP file. Also even though I am using preventDefault after I submit the form it reloads the page and opens the first tab which does not have the form on. FORM

$avatar_form = '
'; $avatar_form .= '
'; $avatar_form .= '
'; $avatar_form .= '

Change avatar

'; $avatar_form .= ''; $avatar_form .= '

'; $avatar_form .= ' '; $avatar_form .= '

'; $avatar_form .= '
';

if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != "") < $fileName = $_FILES["avatar"]["name"]; $fileTmpLoc = $_FILES["avatar"]["tmp_name"]; $fileType = $_FILES["avatar"]["type"]; $fileSize = $_FILES["avatar"]["size"]; $fileErrorMsg = $_FILES["avatar"]["error"]; $kaboom = explode(".", $fileName); $fileExt = end($kaboom); list($width, $height) = getimagesize($fileTmpLoc); if($width < 10 || $height < 10)< $result = "That image has no dimensions"; exit(); >$db_file_name = rand(100000000000,999999999999).".".$fileExt; if($fileSize > 1048576) < $result = "Your image file was larger than 1mb"; echo $result; >else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) < $result = "Please only JPG, GIF or PNG images"; echo $result; >else if ($fileErrorMsg == 1)
$('#avatar_form').submit(function(event) < event.preventDefault(); $.ajax(< type: 'POST', url: 'photo_system.php', data: $(this).serialize(), dataType: 'json', success: function (result) < console.log(result); $('#status').html(result); >>); >); 

Источник

Как на php вернуть конкретную ошибку при оправке формы Ajax?

Форма с помощью Ajax отправляет данные в send.php обработчик и он уже взаимодействует с БазойДанных.

Можно ли прямо в обработчике send.php указывать ошибки типа «Неверный логин» или «Неверный пароль» или сразу обе ошибки и отправлять их на текущую страницу с формой?
Чтобы с помощью JavaScript далее оформлять эти ошибки для пользователя.

Если да, то покажете пример?

Нашел только технологию — передача ошибки в заголовок, но таким образом можно передать только 1 ошибку, да и строго определенные ошибки, да и не безопасно это от инъекций.

Не могу понять, как вообще делают такое.
Неужели можно только ограничиваться обработчиком на текущей странице, где форма отправки данных там и обработчик.

$("form").submit(function(e) < e.preventDefault(); $.ajax(< type: "POST", url: "send.php", data: $(this).serialize() >).done(function() < // если успешная отправка >).fail(function () < // если ошибка отправки >); return false; >);
// Если такой логин есть, значит ошибка if ( R::count('users', "login = ?", array($_POST['login'])) > 0) < // ХОТЯ И ВОЗНИКАЕТ ОШИБКА, AJAX ОТМЕЧАЕТ УСПЕШНУЮ ОТПРАВКУ. // КАК ЕЕ ОТПРАВИТЬ НА ТЕКУЩУЮ СТРАНИЦУ ? $errors = 'Пользователь с таким Логином уже существует!'; >else < // Если логин уникальный - регистрируем юзера $user = R::dispense('users'); $user->login = $_POST['login']; $user->password = $_POST['password']; R::store($user); >

Простой 8 комментариев

Источник

Clean way to throw php exception through jquery/ajax and json

Why do you want to throw an exception? It would likely be better to return an error state that does not trigger an exception.

I mean I have try catch on the server side, and I want to put the error message into the json response.

5 Answers 5

You could do something like this in PHP (assuming this gets called via AJAX):

 echo json_encode(array( 'result' => 'vanilla!', )); > catch (Exception $e) < echo json_encode(array( 'error' =>array( 'msg' => $e->getMessage(), 'code' => $e->getCode(), ), )); > 

You can also trigger the error: handler of $.ajax() by returning a 400 (for example) header:

header('HTTP/1.0 400 Bad error'); 

Or use Status: if you’re on FastCGI. Note that the error: handler doesn’t receive the error details; to accomplish that you have to override how $.ajax() works 🙂

You might want to throw in the ‘stack’ => $e->getTrace() as well so you get a nice array of the stack too.

Facebook do something in their PHP SDK where they throw an exception if a HTTP request failed for whatever reason. You could take this approach, and just return the error and exception details if an exception is thrown:

 $results )); > catch (Exception $e) < echo json_encode(array( 'error' =>array( 'code' => $e->getCode(), 'message' => $e->getMessage() ) )); > 

You can then just listen for the error key in your AJAX calls in JavaScript:

  

Источник

How do I return a proper success/error message for JQuery .ajax() using PHP?

You need to provide the right content type if you’re using JSON dataType. Before echo-ing the json, put the correct header.

Additional fix, you should check whether the query succeed or not.

success: function(data) < if(data.status == 'success')< alert("Thank you for subscribing!"); >else if(data.status == 'error') < alert("Error on query!"); >>, 

Oh, and you should differentiate server side error and transmission error. I put the check on success part of the AJAX to check the value sent by server (so it is not transmission error).

how do store multiple varriable like $response_array[‘status’]=’success’, $response_array[‘userid’] = $userid; etc.

Just so you know, you can use this for debugging. It helped me a lot, and still does

error:function(x,e) < if (x.status==0) < alert('You are offline!!\n Please Check Your Network.'); >else if(x.status==404) < alert('Requested URL not found.'); >else if(x.status==500) < alert('Internel Server Error.'); >else if(e=='parsererror') < alert('Error.\nParsing JSON Request failed.'); >else if(e=='timeout') < alert('Request Time out.'); >else < alert('Unknow Error.\n'+x.responseText); >> 

Some people recommend using HTTP status codes, but I rather despise that practice. e.g. If you’re doing a search engine and the provided keywords have no results, the suggestion would be to return a 404 error.

However, I consider that wrong. HTTP status codes apply to the actual browserserver connection. Everything about the connect went perfectly. The browser made a request, the server invoked your handler script. The script returned ‘no rows’. Nothing in that signifies «404 page not found» — the page WAS found.

Instead, I favor divorcing the HTTP layer from the status of your server-side operations. Instead of simply returning some text in a json string, I always return a JSON data structure which encapsulates request status and request results.

$results = array( 'error' => false, 'error_msg' => 'Everything A-OK', 'data' => array(. results of request here . ) ); echo json_encode($results); 

Then in your client-side code you’d have

Источник

Оцените статью