0

I am trying to pass a variable from jQuery to a PHP file and I am having a difficulty in doing it.

Here is a simple HTML file of "send.html".

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
      $.ajax({
        type: 'post',
        url: 'receive.php',
        data: {message : "Hello World!"}
      })
      .done(function(data) {
          alert(data);
      });
    });
  });
</script>
</head>
<body>
  <button>Click here</button>
</body>
</html>

And I have a PHP file of "receive.php".

<?php
  session_start();

  if(isset($_POST['message'])){
    $_SESSION['message'] = $_POST['message'];
    echo $_SESSION['message'].'<br />';
  } else {
    echo "message not set";
  }
?>

When I click the button on send.html, I get the correct alert saying "Hello World!". But when I access "receive.php" by typing the URL on my webbrowser, I get the message saying:

message not set

If I want to get "Hello World!" from receive.php, what should I do? Anybody has a solution to this problem?

Thanks.

1
  • that is because you are checking if(isset($_POST['message'])){ and not if(isset($_SESSION['message'])){ for direct view you should check for session. There is no POST when you are viewing receive.php directly. Commented Jan 27, 2014 at 12:39

1 Answer 1

5

your receive.php should be

<?php
  session_start();

  if(isset($_POST['message'])){
    $_SESSION['message'] = $_POST['message'];
    echo $_SESSION['message'].'<br />';
  }else if(isset($_SESSION['message'])){
     echo $_SESSION['message'].'<br />';
  }else{
     echo "message not set";
  }
?>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.