0

I am trying to load some content via ajax into a div that has been previously loaded using another ajax function and I am having a really hard time putting the data into the div. Either, they are all loaded with the same content or nothing at all. I am sure it is something really simple that I am missing - any help will be greatly appreciated.

Ajax function:

$(document).on('click', '.btn.btn-clearview.loadSubresults', function () {
$.ajax({
   type: "POST",
   url: "loadData.php",
   data: $(this.form).serialize(), // serializes the form's elements.
   dataType: 'json',
   success: function(data)
   {
       console.log(data);
       $(this).closest('.wrapper').children('.resultExpander').html(data); // Should be doing something but nothing is happening (OPTION 1)
       //$('.resultExpander').html(data); // Load the response from the PHP into the HTML (OPTION 2)
   },
      error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
      }
 });

How this all pulls together:

User loads the main results page --> clicks the search button and loads the results via ajax. This result has a div with class "result" and there are multiple instances of this div.

From what I understand, using the traversing rules (https://learn.jquery.com/using-jquery-core/traversing/) I can target the required div even though the same class name is used throughout.

Error messages / information from the console on Firefox

none -- just does not load if I use option 1

Thanks.

alpharomeo
  • 418
  • 5
  • 13
  • you can't use `$(this)` inside ajax success to access `.btn.btn-clearview.loadSubresults`. Before ajax assign it into variable like `$_this=$(this);` then call it inside success `$_this.closest('.wrapper').children('.resultExpander').html(data);` – Ravisha Hesh May 16 '16 at 15:57
  • @RavishaHesh Yeah, I think you got it. Please add this as an answer so OP can checkmark it if it solves the problem. – cssyphus May 16 '16 at 16:03
  • @Ravisha: That seemed to do the trick! Thanks for your help. I know you said I can't use $(this) inside the success code ... can I ask why this was the case please? – alpharomeo May 16 '16 at 16:23

1 Answers1

1
$(document).on('click', '.btn.btn-clearview.loadSubresults', function () {
  $_this = $(this);
  $.ajax({
    type: "POST",
    url: "loadData.php",
    data: $(this.form).serialize(), // serializes the form's elements.
    dataType: 'json',
    success: function(data)
    {
      $_this.closest('.wrapper').children('.resultExpander').html(data);
    },
    error: function (xhr, ajaxOptions, thrownError) {
      alert(xhr.status);
      alert(thrownError);
    }
  });
});

Assign $(this) into variable before ajax then call through that inside success

Ravisha Hesh
  • 1,504
  • 13
  • 19