Shubham Jha Shubham Jha - 12 days ago 6
Ajax Question

Change image preview and get values of img tag

I have the following code which displays the image previews. But when I select new images or say when I change images then on change the previously selected images preview should be removed and only new images should show up in the preview. But its not happening. Currently, if I select 3 images then the preview shows up. But when I select more images then the preview adds up to the previous images.

Also please tell me how can I get values of

<img id="imgs">
to insert in the database rather than the values from
<input type="file" name="files[]" multiple="multiple" id="file-5">
. Please help.

HTML:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server" enctype="multipart/form-data">
<textarea name="status" class="textarea newstatuscontent" placeholder="What are you thinking?"></textarea>
<input type="file" name="files[]" multiple="multiple" id="file-5"><br />
<img id="imgs"><br />
<input type="submit" name="post" value="Post" class="post-btn" id="submit" />
</form>


Jquery:

$(document).ready(function(){
$("#file-5").on('change',function() {
var fileList = this.files;
for(var i = 0; i < fileList.length; i++){
var t = window.URL || window.webkitURL;
var objectUrl = t.createObjectURL(fileList[i]);
$('.removeimg').fadeIn();
$('#imgs').append('<!--span class="img_'+i+'" onclick="del('+i+')" style="cursor:pointer; margin-right: 3px;"><b>x</b></span--><img class="img_'+i+'" src="' + objectUrl + '" width="150" height="150" style="margin-right: 3px;">');
j = i+1;
if(j % 3 == 0)
{
$('#imgs').append('<br>');
}
}
});
});

Answer

The img element is not a container. You should use a div element instead like this:

<div id="imgs"></div>

Then to have all images removed whenever the user selects new images, simple use jQuery empty (before the for loop) on your container div#imgs to remove all the images it contains:

$('#imgs').empty();

A full working example:

function del(index) {
    $('div.img_'+index).remove();
    updateFiles();
}

function updateFiles() {
    var fileIndexes = $('#imgs > div').map(function() {
        return $(this).data('index');
    }).get().join(",");
    $('#files_selected').val(fileIndexes);
}

$(document).ready(function() {
    $("#file-5").on('change', function() {
        var fileList = this.files;
        $('#imgs').empty();
        for (var i = 0; i < fileList.length; i++) {
            var t = window.URL || window.webkitURL;
            var objectUrl = t.createObjectURL(fileList[i]);
            $('.removeimg').fadeIn();
            $('#imgs').append('<div data-index="' + i + '" class="img_' + i + '"><span class="img_' + i + '" onclick="del(' + i + ')" style="cursor:pointer; margin-right: 3px;"><b>x</b></span><img class="img_' + i + '" src="' + objectUrl + '" width="150" height="150" style="margin-right: 3px;"></div>');
            j = i + 1;
            if (j % 3 == 0) {
                $('#imgs').append('<br>');
            }
        }
        updateFiles();
    });
});
#imgs > div {
    display:inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server" enctype="multipart/form-data">
    <textarea name="status" class="textarea newstatuscontent" placeholder="What are you thinking?"></textarea>
    <input type="file" name="files[]" multiple="multiple" id="file-5"><br />
    <div id="imgs"></div>
    <input type="submit" name="post" value="Post" class="post-btn" id="submit" />
    <input type="hidden" name="files_selected" id="files_selected" />
</form>

EDIT

The javascript files property is readonly, so to do what you want, you'll have to have a hidden input and update it with a string of comma separated indexes that point to the selected files array in PHP. Also, if you add display: inline CSS rule, then you'll have the divs on the same line and break every 3 images as your code works. See my updated snippet code for the whole working example.

To see the exact out put, use the following PHP code:

<pre><?php
print_r($_POST);
print_r(explode(',', $_POST['files_selected']));
?></pre>

<pre><?php
print_r($_FILES);
?></pre>

OUTPUT

Array
(
    [status] => 
    [post] => Post
    [files_selected] => 0,2
)
Array
(
    [0] => 0
    [1] => 2
)
Array
(
    [files] => Array
        (
            [name] => Array
                (
                    [0] => 1c.jpg
                    [1] => 1e.jpg
                    [2] => 2c.jpg
                )

            [type] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                    [2] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => /var/www/clients/client3/web35/tmp/phpzkmzlf
                    [1] => /var/www/clients/client3/web35/tmp/php9HuwoF
                    [2] => /var/www/clients/client3/web35/tmp/phpZiOur5
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                    [2] => 0
                )

            [size] => Array
                (
                    [0] => 11384
                    [1] => 7348
                    [2] => 12700
                )
        )
)

You have all selected files indexes to an array by making this call $selected = explode(',', $_POST['files_selected']

Comments