skip to Main Content

I have an html button which call a php function on click , and this function change the value of a variable , and beside the button i have a text which display the value of this variable , my question is how can i change immediatly the value and be displayed in the html page ( for example i have the current value ‘9’ , but when i click on button i want it to be ‘voila’ as done in function ) , i’ve read that i can do it with AJAX but i dont 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";
        }
 ?>

2

Answers


  1. 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();
        }
    
    Login or Signup to reply.
  2. function generer(){ $("#gen_value").html("voila"); }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button type="button" class="btn btn-success" onClick="generer()">Generate</button>
    <a href="#" id="gen_value" class="list-group-item disabled">9</a>

    >

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search