Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery checking if an image exists in a folder

Tags:

jquery

image

i am changing the source of an image using the following code:

var src = "/Content/Productimg/" + data.image +".jpg";
              $("#image").attr("src", src);

However, sometimes if data.img returns test and test.jpg does not exist in the Productimg folder a funny icon is displayed.

Is there a way i can check if the image is there before assigning the src?

like image 455
Beginner Avatar asked Nov 26 '25 12:11

Beginner


1 Answers

For checking if image exists or not , you can do:

$.ajax({
    url:'http://yourhost/someimage.ext',
    type:'HEAD',
    error: function()
    {
        //file does not exist
    },
    success: function()
    {
        //file exists do something here
    }
});

like image 184
Sudhir Bastakoti Avatar answered Nov 28 '25 02:11

Sudhir Bastakoti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!