htmljqueryajaxhtml-table

Change a specific row data of a HTML table as well as database using AJAX call


I have a database table like this -

    -----------------------------------|
    ID         |    Name  |   Status   |
    -----------------------------------|
    101             John        0      |
                                       |
    102             Robert      1      |
                                       |
    103             David       0      |
    -----------------------------------|

By featching this database I am creating a html table (shown below) in which each row has a button to change its current status in the table and also in the backend database. i.e. 0 becomes 1 and 1 becomes 0.

<table>
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Status</th>
    <th>Action</th>
  </tr>
  <tr>
    <td>101</td>
    <td> John </td>
    <td> 0 </td>
    <td><button>Change Status</button> </td>
  </tr>
  <tr>
    <td>102</td>
    <td> Robert </td>
    <td> 1 </td>
    <td><button>Change Status</button> </td>
  </tr>
  <tr>
    <td>103</td>
    <td> David </td>
    <td> 0 </td>
    <td><button>Change Status</button></td>
  </tr>
</table>

This should be done without refreshing the page. So I think I should make an AJAX call to the server with the ID and the status of that ID. But I don't understand how to do it.


Solution

  • First add a data attribute on the button tag and output the ID in its value, and create another data attribute for current status, so that button tag looks something like this:

    <button data-id="5" data-status="0">Change Status</button>
    

    Then use jQuery's ajax method to send Ajax call to server, something like below:

    $("button").click(function(e){
        e.preventDefault();
        data = {row_id: $(this).data('id'), current_status: $(this).data('status')};
        $.ajax({
            type : "post",
            data: data,
            url: "URL_TO_SERVER_FILE_WHICH_WILL_HANDLE DATA",
            success: function(result){
                // show message here and also change current status on data 
                // attribute of button and in the status column of table
    
            }
        });
    });