Question

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?

Was it helpful?

Solution

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?

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