Greetings,
I was trying to discover a proper way to send captured errors or business logic exceptions to the client in an Ajax-PHP system. In my case, the browser needs to react differently depending on whether a request was successful or not. However in all the examples I've found, only a simple string is reported back to the browser in both cases. Eg:
if (something worked)
echo "Success!";
else
echo "ERROR: that failed";
So when the browser gets back the Ajax response, the only way to know if an error occurred would be to parse the string (looking for 'error' perhaps). This seems clunky.
Is there a better/proper way to send back the Ajax response & notify the browser of an error?
Thank you.
You could send back an HTTP status code of 500 (Internal server error) , and then include the error message in the body. Your client AJAX library should then handle it as an error (and call an appropriate callback etc.) without you having to look for strings in the response.
I generally send back a JSON response like this:
$response = array('status' => 'error', 'message' => 'an unknown error occured');
if( some_process() ) {
$response['status'] = 'success';
$response['message'] = 'Everything went better than expected.';
} else {
$response['message'] = "Couldn't reticulate splines.";
}
die( json_encode($response) );
So, I can check the status of response.status in my JavaScript and look for a value of "sucess" or "error" and display response.message appropriately.
showing to the user a status of what is happening and what has happened is very important.
I you want to structure your ajax responses, you should look into the json format.
if (something worked)
echo '{ "error": 0 }';
else
echo '{ "error": 1 }';
Once you set foot into the json world, you will be able to send more structured output. For example :
if (something worked)
echo '{ "error": 0 }';
else
echo '{ "error": 1, "code": 889, "desc": "Something bad happened" }';
When you receive this output in javascript, you can transform it into an object and take actions depending on the different keys.
The library json2.js will help you transform your output into an object
Sending the appropriate http headers should do the trick and tell your ajax scripts to execute the right callback. Each javascript framework i know of has a success and error callback for it's XHR requests.
header('HTTP/1.1 500 Internal Server Error');
You can send back a JSON object which contains a custom error code and error message which you can then either handle or display directly to your users:
{
"response": 10,
"message": "The database didn't work or something"
}
It would work for success as well:
{
"response": 1,
"message": "It worked! Yippee!"
}
Related
I am building an integration with Zapier (https://zapier.com/platform) and I want to throw an error but it seems like it's not working properly.
My authentication code (dumbed down for the purpose of this post):
if($_POST['api_key'] === $row['api_key']) {
$array = ['success' => 'yes'];
echo json_encode($array);
} else {
echo "Sorry but that is the invalid API token. Please try something else";
}
When I try to test that in the Zapier developer platform, I get this message from them:
Error parsing response. We got: "Sorry but that is the invalid API token. Please try something else". This is likely a problem with the app. Please contact support at contact#zapier.com
But Zapier wants me to throw an error that does not have the "Error parsing response" and "This is likely a problem with the app..." parts....
How can I fix this?
Simply sending a message that the auth was unsuccessful isn't enough - you need to also send the appropriate HTTP response code. In this case, you probably want 403 or 401. I'm not sure how to do that, but there plenty of questions that'll point you in the right direction.
Additionally, you probably want to send back JSON rather than plain text. This could be as simple as: {"message": "invalid token"}. This'll help the client better surface that info to the user.
I'm recently tried to use webhook to get update from telegram. my program work correctly whit getUpdates().
but when i set webhook i got
"Wrong response from the webhook: 400 Bad Request"
error when try to check status of webhook by getWebhookInfo method.
here is my code:
$telegram->commandsHandler(true)
when is used below code in getUpdates mod every thing was fine.
$telegram->commandsHandler(false)
And is should say i use https and my ssl is ok.
This is answer of getWebhookInfo to me.
{
"ok": true,
"result": {
"url": "https://telbit.ir/api/bot/<token>",
"has_custom_certificate": false,
"pending_update_count": 13,
"last_error_date": 1476344420,
"last_error_message": "Wrong response from the webhook: 400 Bad Request"
}
}
I found my answer
every things was ok. the error happens because of my framework.
I tried to create a webhook for a task in Asana but the only response I'm getting is this:
{
"errors": [
{
"message": "Could not complete activation handshake with target URL. Please ensure that the receiving server is accepting connections and supports SSL",
"help": "For more information on API status codes and how to handle them, read the docs on errors: https://asana.com/developers/documentation/getting-started/errors"
}
]
}
(Status: 400 Bad Request)
I am sending a POST Request via Postman to https://app.asana.com/api/1.0/webhooks with following content:
{
"data":
{
"resource": 123456789012345,
"target": "https://example.com/asana.php"
}
}
The asana.php looks something like this:
$headers = getallheaders();
$secret_token = $headers['X-Hook-Secret'];
header('X-Hook-Secret: ' . $secret_token);
What am I doing wrong? Am I missing something?
According to the Asana API Reference (https://asana.com/developers/api-reference/webhooks),
The target must respond with a 200 OK and a matching X-Hook-Secret header to confirm that this webhook subscription is indeed expected.
When you send the header, do you know what response code is being sent? Perhaps you might want to have a look at the $http_response_code argument in http://php.net/manual/en/function.header.php
I have page which checks data sent via HTTP POST (http://example.com/http_post). If the data is good I add to database and wish to set http response code 201 and a success message as http response. If not I collect the errors in a an array and wish to set http response code and message as serialized JSON array as http response.
1) Whats the syntax to serialze the errors array as JSON in php?
Example
{
"message": "The request is invalid.",
"modelState": {
"JobType": [ "Please provide a valid job type eg. Perm"]
}
}
Whats the syntax to set and return the http response to 412.
Whats the syntax to set and return the serialized JSON in the http response body as above.
An example would be helpful on how to set all these http response headers.
Thanks
You are probably looking for...
$arr = array('message' => 'blah'); //etc
header('HTTP/1.1 201 Created');
echo json_encode($arr);
I am building my own rest api in php for practice. I can evaluate the http code sent to my api (post,put,delete,get). But when I send out my response I really am just printing out a json. For example, I build a response in my api like this
public function actionTest()
{
$rtn=array("id":"3","name":"John");
print json_encode($rtn);
}
I am not manipulating the headers in anyway. From reading stackoverflow, I understand that I should be returning http response codes to match my api results. How can I build on my api and return the response codes. I just don't understand how I can do it because right now I am just printing out a json.
I am not asking which codes to return. I just want to know how to return codes in general.
You could re-think your code this way
public function actionTest()
{
try {
// Here: everything went ok. So before returning JSON, you can setup HTTP status code too
$rtn = array("id", "3", "name", "John");
http_response_code(200);
print json_encode($rtn);
}
catch (SomeException $ex) {
$rtn = array("id", "3", "error", "something wrong happened");
http_response_code(500);
print json_encode($rtn);
}
}
Basically, before stream the output (the JSON data), you can set the HTTP status code by http_response_code($code) function.
And about your additional question in comment, yes, printing the JSON data is the correct way.