Junjie Zhang
Junjie Zhang

Reputation: 133

JQuery POST data to php, direct to php, data not exist anymore in php

I passed along data via POST to php using JQuery, but when the page direct to the php file, the POST["createVal"] in php doesn't seem to exit after the call back. I showed this in demo below, notice that the $name is undefined when the callback result is clicked. Any idea how to fix this?

I'm trying to make a function that when the returned result was clicked, html page could redirect to the php page in which user input in html file could be printed out.

HTML file

 <html>
    <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

</head>
<body>
<input type="text" id="userinput">
    <div id="result">
    </div>
</body>

<script>
    $("input").keyup(function(){
        var input=$("input").val();
        $.post("process.php",{createVal:input},function(data){
            $("#result").html("<a href='process.php'>"+data+"</a>");
        })
    })
</script>
</html>

php file(process.php)

<?php
if(isset($_POST["createVal"])){
    $name=$_POST["createVal"];
    echo $name;     
}
?>

<?php
    echo $name;
?>

Upvotes: 0

Views: 109

Answers (2)

Sami Ahmed Siddiqui
Sami Ahmed Siddiqui

Reputation: 2386

Use this Html Code:

<html>
<head>
    <script type="text/javascript"   src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
  </head>
 <body>
<input type="text" id="userinput">
   <div id="result"> </div>
 </body>

<script>
$("input").keyup(function(){ 
    var input=$("input").val();
    $.ajax({
        type: "POST",
        url: "http://localhost/stackoverflow/process.php",
        data: {'createVal': input},
        success: function(data){
            $("#result").html("<a href='http://localhost/stackoverflow/process.php?createVal="+data+"'>"+data+"</a>");
        }
    });
});
</script>
 </html>

PHP Code:

<?php
 if(!empty($_REQUEST['createVal']) || !empty($_GET['createVal'])){
  $name = $_REQUEST['createVal'];
  echo $name;     
 }elseif(!empty($_GET['createVal'])){
  $name = $_GET['createVal'];
  echo $name;  
 }
 return 1;
?>

I have run and checked this too.

localhost: if you are running this code on localhost

stackoverflow: is the folder name, if you have any folder in localhost for it so replace the name by this.

Upvotes: 1

Ram Sharma
Ram Sharma

Reputation: 8819

change

$("#result").html("<a href='process.php'>"+data+"</a>");

to

$("#result").html("<a href='process.php?createVal="+data+"'>"+data+"</a>");

and

process.php

if(isset($_REQUEST["createVal"])){
    $name=$_REQUEST["createVal"];
    echo $name;     
}

Upvotes: 1

Related Questions