ajax request in extjs always executes success - javascript

I have a ajax request, where i have code for both success and failure
success: function(my_response) {
},
failure: function(my_response) {
}
I am using Perl CGI in the server to handle the Ajax request, it prints below string when there is a failure
print "Content-type: text/plain\n\n";
print "{success: false, errors: {response: 'Query Failed -- Please check the syntax'}}";
exit
In the firebug, i can see the above response. But, my browser is always executing the code in success. Is there anything wrong in the way i am handling the ajax request?

You are sending JSON message with status code 200 which is considered as success. The fact that this JSON message contains some custom structure with an error message is not something that extjs is capable of knowing. You could either send a 500 HTTP status code from your server or simply use an if condition in your success handler like this:
success: function(my_response) {
if (my_response.success) {
alert('it worked!');
} else {
alert('oops, something went wrong: ' + my_response.errors.response);
}
}
Also readapt the content type to what you are actually sending:
print "Content-Type: application/json\n\n";

Related

My restify POST error data isn't visible in the client JavaScript

I'm trying to implement a POST REST call in node.js using restify. In this instance, I want to send an error to the browser. Unfortunately, I haven't figured out how to send the error data so that the browser JavaScript can see the error data I sent.
When I call the doPost() function on the browser, it performs an ajax POST call to my server. The server code returns with an error 400 and a small JSON object containing an error message.
The browser then goes to the .fail() function. However, the textStatus is "error", errorThrown is an empty string, and the jqXHR properties are readyState : 0, responseText : "", status : 0, statusText : "error".
What can I do to get my error data from Node to the client browser?
Here is the jQuery code that runs in the browser:
function doPost() {
$.ajax({
url: "http://localhost:3979/api/address",
type: "POST",
// Request body.
data: {key: "mykey", address: "myaddress"}
})
.done(function(data) {
// Show the formatted JSON in the text area.
$("#outputTextArea").val(JSON.stringify(data, null, 2));
})
.fail(function(jqXHR, textStatus, errorThrown) {
// An error occurred. Display the error information.
$("#outputTextArea").val(
"status: " + jqXHR.status +
", textStatus: " + textStatus +
", errorThrown" + errorThrown + "\r\n");
});
}
And here is the Node.js code that runs on the server:
const restify = require('restify');
// Create the server.
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3979, function () {
console.log(`${server.name} listening to ${server.url}`);
});
// POST call that returns an error.
server.post("/api/address", async (req, res) => {
res.send(400, {errorMessage: "The value given does not appear to be valid."});
});
Edit: Both res.status(422); res.send("The value given does not appear to be valid."); and res.send(new BadRequestError('meh')); fail in the exact same way. The jqXHR properties are the same (zero for readyState and status, empty string for responseText), textStatus is "error, and errorThrown is an empty string.
I tested my .ajax code against a known working POST call, and it gets proper values, including a JSON responseText.
Can someone please try this out in node.js and show me what I'm doing wrong, or show me the right way to send an error to the browser. So far, nothing works.
Edit: After further tests and experiments, this time with curl, I found that my POST call works and returns expected values.
I used this curl command to retrieve the status code:
curl -s -o /dev/null -w "%{http_code}" -X POST http://localhost:3979/api/address
And received this response: 400
I then used this curl command:
curl -X POST http://localhost:3979/api/address
And received this response:
{"errorMessage":"The value given does not appear to be valid."}
So it appears that the problem exists on the browser end.
This stackoverflow question seems to indicate a cross domain problem (page: www.mydomain.com/register, REST: server.mydomain.com/rest). However, I am doing all of this using localhost, so I don't see how the browser could see a cross domain issue here.
Any ideas on how to get REST POST errors to show up in the browser when running on localhost?

jQuery AJAX HTTP error codes not being picked up in Safari

I'm using jQuery.ajax() to send data to my own PHP file for adding subscribers to a MailChimp list. The Javascript looks like this:
$.ajax({
url: url,
method: 'POST',
data: params, // the data is working so here is just the variable I'm using
error: function(response) {
console.error($.parseJSON(response));
// show some response text through DOM manipulation
}, success: function (response) {
console.log($.parseJSON(response));
// show some response text through DOM manipulation
}
});
The PHP looks like this (at least just for the HTTP status code response):
// All my PHP code, which is working is above this
$result = curl_exec($ch);
echo $result; // This is for the response text in the ajax call
http_response_code(intval(json_decode($result)->status)); // This should be sending a success code or triggering errors
On Chrome, if I get a good response (a HTTP status in the 200s), the success function will run. If I trigger an error (in my testing, a HTTP status in the 400s), the error function will run. All is good.
However, on Safari, whether it is a 200 or a 400 code, the success function runs. There seems to be no detection in my Javascript of error codes when using the Safari browser. How can I fix this? Why is it different between Chrome and Safari?
In case it matters, I'm working locally with CodeKit and MAMP PRO to run my project. Thanks.
You need to send the response code before the actual response, i.e.,
$result = curl_exec($ch);
http_response_code(intval(json_decode($result)->status)); // This should be sending a success code or triggering errors
echo $result; // This is for the response text in the ajax call
This is because http_response_code is essentially running a header("HTTP/1.0 $code $codeMessage") and the header needs to be sent before the response.

JQuery AJAX request show AJAX and PHP errors

