1

I'm trying to update the class of the object in the DOM that was clicked using data passed back from my api. User clicks a link in a bootstrap dropdown which passes some data to an api, and is returned the updated status which I want to use to update the css (and eventually the text) in the button. I can manipulate the DOM just after the click, but inside the done function, nothing happens. I know in other cases I've passed data with 'use', but I can't seem to do that in this case.

$(".status-item").click(function(){
  $.post( "/api/orderstatus/{{$order->id}}", { status_id: 1 })
  .done(function( data ) {
    $(this).parent().parent().addClass('noticeme');
  });
});

<div class="btn-group float-end">
  <button type="button" class="btn btn-primary">Picked-up</button>
  <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false"><i class="mdi mdi-chevron-down"></i></button>
  <div class="dropdown-menu" style="">
    <a class="dropdown-item status-item text-primary" href="#" data-id="1">Picked-up</a>
    <a class="dropdown-item status-item text-info" href="#" data-id="2">Laundered</a>
  </div>
</div>
Dylan Glockler
  • 1,115
  • 1
  • 20
  • 40
  • 1
    from my experience, don't use `this` inside `done` function. it actually refers to a different object inside `.done()`. Rather directly use the ID of the element. Also, have a look at [this post](https://stackoverflow.com/questions/6394812/this-inside-of-ajax-success-not-working) – TBA Nov 06 '21 at 04:24

1 Answers1

0

Thanks TBA, I knew that 'this' was contextual, just couldn't figure out how to get access to the 'this' I needed (being the clicked element in the DOM). Using TBAs link and suggestion (THANKS!) here's what I've gone with. Setting a var as btn, then moving up two parents to the btn-group so that I can manipulate the content of the button (colors and text) after the status object is returned from the server.

    $(".status-item").click(function(){
        var btn = $(this).parent().parent();
        $.ajax({
          method: "POST",
          url: "/api/orderstatus/{{$order->id}}",
          data: { status_id: $(this).data("id") }
        })
          .done(function( status ) {
            // alert( "Returned: " + status.name );
            @foreach($statuses as $status)
                btn.children('button').removeClass('btn-{{$status->display}}');
              @endforeach
            btn.children('button').addClass('btn-'+status.display);
            btn.children('button').first().text(status.name);
          });
    });
Dylan Glockler
  • 1,115
  • 1
  • 20
  • 40