I'm working on a school project. I'm creating a webform that helps the user to edit some entries of a database (let's say I want to edit an entry of the 'books' table).
First, I display a list of books, the user can click on the one he/she wants to edit and all the informations will be retrieved and displayed inside input forms, so that he/she can edit and then submit the updated data.
I'm having one problem. Associated with each book there's a picture that I'd like to display, unfortunately all I can retrieve from the database is the name of the picture file but not the extension. The only extensions allowed are jpeg, gif, jpg and png. What I tried this far is the following function:
function UrlExists(url)
{
var ext = [ ".jpeg", ".jpg", ".png", ".gif" ];
var http = new XMLHttpRequest();
var url_ext = '';
$.each(ext, function(key, value){
http.open('HEAD', url+value, false);
http.send();
if(http.status!=404){
url_ext = url+value;
}
});
if(url_ext){
return url_ext;
}else{
return "image_path/notfound.jpg";
}
}
It's not pretty but it works. The only side-problem are all the warnings on the dev-tool in chrome. I don't really mind but I feel like this is bad practice, I'm basically trying to retrieve the file hitting the server with every allowed extension.
This code works because there are no files with the same name, so there cannot be "picture.jpg" AND "picture.png". Is there a good solution to this problem ? I tried using some php inside jquery, with the glob() function, but I couldn't make it work. Something like this:
$('#image_id').attr('src', '<?php echo json_encode(glob("image_path/filename.{jpg,jpeg,png,gif}", GLOB_BRACE)) ?>' );
It's not really doing any php work, I think I'm missing something to make php work inside a jQuery function or maybe it runs when the document is loaded so it wouldn't work. Anyway I'm not even sure this can work. Any help would be much appreciated. Keep in mind I'm no php/jquery expert ;)