Невозможно вызвать функцию с помощью кнопки onclick в данных таблицы jQuery ajax - PullRequest
0 голосов
/ 01 октября 2018

Я пытаюсь выполнить операцию удаления данных строки динамической таблицы.По какой-то причине, когда я нажимаю на кнопку удаления, функция удаления не вызывается!Есть ли проблема в этом коде, если да, пожалуйста, дайте мне знать.

Я все еще на начальном уровне.

data = "";

// to delete

delete_ = function(user_email) {
  alert("inside delete");
};

myfunction = function() {
  $(".tablecontainer").show();
  load();
};

load = function() {
  $.ajax({
    url: "updatedservicerequests",
    type: "POST",
    data: {},
    success: function(response) {
      alert(response.message);
      data = response.data;
      alert(response.data);
      $(".tr").remove();
      alert(response.data);
      $(function() {
        for (i = 0; i < response.data.length; i++) {
          $("#table").append("<tr> <td> " + response.data[i].user_email + " </td> <td> " + response.data[i].booking_number + " </td> <td> " + response.data[i].booking_address + " </td> <td> " + response.data[i].booking_date + " </td> <td> " + response.data[i].booking_message + " </td> <td> " + response.data[i].request_date + " </td> <td> " + response.data[i].chosen_emails_1 + " </td> <td> " + response.data[i].chosen_emails_2 + " </td> <td> " + response.data[i].chosen_emails_3 + " </td> <td> <button onclick='edit(" + response.data[i].user_email + ");'> Edit </button> <br>    <button onclick='delete_(" + response.data[i].user_email + ");'> Delete </button> </td> </tr>");
        }
      });
    },

    error: function(response) {
      alert("unable to pull up any service request");
    }
  });

  //to prevent (contact-submit) button from submitting form data since submit button has default action of submitting form

  $(document).ready(function() {
    $("#contact-submit").click(function(e) {
      return false;
    });
  });
};
<button onclick="myfunction();">Go</button>
<div class="tablecontainer" style="display: none;">
  th&gt;
  <table border="1" id="table">
    <tr>
      <th>booking_email</th>
      <th>booking_number</th>
      <th>booking_address</th>
      <th>booking_date</th>
      <th>booking_message</th>
      <th>when the request was made</th>
      <th>requested_tech_1</th>
      <th>requested_tech_2</th>
      <th>requested_tech_3</th>
      <th>operations</th>
    </tr>
  </table>
</div>

1 Ответ

0 голосов
/ 01 октября 2018

Ваша проблема имеет относительно простое решение.Я лично использую плагин jQuery для таблиц под названием DataTables found here

.Что касается вашего основного вопроса "Как удалить строку данных в таблице?"Это относительно просто.Поэтому вместо использования цикла for для итерации данных вы можете использовать jQuery .each, что тоже довольно просто.Я собираюсь показать вам этот метод здесь, и я могу добавить больше к моему ответу позже, если вы хотите увидеть версию DataTables.

# please note that I use ES6 syntax in JS.
# this: function() {...code here...}
# is the same as this: (()=> {...code here...});
# ES6 allows for shorthand annonymous functions

// wait for document to load
$(document).ready(()=> {
    // declare variable
    let foo = "hello world";
    // fetch data from the back end
    $.get("data.php?foo=" + encodeURIComponent(foo), (data)=> {
        # the $.get is the exact same as the AJAX code you used above but shorthanded
        // the 'data' is a parameter in the annonymous function that is storing the data from the back end
        console.log(data); // test that we are getting the data properly
        // remove table rows if they exist
        $("#mytable tbody").remove();
        $("#mytable").each(data, (i, item)=> {
            // add your data to the table by appending to the table
            # You would just continue this until you have all the cells you need filled. I'm going to skip to the end with adding the btn now
            $("#mytable").append('<tbody><tr><td>'+item.booking_email+'</td><td>'+item.booking_number+'</td><td><button class="btn btn-lg btn-danger deletebtn" id="'+item.booking_number+'">Delete</button></td></tbody>');
            /* the button has to have a unique ID to be called on so I assigned it the booking numbers to the ID. 
            Here's how we would call on it*/
            $(".deletebtn").unbind().click((d)=> {
                // you must unbind it first or you will have multiple events fire and you only want a single event to fire
                // pass the annonymous function a parameter (can be anything really I use d for delete)
                console.log(d.target.id); // check to make sure the button is getting an ID.
                // post to back end to delete then when it succeeds, we delete that row.
                $.post("data.php", {deletefoo: d.target.id}, (data)=> {
                    // delete row by calling on the target and removing the parent in this case being the row 'tr'
                    $(d.target).parents('tr').remove();
                });
            });
        });
        $("#mytable").show();
    });
});

Надеюсь, это поможет вашей проблеме.Дайте мне знать, если это помогает / работает для вас или нет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...