Rom Almazan Tacmoy
Rom Almazan Tacmoy

Reputation: 19

How to UPDATE database table using button with AJAX jQuery?

I have 2 textbox the firstName and lastName. The problem is when I click another textbox which is the lastName the alert message popup and when I click OK, alert message show again and again. I need to refresh my browser to remove the alert message. I want to update my information using button. When I click the update button the alert message will show and when I click OK my table will be updated and alert message will be vanish. Can somebody help me regarding to my problem?

function edit_data(id, text, column_name){
  $.ajax({
    url:"edit.php",
    method:"POST",
    data:{id:id, text:text, column_name:column_name},
    dataType:"text",
    success:function(data){
      alert(data);
    }
  });
}

$(document).on('blur', '.first_name', function(){
  var id = $(this).data("id1");
  var first_name = $(this).text();
  edit_data(id, first_name, "FirstName");
});

$(document).on('blur', '.last_name', function(){
  var id = $(this).data("id2");
  var last_name = $(this).text();
  edit_data(id,last_name, "LastName");
});

$(document).on('click', '.btn_update', function(){
  var id=$(this).data("id10");
  if(confirm("Are you sure you want to update this?")){
    $.ajax({
      url:"update.php",
      method:"POST",
      data:{id:id},
      dataType:"text",
      success:function(data){
        alert(data);
        fetch_data();
      }
    });
  }
});

Upvotes: 0

Views: 2591

Answers (1)

Twisty
Twisty

Reputation: 30893

Consider the following code.

function editData(i, t, c) {
  if (i === undefined || t === undefined || c === undefined) {
    return false;
  }
  $.ajax({
    url: "edit.php",
    method: "POST",
    data: {
      id: i,
      text: t,
      column_name: c
    },
    dataType: "text",
    success: function(d) {
      console.log("Success:", d);
    },
    error: function(xhr, txt, err) {
      console.log("AJAX Error: ", xhr, txt, err);
    }
  });
}

function updateData(i) {
  if (i === undefined) {
    return false;
  }
  var $items = $("tr[data-row-id='" + i + "'] input");
  var myData = {
    id: i
  };
  $item.each(function(ind, el) {
    myData[$(el).attr("class")] = $(el).val();
  });
  $.ajax({
    url: "update.php",
    method: "POST",
    data: myData,
    dataType: "text",
    success: function(d) {
      console.log("Success:", d);
      fetch_data();
    },
    error: function(xhr, txt, err) {
      console.log("AJAX Error: ", xhr, txt, err);
    }
  });
}

$(function() {
  var $dt = $("#data-table");

  $dt.on('blur', 'input', function(e) {
    editData($(this).parent().parent().data("row-id"), $(this).val(), $(this).attr("class"));
  });

  $dt.on('click', '.btn_update', function(e) {
    e.preventDefault();
    if (confirm("Are you sure you want to update this?")) {
      updateData($(this).parent().parent().data("row-id"));
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="data-table">
  <thead>
    <tr>
      <th>First Name</th>
      <th colspan="2">Last Name</th>
    </tr>
  </thead>
  <tr data-row-id="1001">
    <td><input type="text" class="firstName" value="Homer" /></td>
    <td><input type="text" class="lastName" value="Simpson" />
    </td>
    <td><button class="btnUpdate">Update</button></td>
</table>

This may help you streamline your code. It was not clear what your Update Button was going to do, and since I do not know what your PHP scripts are doing, it's hard to anticipate what you are trying to accomplish.

Since you did not provide a MCVE, I was unable to test the code for proper functionality. But using console can allow you a lot more detail without disrupting the User interaction. An alert box requires clicking the Button to proceed which can alter the interactions.

You do not have to use a <table>, a parent <div> can also work, but it's helpful to have something that can be a container for the data that is associated with the id. I assigned the id to each row to make it easier to address. I assume your Database table holds data like so:

+---------------------------+
| ID | firstName | lastName |
+---------------------------+
|  1 | Homer     | Simpson  |
|  2 | Marge     | Simpson  |
| 99 | Moe       | Szyslak  |
+---------------------------+

Therefore, it does not make sense to retain the ID in each <input> if possible. It's really up to you, since it's not clear what the HTML looks like, again if you provide a more complete example, people can help further.

I also suspect you'd need to update your update.php to handle the new stream of data.

update.php

<?php
$cn = array();
foreach($_POST as $k => $v){
  if($k == 'id'){
    continue;
  }
  array_push($cn, $k);
}
include_once 'mysqli_connect.php';
$id = $mysqli->real_escape_string($_POST['id']);
$sql = "UPDATE table_name SET ";
foreach($cn as $col){
  $val = $mysqli->real_escape_string($_POST[$col]);
  $sql .= "$col = '$val',";
}
$sql = substr($sql, 0, -1) . " WHERE id = $id;";
// Execute SQL Query
?>

This will update each column for the row with whatever data was sent in. You may also consider making use of JSON to pass the data to PHP.

Upvotes: 1

Related Questions