I am using a Jquery $.post request to get a JSON response that is generated by PHP. When the request is complete, a success or error message is displayed. During development however, I sometimes have PHP errors which end up being returned instead of the JSON. When this happens, I just get the error message:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The code I have now looks like this:
var request = $.post(url, data, null, "json");
request.fail(on_failure);
var on_failure = function(jqXHR, text_status, error_thrown)
{
$("#text_status").empty().append(error_thrown);
};
I would like to be able to show the PHP error if one is returned rather than just indicate that there is a PHP error (just to speed up debugging). Obviously, if a non-JSON parsing error such as HTTP 404 occurs, I still want to display that. I found a method here that indicates that I can detect this error with something like this
$.ajaxSetup({
error: function(jqXHR, exception) {
if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
}
}
});
But it doesn't seem like that helps me because it runs for every request rather than individual requests and (as far as I know) it does not allow access to the error message in the returned data.
No sure what version of jquery are you using. Anyway, did you try to remove the json dataType?
var request = $.post(url, data, null);
Doing this jQuery will guess the dataType for you.
I hate to steal mkross1983's credit, but he has not responded to my request to turn his comment into an answer. mkross1983 said:
Have you tried using Firebug under the "Net" tab to see the results of the requests? Sometimes errors can be seen there that can give some clues to the problem
The Firebug "Net" tab has proved to be a valuable debugging tool. This way I can see exactly what request was made and the response sent to it. It even allows me to see the headers and cookies that were sent with the request.
Thank you mkross1983

Using AJAX to call a php function keeps failing

im having a problem trying to get an ajax call to trigger a php function and then return successfully. As far as i can see my syntax is correct.
But all i get back is failed! Any ideas?
EDIT
I have changed my AJAX request to send without using data, just to rule out that being a problem and i have implemented some of the things people suggested below but to no avail, heres what my 2 files look like now:
ship.js:
function set_ship()
{
//var datastring = {'ship':'true'};
$.ajax({
type:'POST',
url:'soap/classes/class.ship.php',
success: function(success){
alert('success');
},
error: function(fail){
console.log(fail);
}
});
}
And my PHP class.ship.php:
<?php
var_dump("hello");
header('Content-type: application/json');
echo json_encode(array("result"=>"true"));
From the var_dump on my PHP script i can see that the class.ship.php isnt even being called for some reason.
Thanks
Please try this
json_encode(array("result"=>"true"));
because
json_encode(true) // will return just "true" which is not a valid json
Also try serializing the dataString , by doing
data: datastring.serialize();
lowercase JSON_ENCODE
success: function(success), error: function(fail)
check what is returned in network tab of firebug.
You need to set the content header to json header('Content-type: application/json'); and make sure you request return only json coz ajax is waiting only for "JSON" and it will throw parse error
if(isset($_POST['ship']) && $_POST['ship'] == "true"){
$result = "result";
header('Content-type: application/json');
echo json_encode(true);
}
I would suggest that you check what it being actually returned by the server.
The error callback receives one argument representing the xhr object, so you can inspect that directly by placing a breakpoint or using console logging, like this
error: function(xhr) {
console.log(xhr);
}
Likewise, the success callback receives three parameters: the status, the returned data and the XMLHTTPRequest Object, so you can check those in the very same way:
success: function(status, data, xhr) {
console.log(status, data, xhr);
}
You should look for the response status code and the response text in the xhr object to understand what is going wrong. If you're seeing a 200 OK response status, the data returned from the server is probably not being interpreted correctly as JSON data, so you should try setting the response header server side to application/json.
An error might occur also if something else is appended or prepended to your response. This happens especially when warnings occur in the code before returning and you have error reporting set to ON.

How to handle specific HTTP error for all AJAX calls?

I have a web app, requesting and sending data via AJAX, and as a response, my server-side sends HTTP status codes, depending on the situation. so for example if a user tries to login while he's logged I probably return a 400 HTTP status code. And eventually i handle it with an alert, etc.
But handling these HTTP Status codes gets too heavy, since I'm making heavy use of AJAX. that means I'll be handling HTTP status code repeatedly with every AJAX request, which will result in duplicated code, and that's a bad practice.
So, what I'm looking for is a way to handle all these errors in one place, so I just handle all 400, 401, etc with the same code.
What i'm currently doing:
Handling the errors manually for each AJAX call. By using the statusCode in$.ajax().
statusCode: {
500: function(data) {
alert('Some friendly error message goes here.');
}
It seems like an overkill for me, as my web app develops, and as I create more ajax calls. I'll be repeating this piece of code again and again.
Currently, the only idea I have in mind is creating a function that will work on top of AJAX, something like:
function doAjax(type,url, data, moreVars) {
//this function is just a SIMPLE example, could be more complex and flexible.
$.ajax({
type: type,
url: url,
data: data,
moreOptions:moreVars,
//now handling all status code.
statusCode: {
//handle all HTTP errors from one place.
}
});
}
doAjax("POST", 'mydomain.com/login.php', dataObj);
You can use $.ajaxSetup() to register global error state handlers.
Description: Set default values for future Ajax requests.
Example:
$.ajaxSetup({
statusCode: {
500: function(data) {
alert('Some friendly error message goes here.');
}
}
});

Categories

Resources