JavaScript client checks if URL is an image - javascript

The browser gets a list of external URLs, and I want to filter the ones that are images.
The URLs are on other domains, so I think I can only do this using a JSONP dataType.
function checkImageURL(url){
var isImage = false;
$.ajax({
type : "GET",
dataType : "jsonp",
url : url,
success: function(data){
console.log("Success was returned => a JSON file was returned");
return false;
},
error: function(jqXHR, textStatus, errorThrown){
console.log(url);
console.log(jqXHR, textStatus, errorThrown);
if(jqXHR.status === 404){
console.log('Is image');
return true;
}
else if(jqXHR.status === 200){
console.log('Not image');
return false;
}
else{
console.log("new status!",jqXHR.status);
return false;
}
}
});
}
checkImageURL("https://en.wikipedia.org/404");//404 page
checkImageURL("http://www.sheldonbrown.com/web_sample1.html");//HTML page
checkImageURL("http://sites.duke.edu/jc319/files/2014/03/yellow-disney-pixar-cars-33967438-3507-2481.jpg");//Real image
jsfiddle
Results:
GET https://en.wikipedia.org/404?callback=jQuery21307281952630728483_1435482371527&_=1435482371528 404 (Not Found)
https://en.wikipedia.org/404
Object {readyState: 4, status: 404, statusText: "error"} "error" "error"
Is image
Uncaught SyntaxError: Unexpected token <
http://www.sheldonbrown.com/web_sample1.html
Object {readyState: 4, status: 200, statusText: "load"} ........
Not image
Refused to execute script from 'http://sites.duke.edu/jc319/files/2014/03/yellow-disney-pixar-cars-33967438…2481.jpg?callback=jQuery21307281952630728483_1435482371531&_=1435482371532' because its MIME type ('image/jpeg') is not executable.
http://sites.duke.edu/jc319/files/2014/03/yellow-disney-pixar-cars-33967438-3507-2481.jpg
Object {readyState: 4, status: 404, statusText: "error"} "error" "error"
Is image
My issue now is that a 404 page and a real image both return the same error (a 404). The browser itself throws a different error for each, but apparently I can't catch those ones.
I am kind of stuck right now, so either it's not possible to do, either there is a completely different solution?

Leave the dataType empty since you don't know what the response content is. Instead set crossDomain to true in your ajax request.
If you get a success response that still doesn't mean the response is an image so check for the content type:
success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
console.log((ct.indexOf('image') > -1) ? "is image" : "not image");
}

Related

how to show custom REST API error messages in javascript client

I have Java REST API generated using swagger, in that if client is unauthorized then then i am sending custom error messages in response
public Response collaborationCollabIdDelete(Integer collabId, SecurityContext securityContext, String authBase64String) throws NotFoundException {
// do some magic!
ErrorRequestObject erb;
ArrayList <ErrorRequestObject> erbs = new ArrayList<ErrorRequestObject>();
if (authBase64String == null)
{
erb = new ErrorRequestObject(); erb.setError("Missing Authorization in Header"); erb.setPath("Header:Authorization");
erb.setProposedSolution("Authorization Header should contain user:pwd:nhPath as Base64 string");
erbs.add(erb);
}
if (erbs.size() == 0)
{
//success code here
}
else
{
return Response.status(400).entity(erbs).build();
}
}
I call this API using ajax as follows,
$.ajax({
url : URL,
type : "DELETE",
dataType : "json",
contentType : "application/json",
async : false,
success : function(result){
Response.resolve(result);
console.log("Response : " + JSON.stringify(result));
}
});
now when i call this API with ajax call it without authorization in header it gives me 400 status that is fine as expected but how do i get error object created with java ? can anyone please tell me how do i get this error object at javascript client ?
Something like this:
$.ajax({
url : URL,
type : "DELETE",
dataType : "json",
contentType : "application/json",
async : false,
success : function(result){
Response.resolve(result);
console.log("Response : " + JSON.stringify(result));
},
error: function(err) { /* your code here*/})
});
You can use the error function like
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
Where,
The jqXHRobject, textStatus - a string describing the type of error that occurred and an optional exception object as errorThrown, if one occurred. So, you can manipulate the statusCode and everything from this parameters like,
jqXHR.status == 400

AJAX call doesn't go into "error:" block if the API server returns http 500

I want to implement a retry logic in my javascript code. This is how I'm calling the API:
$.ajax({
url: api_url + 'report',
type: 'GET',
dataType: 'json',
async: false,
tryCount : 0,
retryLimit : 3,
headers: {
"Authorization": "Basic " + btoa(api_username + ":" + api_pass)
},
data: {start: start_date, end: end_date},
success: function(result) {
data = result.results;
console.log("success");
},
error : function(xhr, textStatus, errorThrown ) {
console.log("in error");
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
console.log("try count:");
console.log(this.tryCount);
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
console.log("still 500");
} else {
console.log("still !500");
}
}
});
So when there are issues with the server and it returns http 500 then still my control in the above JS file doesn't go into the "error:" block and this line: "console.log("in error");" doesnt get printed on the console.
How can I correctly implement a retry logic in my code in case my server returns 500 then it should keep on retrying for some x amount of times?
500 error generally means that something is wrong with backend server. So it doesn't get into error block of client JavaScript. I don't think there is anything you can do. But in general you can always ask backend developers to do better error handling and return apt error response if possible.

