send data on button click from javascript to database

喜夏-厌秋 提交于 2019-11-29 16:55:50

First of all you have to add an ID to every TD on your table, i.e. Seat ID, For example:

echo "<td id='Seat_A' data-seat='". $row['id'] ."'class='count'>" . $row['Seat'] . "</td>";

Then send this ID to your PHP script with Ajax:

$("td #Seat_A").click(function(){
    var seat_number = $(this).data("seat");

    $.ajax({
        type: 'POST',
        url: "/take_a_seat.php",
        data: 'seat_number='+seat_number,
        success: function(data){
            $(this).css("background", "red");
        }
        dataType: "json"
    });
});

On the PHP script you have to do what you want to the seat with this ID and return true or false as a result. Let's suppose you have a field named reserved in your database table. You can get the unique ID and update that row to reserved = 1 for example.

Try this easy to use ajax script to accomplish your task

Features: you can show an gif img before send data to db in beforeSend section
get response from php file in success section
hide img after data inset in db in complete section and show successful or not success msg

var myVar = 'your desire data you want to send to db';
$.ajax({           
            type: "POST",  
            url:"scripts/dummy.php",  
            data:"myVar="+myVar,

            beforeSend: function()
            {                   

            },
            success: function(resp)
            {               

            }, 

            complete: function()
            {

            },

            error: function(e)
            {  
            alert('Error: ' + e);  
            }  

    }); //end Ajax

Javascript is client side. Your database is server side.. So you have to use php to change your database entries.

In short, if you want to execute PHP stuff without reloading page, than use AJAX. You can use it with your favorite JQuery.

This is an overview. For existing records you should some thing like this

  <?php
  $count=1;
  $res = mysql_query("SELECT * FROM Seating_para_20 Where Seat > '10'");
  while($row = mysql_fetch_array($sql)) {

    if($row['status']==1) {
      $tdcolor = 'red';
    } else {
       $tdcolor = 'blue';

    }
    ?>

    <td id="td-<?php echo $count;?>" sytle="background-color:<?php echo $tdcolor; ?>" onclick="reserveseat(<?php echo $count; ?>);" >
    <?php
    $count++;
  }
  ?>

For changing after page load you will do ajax operation

 <script type="text/javascript" language="javascript">
 function reserveseat(count) {
   $.ajax({
    type: 'POST',
    url: "bookseat.php",
    data: '',
    success: function(data){
        $("#td-"+count).css("background-color", "red");
    }

   });
 }

 </script>

In bookseat.php you will change the status ... :-) Read about ajax from here . :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!