Reputation: 23409
I have to open a URL in a new tab in my JQuery code. I am using the below code to do it.
window.open(result + PATHtoCALL);
It works fine however in some cases the report will not be available in the URL and I get the below output in the new browser tab
{"success":false,"timestamp":1408690695881,"error":{"code":"0"}}.
So I thought it might be a good idea to first validate if the Report is ready. If I get success in it then I will call the window.open(result + PATHtoCALL);
So I wrote the below code in Ajax to validate it. However it is always going in the error code.
$.ajax({
url: result + PATHtoCALL,
type: 'POST',
dataType: 'json',
success: (function(resp, statusText, xhr) {
if (resp.success)
{
console.log('.............Passed');
}
else
{
console.log('.........Failed');
}
}).bind(this),
error: (function(xhr, statusText, error) {
console.log('11111111111111111111111111111111',error);
}).bind(this)
});
However the above Ajax code always fails and the error is "SyntaxError: Unexpected token <"
If I run window.open(result + PATHtoCALL);
it works fine.
What is the mistake here in Ajax code ?
Is there a better alternative than this approach ?
I am sorry if it is really trivial. I am very new to Javascript.
Upvotes: 0
Views: 42
Reputation: 943142
If you are trying to open a URL in a new window, then it (presumably) is an HTML document (or something else that is designed to be human readable).
This:
{"success":false,"timestamp":1408690695881,"error":{"code":"0"}}.
is JSON.
This:
dataType: 'json',
tells jQuery to process the response as JSON no matter what the server says it is.
So:
If you get an error message, it will be a successful HTTP request (because the error is expressed at the data level not the HTTP level) so the Ajax request will be successful.
If you don't get an error message, it will also be a successful HTTP request, but the response will be HTML. jQuery will try to parse the HTML as JSON and fail. It will then throw run the error handler.
Approaches you could take to fix this include:
window.open
to a different URL to actually get the document.Upvotes: 1