简体   繁体   中英

Access the php value on the same page using jquery and ajax

i am trying to echo the value entered by the user in the input tag using jquery and ajax . the following is my code

 < script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script> < script type = "text/JavaScript" > function showMessage() { var message = document.getElementById("message").value; $.ajax({ url: 'value_pass.php', type: 'GET', data: { var_PHP_data: message }, success: function(data) { alert("success"); }, error: function(XMLHttpRequest, textStatus, errorThrown) { //case error } }); } < /script> 
 <!DOCTYPE html> <html> <head> </head> <body> Enter message: <input type="text" id="message"> <input type="submit" onclick="showMessage()" value="submit" /> <?php echo "hi".$_GET['var_PHP_data'];?> </body> </html> 

My php script is:

<?php 
echo "hi".$_GET['var_PHP_data'];
?>

the code alert the success prompt , but i am not able to access the value using GET , any pointers on what i am doing wrong.

If you are doing this on same page add your php script at the top of the page that handle your ajax request

Like this

<?php if(isset($_GET['var_PHP_data'])){
  echo "hi".$_GET['var_PHP_data'];
  die;
}?>

<!-- rest of your html code start from here -->
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  Enter message: <input type="text" id="message">
  <input type="submit" onclick="showMessage()" value="submit" />
</body>

</html>

If you using ajax, follow below code

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  Enter message: <input type="text" id="message">
  <input type="submit" onclick="showMessage()" value="submit" />
 <span id = 'PHP_data'></span>
</body>

</html>


<script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script>
  <script type = "text/JavaScript" >
  function showMessage() {
    var message = document.getElementById("message").value;
    $.ajax({
      url: 'value_pass.php',
      type: 'GET',
      data: {
        var_PHP_data: message
      },
      success: function(data) {
      message1 = "Hi "+message
       $('#PHP_data').html(message1);
        alert("success");
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        //case error
      }
    });

  } 
  </script>

If you are using form submit use below code

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method ='GET'>
  Enter message: <input type="text" id="message" name = "message">
  <input type="submit" value="submit" />
 <?php if(isset($_GET['message'])){
 echo "hi".$_GET['message'];
  die;
} ?>
 </form>
</body>

</html>

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