简体   繁体   English

图片上传脚本仅适用于保存在DB中的最新<li> </ li>

[英]Image upload script only works for latest <li></li> saved in DB

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. 在网站的一个页面上,有一个表格,在每个<li></li> ,有一个上传图标 ,用户可以在其中添加一个图像。

The issue is the image upload only works for the "highest" empty <li> on the table. 问题是图像上传仅适用于表格中“最高”的空<li>

Here, "highest" means the latest <li> saved in the DB (table is sorted by TIME DESC). 这里, “最高”表示保存在DB中的最新<li> (表按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. 例如,如果我想将图像上传到页面上的随机<li></li> ,一旦我选择了图像,就不会发生任何事情。 But if I select the "highest" empty (empty = no image saved in DB) <li></li> , it works like a charm. 但是,如果我选择“最高”空(空=没有保存在数据库中的图像) <li></li> ,它就像一个魅力。

HTML: 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): JAVASCRIPT (一旦选择一个图像就会触发上传):

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

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

PHP: 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 . 首先,您发布的HTML 无效 I suspect that your Javascript code has a problem with such invalid HTML. 我怀疑您的Javascript代码存在此类无效HTML的问题。 However, the following code has not (for your HTML code duplicated once for demonstration purposes): 但是,以下代码没有(为了演示目的,您的HTML代码重复一次):

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/ 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. 您所需要的只是将正确的侦听器分配给正确的元素,如您所见,我不使用任何ID值,因为它们是重复的。

I can use as well duplicate IDs in case you think this is not an argument, this is demonstrated in a related answer: 如果你认为这不是一个参数,我也可以使用重复的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. 我希望这可以帮助你在地面上重新获得足球,这样你就可以继续验证HTML并清理一下。

It appears that your html form has 看来你的html表单有
<input type="hidden" value="<?php echo $recipe_id; ?>"/>

However, the input field name attribute is not present so the post data stream will not have a definition for $_POST["recipe_id"] field. 但是,输入字段名称属性不存在,因此后期数据流将不具有$_POST["recipe_id"]字段的定义。 The undefined value is likely being interpreted by your script as 0 and so only the top or "highest" li image is updated. 未定义的值很可能被脚本解释为0,因此只更新顶部或“最高”的li图像。

If you alter the input field thus: 如果您改变输入字段:

<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>"/>

You may have better results... 你可能会有更好的结果......

Just change this part : 只需更改此部分:

document.getElementById("file").onchange = function() {
   document.getElementById("upload_icon").submit();
}

With : 用:

$("#file").change(function(){$(this).parents("form").get(0).submit();})

In your HTML, you have: 在您的HTML中,您有:

<form id="upload_icon" action="upload_extra.php" method="POST" 
  enctype="multipart/form-data">

Then your Javascript mentions: 然后你的Javascript提到:

document.getElementById("file").onchange = function() {
  document.getElementById("upload_icon").submit();
}

According to some specifications ( HTML4 , HTML5 ), there shouldn't be same IDs on multiple elements. 根据一些规范( HTML4HTML5 ),多个元素上不应该有相同的ID。 So, when you use an iteration, avoid printing ids without appending something unique on them, like: 因此,当您使用迭代时,请避免打印ids而不在其上添加任何唯一内容,例如:

<form id="upload_icon<?php print $recipe_id; ?>"
  action="upload_extra.php" method="POST" enctype="multipart/form-data">

Your Javascript can be turned into something like the following. 您的Javascript可以变成以下内容。 (please mind that you need to call this function after the page is loaded) (请注意,您需要在加载页面后调用此函数)

function afterPageLoad() {
  var buttons = document.getElementsByClassName("upload");
  for (i = 0; i < buttons.length; i++) {
    buttons[i].onchange = function() {
      this.form.submit();
    }
  }
}

Now, if your PHP code has stopped working, we would need to see that, too, at the part you omitted by writing 现在,如果您的PHP代码已经停止工作,我们也需要在您通过编写省略的部分看到它

//get image attributes

where the $location variable is initiated. 启动$location变量的$location

In JavaScript provided its submitting the form by finding the element by ID, As in the HTML code the IDs are repeating (not a standard method, IDS can't repeat but class can) so the browser will always submit the last (highest) form only, that's why when adding image to highest row its working and in between its not. 在JavaScript中提供了通过ID来查找元素提交表单,在HTML代码中,ID是重复的(不是标准方法,IDS不能重复,但类可以),因此浏览器将始终提交最后(最高)表单只是,这就是为什么在将图像添加到最高行时它的工作原理和它之间的原因。

Please check this code out 请检查此代码

 <script>
$(document).ready(function() 
{
    id = '';
   $('.upload_icon').click(function(){
        id = $(this).attr('id');
       $(this).parent().find('#file'+id).click();
   });

    $(".upload").change(function () {
        $('#upload_icon'+id).submit();
    });
});
</script>
<style>
.upload_icon {
    cursor:pointer;
}
</style>
<ul>
<?php for($recipe_id=1;$recipe_id<10;$recipe_id++): ?>
<li id="entry<?php echo $recipe_id ?>">
    <div class="addimage_icon" id="upload<?php echo $recipe_id; ?>">
        <form action="upload.php" method="POST" enctype="multipart/form-data" id="upload_icon<?php echo $recipe_id; ?>">
            <input class="upload" id="file<?php echo $recipe_id; ?>" type="file" name="image" style="display:none"/>
            <input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>" />
            <img class="upload_icon" src="https://cdn2.iconfinder.com/data/icons/picons-basic-2/57/basic2-036_cloud_upload-128.png" id="<?php echo $recipe_id; ?>">
        </form>
    </div>
</li>
<?php endfor; ?>
</li>

In the HTMl code I have provided have different IDs for each forms (used the $recipe_id as suffix), when ever click event on the upload icon is fired it will check which upload icon is clicked by its attribute Id and then the respective input type file value is changed by finding the element by Id (used the same $recipe_id as suffix here also). 在我提供的HTMl代码中,每个表单都有不同的ID(使用$ recipe_id作为后缀),当上传图标上的点击事件被触发时,它将检查哪个上传图标被其属性Id点击,然后是相应的输入类型通过Id查找元素来更改文件值(此处也使用相同的$ recipe_id作为后缀)。 On input type change event also same logic is used to fire the respective form. 在输入类型更改事件中,也使用相同的逻辑来触发相应的表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM