phphtmljqueryajax

Change input value on button click with PHP


I have an html button which calls a PHP function on click, and this function changes the value of a variable, and beside the button I have a text which displays the value of this variable. My question is how can I change immediately the value and be displayed in the html page (for example I have the current value '9', but when I click on the button, I want it to be 'voila' as done in function)? I've read that I can do it with AJAX but I don't know how exactly, any help will be appreciated.

The Button

<button type="button" class="btn btn-success" onClick="generer()">Generate</button>

The display input

<a href="#" class="list-group-item disabled"><?php echo $password; ?></a>

The PHP code

<?php
 $password = "9";
 function generer(){
           $password = "voila";
        }
 ?>

Solution

  • You can not call a php function from html. You will need javascript for that.

    There are 2 possible solutions -

    1. Write your function in js like

     function generer(){
               document.getElementById("generated").innerHTML = "voila";
            }
    <button type="button" class="btn btn-success" onClick="generer()">Generate</button>
    
    <a href="#" id="generated" class="list-group-item disabled">9</a>

    1. If you must handle something on the server with php. You will need to make a separate php script where you will generate the value and return it, then make an AJAX request(as you mentioned) again via JS to retrieve that value and change html. Like this

    assuming you created generator.php file and put your generation logic in it, this will be your js function

        function generer() {
           var xmlhttp = new XMLHttpRequest();
           xmlhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200) {
                 document.getElementById("generated").innerHTML = this.responseText;
             }
           };
           xmlhttp.open("GET", "generator.php", true);
           xmlhttp.send();
        }