Different Actions For Each Button Using Ajax
Solution 1:
You can't have three buttons for a single form. Simply create three buttons that will have unique class names, in addition to a synonymous class that you can reference on button click. Then reference the click handler for that synonymous class (rather than the form submission):
HTML:
<form method="post" id="form_shirt" enctype="multipart/form-data">
  ID:
  <br>
  <input type="hidden" name="id_shirt" id="id_shirt" class="form-control"> Name:
  <br>
  <input type="text" name="name_shirt" id="name_shirt" class="form-control" required="required"> Price:
  <br>
  <input type="text" name="price_shirt" id="price_shirt" class="form-control" required="required">
  <button name="btninsert" id="btninsert" value="Insert" class="submit insert_shirts btn btn-success" />
  <button name="btnupdate" id="btnupdate" value="Update" class="submit update_shirts btn btn-warning" />
  <button name="btndelete" id="btndelete" value="Delete" class="submit delete_shirts btn btn-danger" />
</form>
JavaScript:
$(document).ready(function() {
  $('.submit').on("click", function() {
    $.ajax({
      url: this.classList[1] + ".php",
      method: "POST",
      data: new FormData(this),
      contentType: false,
      cache: false,
      processData: false,
      success: function(data) {
        $('#form_playera')[0].reset();
        $('#table_playeras').html(data);
      }
    });
  });
});
Note that you can have the three separate functions in one $(document).ready(), and the three functions can all be combined into one, sending different url parameters to AJAX by using this.classList: url: this.classList[1] + ".php". The 1 denotes the second class of each element (insert_shirts, update_shirts and delete_shirts respectively).
Also note that you won't need event.preventDefault(), as you're no longer targeting the form submission.
Hope this helps! :)
Post a Comment for "Different Actions For Each Button Using Ajax"