简体   繁体   中英

call value of a variable from php page by ajax

I am new to javascript and I've searched this question everywhere but no suitable answer. I have a "code.php" page as

$query = "SELECT * FROM users WHERE id=1";
$result= mysqli_query($con,$query);
$row=mysqli_fetch_array($result);
echo $row[1];

On the other side in "index.php" i have

<h1>"the value for number is: " <span id="myText"></span></h1>

function myFunction() {
   document.getElementById("myText").innerHTML = $row[1];
}

I want to load the value of $row[1] from code.php to index.php .

I know that i have to use ajax but how?

In index php use ajax to get data from code php. this is example :

<script>
  $.ajax({
    url: 'code.php',
    type:'get',
    success:function(data){
      $("#myText").html(data);
    }
  });
</script>
<script>  
 $(document).ready(function(){  

    $.ajax({
        type:'get',
        url:'code.php',
        success:function(response){
    // ajax will assign the result of code =,php into response
      document.getElementById("myText").innerHTML = response; //response;
        }
      });
});


 </script>

Place this at header of your index.php

You can find more tutorials on line to get more understanding of ajax

dont forget to download jquery and embed it your code https://jquery.com/download/

Or u can copy this <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM