简体   繁体   中英

Passing variable from ajax to php and it is not being passed

I want to pass a variable value to php on same page using onClick

I have been searching google for days and trying all the examples and can't get anything to work

<!doctype html>
<?php

if(isset($_POST['name']))
{
    echo $YourName= $_POST['name'];
}

?>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">

    </script>
</head>
<body>
<script type="text/javascript">
 function msg(){

      var name = "JR"; 

    $.ajax({
      type: 'POST',
      data:  {name : name},
      cache: false,
      async:false,
      success: function(data){
        $('#results').html(data);
      }
    })
 }
    msg(); 
</script>
<button type="button" onClick="msg();">Click Me!</button>
</body>
</html>

should pass value to the php part of the page

Add the url in ajax of same page.

If it's in same page, after getting the response use die. otherwise you will get complete HTML code in response. and it should be on top of page.

example.php file will be like.

  <?php
if(isset($_POST['name']))
{
    echo $YourName= $_POST['name'];
    die;
}
?>
<!-- now start html code -->
<!doctype html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
 function msg(){
    var name = "JR"; 
    $.ajax({
      type: 'POST',
      url:'example.php',  //Add the url of same page
      data:  {name : name},
      cache: false,
      async:false,
      success: function(data){
        $('#results').html(data);
      }
    })
 }


</script>
<div id="results"></div>
<button type="button" onClick="msg();">Click Me!</button>
</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