AJAX error is returned as Success

AJAX error is being returned as Success. How to return JSON error from ASP.NET MVC? Could you tell me what I'm doing wrong? Thank you.
[HttpPost]
public JsonResult Register(int EventID)
{
try
{
// code
return Json(new { success = true, message = "Thank you for registering!" });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
$.ajax({
url: "#Url.Action("Register", "Home")",
type: "post",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(postData),
success: function(data) {
},
error: function (data) {
}
});
The error function gets executed only when the HTTP Response Code is not HTTP 200 Ready. You handle the error in the server-side and return proper response, which will be picked up by success function in the AJAX call. Instead, use the status variable in your JSON and handle it on the client side:
success: function(data) {
if (typeof data == "string")
data = JSON.parse(data);
if (data.success) {
// Code if success.
} else {
// Code if error.
}
},
From the docs (scroll down to the error section):
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
The Ajax error method is hit only when you get a Yellow Screen Error in the server side. In your scenario you are handling the error using try catch and returning a valid response. So this is not considered as a error but a valid response. Remove your try catch so that Ajax will pick up the error event, else if you want to show the actual error message from server then you can use the success property to decide if the response was a success or a error , its similar to what Praveen has already posted in his answer.
success: function(data) {
if (data.success) { //as you are passing true/false from server side.
// Code if success.
} else {
// Code if error.
}
},

Ajax response status 200 but shows error message

I'm getting status as 200 but it's printing message present inside error message alert("error...");. Why so?
function makeSelect() {
var blouseoption = document.querySelector('input[name="blouseoption"]:checked').value;
var url = "http://dukano.co/sakhidev/retailon/productoption/values";
alert(url);
var jsondata = $j('#customoption').serialize();
alert("jsondata: " + JSON.stringify(jsondata));
$j.ajax({
type : 'POST',
url : url,
data : jsondata,
dataType : 'json',
success : function(response) {
console.log("calling");
console.log(response);
alert("call success");
alert("response data:" + JSON.stringify(response));
if (response.status == 200) {
console.log("yes");
} else if (response.status == "error") {
console.log("no");
}
},
error : function(response) {
alert("error...");
alert("response:" + JSON.stringify(response));
console.log(response);
}
});
}
Magento's controller function returning json value
public function valuesAction(){
$blouseoption = $this->getRequest()->getParam('blouseoption');
$sareefinishing = $this->getRequest()->getParam('sareefinishing');
$data = array( 'sfinishing' => $sareefinishing, 'layout' => $this->getLayout());
Mage::dispatchEvent('product_custom_option', $data);
$jsonData = json_encode(array($blouseoption, $sareefinishing));
$this->getResponse()->clearHeaders()
->setHeader('Content-type','application/json',true);
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($jsonData));
$this->getResponse()->sendResponse();
}
As you are using
dataType: "json"
this evaluates the response as JSON and returns a JavaScript object.any malformed JSON is rejected and a parse error is thrown.
This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function and set the textStatus parameter to "parsererror".
Make sure that the server returns valid JSON. empty response is also considered invalid JSON; you could return {} or null for example which validate as JSON.
try to check the textStatus in the error.
error : function(jqXHR,textStatus,errorThrown)
{console.log(textStatus)}
if this prints "parsererror" then of course you have problem with your returning json. please check that.
More Info
Alternative answer
Instead of returning status 200 with empty response, you can return status 204 and not return any response. Status 204 is for No Content. JQuery should not throw any error in this case.

How to capture the 500 error message using jquery?

How can i capture the 500 error message using jquery? I want to keep on checking for the 500 error message for sometime until it changes and time out after 50 sec.
I used the code below to try to capture and check the 500 error message but it doesnt seem to catch the 500 error message. I can see it in the firebug
$.ajax({
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
Dispite the accepted answer mentioned by #Danny, you can also do this in newer versions of jQuery.
var xhr = $.ajax({
url: "somewhere"
});
xhr.fail(function(xhr, textStatus, error) {
// Error handling stuff here ...
});
See Deferred Object.
Are you missing url in $.ajax like the one below
$.ajax({
url: "/path to page",
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
You can check the status in error of ajax post please check the below code.
$.ajax({
.....
success: function (data) {
},
complete: function (XMLHttpRequest, textStatus) {
},
error: function (e, status) {
if (e.status == 404)
alert("404 error");
}
});
Thanks

Categories

Resources