1

I have some elements in my document which contains an Image IDs, and I want to replace those IDs with the Images:

$(".image_id_field").each(function() {
  img_id = $(this).html();

  $.post("ajax/get_image.php", { id: img_id }, function( response) {
    // data = "<img src='path_to_image.png' />"
    // How is it possible, to get the current $(this) in here to append the response
  });
)

Two ideas I had:

1. Is it possible, to get the given id from the post parameters in the success function to identify the element?

2. Is it possible, to make the $post asynchronously and use the response after triggering the post request?

user1383029
  • 1,685
  • 2
  • 19
  • 37

1 Answers1

0

Functions remember variables in their parent scope when they're defined. This is called a closure. You can read about it here

So in order to retain a reference to the element, store the element in a variable like so:

$(".image_id_field").each(function() {
    var $this = $(this), // store the jQuery element
        img_id = $this.html();

    $.post("ajax/get_image.php", { id: img_id }, function( response) {
        // the callback function still references the $this var defined in the parent scope
        $this.html(response);
  });
)

I'm not sure about your second question, as the $.post call is asynchronous already.

I'd recommend learning about variable scope in more detail as in your example you were creating a global variable called img_id. What is the scope of variables in JavaScript?

Community
  • 1
  • 1
Seain Malkin
  • 2,273
  • 19
  • 20
  • Thank you! This was exactly what I needed. In my second idea i wanted to write "sychronously" instead of "asynchronously". – user1383029 Nov 08 '13 at 15:26