Question

i have jquery code that finds "src" attribute of all images in div (every image has same class: .image_class), then sends it to ajax (and then to php file that finds that images and delete them). Here is code:

$remove_images = $.each($("#main_div").find(".image_class").attr(""));
$.ajax({
    type: 'POST',
    data: {
        action: 'delete_images',
        imagefile: $remove_images
    },
    url: 'delete.php',
    success: function(msg) {
        alert("" + msg + "");
    }
})

PHP file looks like this:

  if($_POST["action"]=="delete_images"){
    @unlink($_POST['imagefile']);
  }

But this does not work. I suspect something is wrong in $remove_images (lets say "$.each is bad).

Was it helpful?

Solution

You can use the .map() method to collect stuff from a jQuery collection.

The callback will run for every element in the collection that is returned by .find() in our case. this will represent the current DOM element. Whatever you return from the callback will be included in the result.

var $remove_images = $("#main_div").find(".image_class").map(function () {
    return $(this).attr('src');
}).get();

jsFiddle Demo

I used the .get() method to convert the result into a plain Javascript array.

Please read the manual of .map() for further information (and in general, get used to using the manual, because you could have found the answer to your question there - the examples are great in most cases).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top