The image download script only works for the latest version of & lt; li & gt; & lt; / li & gt; saved in the database

advertisements

Below is a script to upload images and save them to the DB.

On one page of the website, there's a table and inside each <li></li>, there is an upload icon where users can add one image.

The issue is the image upload only works for the "highest" empty <li> on the table.

Here, "highest" means the latest <li> saved in the DB (table is sorted by TIME DESC).

For instance, if I want to upload an image to a random <li></li> on the page, once I select an image, nothing happens. But if I select the "highest" empty (empty = no image saved in DB) <li></li>, it works like a charm.

HTML:

<li id="entry<?php echo $recipe_id ?>">
  <div class="addimage_icon" id="upload<?php echo $recipe_id; ?>">
    <form id="upload_icon" action="upload_extra.php" method="POST"
     enctype="multipart/form-data">
       <input  class="upload" id="file" type="file" style="display:none" />
       <input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>"/>
       <img class="upload_icon" src="/upload_icon.png">
    </form>
  </div>
</li>

JAVASCRIPT (upload gets triggered as soon as one image is chosen):

<script>
   $('.upload_icon').click(function(){
       $(this).parent().find('.upload').click();
   });

    document.getElementById("file").onchange = function() {
    document.getElementById("upload_icon").submit();
}
</script>

PHP:

<?php
include "includes/connnect.php";
$id = $_SESSION['id'];
$recipe_id = mysql_real_escape_string($_POST['recipe_id']);

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$recipe_id= $_POST['recipe_id'];

//get image attributes

$add = query("UPDATE cookbook SET recipe_pic = '".$location."' WHERE recipe_id =
'$recipe_id'");

header(Location:"home.php");

}
?>

What's going here ?


There are many, many problems with your question. First of all the HTML you've posted is invalid. I suspect that your Javascript code has a problem with such invalid HTML. However, the following code has not (for your HTML code duplicated once for demonstration purposes):

NodeList.prototype.forEach = Array.prototype.forEach;
document.querySelectorAll('input[type="file"]').forEach(function (file) {
    var click = function() {
        file.click();
    };
    var change = function() {
        console.log('change:', file.value);
    };
    file.form.querySelector('img').addEventListener('click', click);
    file.addEventListener('change', change);
});

http://jsfiddle.net/eBLL5/

All you need is to assign the correct listeners to the correct elements, as you can see, I do not use any ID values because they are duplicated.

I can use as well duplicate IDs in case you think this is not an argument, this is demonstrated in a related answer:

  • remove text from multiple spans having same id

I hope this helps you to get the feets again on the ground so that you can continue to validate the HTML and clean up a little bit.