简体   繁体   English

使用jquery和ajax访问同一页面上的php值

[英]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 . 我试图回显用户使用jquery和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脚本是:

<?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. 该代码警告成功提示,但是我无法使用GET访问该值,这是我做错任何事情的指针。

If you are doing this on same page add your php script at the top of the page that handle your ajax request 如果您在同一页面上执行此操作,请在页面顶部添加用于处理ajax请求的php脚本

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 如果使用ajax,请遵循以下代码

<!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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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