Michael
Michael

Reputation: 327

How to retain context across an Ajax call

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.

Upvotes: 1

Views: 564

Answers (2)

Peter Bailey
Peter Bailey

Reputation: 105908

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
                    }
                });
            });
        }
    );
});

Upvotes: 3

just somebody
just somebody

Reputation: 19247

var self = this;
$.ajax({ ..., success: function (msg) { ... $('p.pClass1', self) ... } ...

Upvotes: 1

Related Questions