0

I am using codeigniter(PHP) for creating a web. I am loading data with jquery ajax and there is a image field in data array. Now i want to check if image is exists or not on server. How can i do this with jquery or javascript. My file location is :-

var path = 'C:\\wamp\\www\\project\\uploads';

if(val.default_image == null)
{
    var url = '<?php echo site_url().'uploads/default.png'; ?>';
    var style = 'background-color: rgb(246, 95, 13);height: 200px';
}
else if(checkImage(path+'\\'+val.default_image))
{
    $style = 'backgound-color:none;height: 200px';
    var url = '<?php echo site_url()."uploads/";?>'+val.default_image;
}

And i am trying this function:-

function checkImage(src) {
        var img = new Image();
        img.onload = function() {
            alert('yes');
            return true;
        };
        img.onerror = function() {
            alert('no');
            return false;
        };
    }

But this function is not working properly. Is there any better solution to check or this?

Gitesh Purbia
  • 1,094
  • 1
  • 12
  • 26
  • 1
    You don't set the `src` on the image you're loading? – wonderb0lt Jul 03 '15 at 15:02
  • 1
    Alternatively, instead of getting the image you could send a [HEAD request](https://stackoverflow.com/questions/333634/http-head-request-in-javascript-ajax) to the server from your JavaScript. – wonderb0lt Jul 03 '15 at 15:03
  • http://stackoverflow.com/questions/3381663/how-to-check-if-image-exists-with-given-url go check this – Deepak Kumar Jul 03 '15 at 15:06
  • Also, checking to see if an image exists is an asynchronous operation so you cannot structure `checkImage()` to directly return the value. The answer will have to come via a callback that occurs some time later. – jfriend00 Jul 03 '15 at 15:20

0 Answers0