0

Below is the code I am working with, my goal is whenever the user clicks the button with a class name '.view_all'. I want to use the data that is returned using ajax and put it inside this line $(this).parent('div').siblings('.body_wrap').html(data); I have tried the code below but it is not working.

$('.view_all').click(function (event) {
     $.ajax({
         type: 'POST',
         url: 'ajax/return_data.php'
     }).success(function (data) {
         $(this).parent('div').siblings('.body_wrap').html(data);
     });

 });
PSL
  • 123,204
  • 21
  • 253
  • 243
user2310422
  • 555
  • 3
  • 9
  • 22
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Barmar Oct 06 '13 at 01:55
  • 2
    Your question title and the content conflicts... – PSL Oct 06 '13 at 02:08
  • 1
    Note that using `.success()` was deprecated in v1.8: using `.done()` is now the recommended method. – nnnnnn Oct 06 '13 at 02:36
  • @user2310422 Did the solution mentioned below work for you? – PSL Oct 06 '13 at 18:49

1 Answers1

2

this is your issue, this inside the ajax success callback is not the DOM element as you thought, it is jqXHR object instead. There are many ways to get around this, simplest way is to just cache $(this) externally and use it inside the callback. try:

$('.view_all').click(function (event) {
    var $this = $(this); //Cache it here
     $.ajax({
         type: 'POST',
         url: 'ajax/return_data.php'
     }).success(function (data) {
          $this.parent('div').siblings('.body_wrap').html(data); //use it
     });

 });

Another way is to set the context property of ajax settings.

$('.view_all').click(function (event) {
     $.ajax({
         context:this, //set up context
         type: 'POST',
         url: 'ajax/return_data.php'
     }).success(function (data) {
          $(this).parent('div').siblings('.body_wrap').html(data); //Now 
     });
 });
PSL
  • 123,204
  • 21
  • 253
  • 243