0

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?

Cookie Ninja
  • 1,156
  • 15
  • 29

2 Answers2

2

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/

Robert
  • 21,110
  • 9
  • 55
  • 65
1

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);
      }
    })
  })
})
Community
  • 1
  • 1
slider
  • 12,810
  • 1
  • 26
  • 42
  • @Zange-chan it would be `$(this).parent().parent()`, where `$(this)` gets the `input` element. Check out https://api.jquery.com/parent/ – slider Jun 12 '16 at 03:06