Reputation: 2879
My JQuery code:
<script>
jQuery(document).ready(function() {
var response = jQuery.ajax({
url: 'filename.jpg',
type: 'HEAD',
async: true,
error: function()
{
return "file does not exist";
},
success: function()
{
return "file exists";
}
});
alert (response);
});
</script>
does not return anything. It should return either "file does not exist" or "file exists" and the message should be shown in an alert box. But the alert box has [object Object]
value instead.
Upvotes: 0
Views: 516
Reputation: 68
Ajax is asynchronous. When you call alert (response);
response has not been resolved yet. I suggest something like this:
jQuery(document).ready(function() {
jQuery.ajax({
url: 'filename.jpg',
type: 'HEAD',
async: true,
error: function()
{
handleResponse("file does not exist");
},
success: function()
{
handleResponse("file exists");
}
});
});
function handleResponse(response){
alert(response);
}
or just move the alert into the error/success functions.
Alternatively, you can do it like this:
loadAnImage = new Image();
loadAnImage.onload = function() {/*success*/}
loadAnImage.onerror = function() {/*error*/}
loadAnImage.src = "/*URL HERE*/";
Upvotes: 2