views:

67

answers:

2

I need to make an Ajax call and have the response update a child of the DOM element that was clicked to trigger the event. Sample HTML:

<div class="divClass">
  <p class="pClass1">1</p>
  <p class="pClass2">Some text.</p>
</div>
<div class="divClass">
  <p class="pClass1">2</p>
  <p class="pClass2">Some text.</p>
</div>
<div class="divClass">
  <p class="pClass1">3</p>
  <p class="pClass2">Some text.</p>
</div>

Sample javascript code:

$(document).ready(function(){
    $(".divClass").each(
        function(e) {
            $(this).attr('divValue', $('p.pClass1', this).text());
            $('p.pClass1', this).text('?');

            $(this).click(function(e) {
                e.preventDefault();

                $.ajax({
                    type: "POST",
                    url: "ajax.php",
                    data: "val=" + $(this).attr('divValue'),
                    success: function(msg) {
                        myData = JSON.parse(msg);
                        $('p.pClass1', this).html(myData.results[0]); // problem exists here
                    }
                });
            });
        }
    );
});

On the problem line "this" refers to the Ajax response object. I do not know how to retain the "this" context of a few lines above so I can update its contents with the response of the Ajax call.

+1  A: 
var self = this;
$.ajax({ ..., success: function (msg) { ... $('p.pClass1', self) ... } ...
just somebody
+2  A: 

With a closure!

$(document).ready(function(){
    $(".divClass").each(
        function(e) {
            $(this).attr('divValue', $('p.pClass1', this).text());
            $('p.pClass1', this).text('?');

            $(this).click(function(e) {
                e.preventDefault();

                // Store 'this' locally so it can be closed
                // by the function scope below
                var self = this;

                $.ajax({
                    type: "POST",
                    url: "ajax.php",
                    data: "val=" + $(this).attr('divValue'),
                    success: function(msg) {
                        myData = JSON.parse(msg);

                        // Now used your closed variable here
                        $('p.pClass1', self).html(myData.results[0]); // problem exists here
                    }
                });
            });
        }
    );
});
Peter Bailey
This is exactly what I was missing. So simple, thanks.
Michael
Don't forget to add a "var" before the "myData = ..." part to prevent it from being declared as a global variable.Also, if you provide the $.ajax() function with a "datatype: 'json'" parameter, you won't have to use JSON.parse to parse the results.
antti_s