Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax - Update database on button click

I need some help with a project. I'm still learning javascript and jquery so bear with me. The website that I'm working on needs to update a database entry when a button is clicked, the button content is also queried from the database.

First database query to get the buttons:

<?php
    $freq_sql = "SELECT freq FROM disc_freq WHERE in_use='0'";
    $result_freq = $connection->query($freq_sql);
    echo "<h5>Available frequencies</h5>";
    while($row = mysqli_fetch_array($result_freq)){
        $set_freq=$row[0];
?>
<a id='button' class='w3-bar-item w3-button'><?php echo $set_freq ?></a>

Then the ajax script I tried but there is something wrong with it

$(document).ready(function(){
    $("#button").click(function(){
        $.ajax({
            url: "set_freq.php",
            type: "POST",
            data: {"set_freq":<?php echo $set_freq ?>}, 
            success: function(data){
                data = JSON.toString(data);

            }
        });
    });
});

Finally the php file

<?php
session_start();
include("konf.php");  
if(isSet($_POST['set_freq'])){ 
    $update_sql="UPDATE disc_freq SET in_use = '1', working_usr='".$_SESSION['username']."' WHERE freq='".$_POST['ins_freq']."'";
    $update_run=mysqli_query($connection,$update_sql);  
}  
?>

For some the first button when clicked on initiates same number ajax calls of how many buttons have been displayed. Others won't do anything.

The php code does work but the only problem is the ajax call and I haven't found a solution yet so any help is appreciated.

like image 758
Michael Avatar asked Aug 23 '26 02:08

Michael


1 Answers

please update code as in your code there is error in ajax script in js change you can change code from

  data: {"set_freq":<?php echo $set_freq ?>},

to

   data: {"set_freq":'<?php echo $set_freq ?>'},
like image 163
Pritamkumar Avatar answered Aug 24 '26 14:08

Pritamkumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!