Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML table and external Php file that change value

I have table like this:

<table border="1">
	<tr align="left" valign="top">
		<th>ID</th>
		<th>NAME</th>
		<th>VALUE</th>
	</tr>
	<tr align="left" valign="top">
		<td>1</td>
		<td>Item 1</td>
		<td><button>-</button> 5 <button>+</button></td>
	</tr>
</table>

It is generated by Php and all information are from MySql DB.. I would like to activate buttons "-" and "+", so when I click minus, value 5 (in this case) will became 4 or when I click plus value 5 will became 6, and also in MySql DB some external php file will change values in real time..

I tried with some AJAX scripts, but I am stuck.. Please help.. Thanks..

like image 675
Aleksandar Avatar asked Mar 22 '26 05:03

Aleksandar


1 Answers

Try storing first the value in an HTML element like <span></span>, and assign class tag for the + and - button:

<table border="1">
  <tr align="left" valign="top">
    <th>ID</th>
    <th>NAME</th>
    <th>VALUE</th>
  </tr>
  <tr align="left" valign="top">
    <td>1</td>
    <td>Item 1</td>
    <td><button class="minus">-</button> <span>5</span> <button class="plus">+</button></td>
  </tr>
</table>

Then create the script:

$(document).ready(function(){

  $(document).on("click", ".minus", function(){ /* WHEN MINUS IS CLICKED */

    var elem = $(this); /* THE ELEMENT CLICKED */
    var id = elem.parent().siblings(":first").text(); /* ID OF THIS ROW IN THE DATABASE */
    var current_no = Number(elem.closest("td").find("span").html()); /* CURRENT VALUE OF THIS ROW */
    var new_no = current_no - 1; /* REDUCE ONE VALUE */
    elem.closest("td").find("span").html(new_no); /* REPLACE WITH THE NEW NUMBER INSIDE THE SPAN */
  });

  $(document).on("click", ".plus", function(){ /* WHEN PLUS IS CLICKED */
    var elem = $(this); /* THE ELEMENT CLICKED */
    var id = elem.parent().siblings(":first").text(); /* ID OF THIS ROW IN THE DATABASE */
    var current_no = Number(elem.closest("td").find("span").html()); /* CURRENT VALUE OF THIS ROW */
    var new_value = current_no + 1; /* ADD ONE VALUE */
    elem.closest("td").find("span").html(new_no); /* REPLACE WITH THE NEW NUMBER INSIDE THE SPAN */
  });

});

For updating the data in your MySQL database in real-time, you need to use AJAX.

$.ajax({ /* START AJAX */
  type: "POST", /* METHOD TO USE TO PASS THE DATA */
  url: "update.php", /* FILE DESTINATION OF THE DATA */
  data: {"id": id, "value": new_value} /* THE DATA TO BE PASSED ON */
}); /* END OF AJAX */

On the update.php file, it must contain the UPDATE query:

/*** YOUR ESTABLISHED CONNECTION HERE ***/
$stmt = $connection->prepare("UPDATE table SET value = ? WHERE id = ?");
$stmt->bind_param("ii", $_POST["value"], $_POST["id"]);
$stmt->execute();

Here is a jsfiddle (but without the AJAX).

like image 65
Logan Wayne Avatar answered Mar 23 '26 18:03

Logan Wayne