Cookie Ninja
Cookie Ninja

Reputation: 1182

Update specific list <li> using ajax after pressing the button of the specific list

How to update a specific list <li> using ajax after the success method.

Here's the simple <li> structure with <div> containing text:

<ul>
  <li>
    <div>List1</div>
    <input class="update" type="submit" name="update" value="Update">
  </li>
  <li>
    <div>List2</div>
    <input class="update" type="submit" name="update" value="Update">
  </li>
</ul>

And here's a simple javascript with ajax:

$(function() {
  $(".update").click(function() {
    var data = "List updated";

    $.ajax({
      method: "POST",
      url: "update_list.php"
      data: data,
      cache: false,
      success: function() {
        // update the specific list
      }
    })
  })
})

Assuming that the data, which is a string, sends to the php file, updates the database, then sends back the string to update a specific list after click the update button of the specific list. Lets say the first list will be updated. How can I update the specific list after a click the update button of a specific list?

Upvotes: 0

Views: 1106

Answers (2)

Robert
Robert

Reputation: 21388

Since you're using jQuery it's .siblings() selector.

$(function() {
  $(".update").click(function() {
    let data = "List updated";
    let sibling = $(this).siblings();

    $.ajax({
      method: "POST",
      url: "update_list.php"
      data: data,
      cache: false,
      success: function() {
        sibling.text("Whatever");
      }
    })
  })
})

https://jsfiddle.net/309q5852/

Upvotes: 2

slider
slider

Reputation: 12990

Refer to this question: Getting the ID of the element that fired an event

What you want is to get the current clicked element's parent 'li', and then find the div inside it. So something like the following:

$(function() {
  $(".update").click(function() {
    var data = "List updated";
    var parentlistElement = $(this).parent(); // points to li

    $.ajax({
      method: "POST",
      url: "update_list.php"
      data: data,
      cache: false,
      success: function(response) {
        // update the specific list item
        parentListElement.find('div').text(response);
      }
    })
  })
})

Upvotes: 1

Related Questions