Pavlov Propagandalf
Pavlov Propagandalf

Reputation: 9

How would I POST from HTML using a button not a form for a MySQL database?

I posed a question previously but I think in the wrong way.

Currently I have a form submit that works to post "toggle_LED" but I want to avoid a form and only use a button to post from my HTML or PHP if possible? As I have a setup that checks for the post of "toggle_LED" for both a readout of what state the LED is in and another that switches the LED if the MySQL database is updated via a POST.

This is one place I want to use it for a little ESP_8266 project.

if (isset($_POST['toggle_LED'])) {
    $sql = "SELECT * FROM LED_status;";
    $result   = mysqli_query($conn, $sql);
    $row  = mysqli_fetch_assoc($result);
    
    if($row['status'] == 1){
        $update = mysqli_query($conn, "UPDATE LED_status SET status = 0 WHERE id = 1;");        
    }       
    else{
        $update = mysqli_query($conn, "UPDATE LED_status SET status = 1 WHERE id = 1;");        
    }
}

Upvotes: 0

Views: 191

Answers (1)

Professor Abronsius
Professor Abronsius

Reputation: 33823

If you assign a dataset attribute to your button you can easily toggle the value between 0 and 1 with a very simple piece of algebra - such as state = 1 - state

With that modified status value then send an ajax request to your php script to update the db.

<?php

    $sql = "SELECT * FROM LED_status;";
    $result   = mysqli_query($conn, $sql);
    $row  = mysqli_fetch_assoc($result);
    
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['status'], $_POST['task'] ) ){
        ob_clean();
        if( $_POST['task']=='toggle_led' ){
            
            if( intval( $row['status'] ) == 1){
                $update = mysqli_query($conn, "UPDATE LED_status SET status = 0 WHERE id = 1;");        
            }else{
                $update = mysqli_query($conn, "UPDATE LED_status SET status = 1 WHERE id = 1;");        
            }
            
            exit( 'Database updated - status=' . $_POST['status'] );
        }
        
        exit();
    }
?>

<input type='button' name='toggle' value='Toggle LED' data-state=1 />

<script>
    let fd=new FormData();
    let bttn=document.querySelector('input[type="button"][name="toggle"]');
        bttn.addEventListener('click',function(e){
            this.dataset.state = 1 - this.dataset.state;
            
            fd.set('status', this.dataset.state );
            fd.set('task', 'toggle_led');   // <---------- removed space!!!
            
            fetch( location.href, { method:'post', body:fd })
                .then(r=>r.text())
                .then(text=>alert(text))
            
            
        });
</script>

An alternative might be to do that same algebra in the database and not worry about the variable being sent.

ie:

$sql='UPDATE `LED_status` SET `status` = 1 - `status` WHERE `id` = 1';

Upvotes: 2

Related Questions