将变量从HTML文件中的jQuery传递到php文件

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!",
        },
        success: function(data) {
          //console.log(data);
          alert(data);
        }
      });
    });
  });
</script>
</head>
<body>
<button>Click here</button>
</body>
</html>

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

<?php
  $message = $_POST['message'];
  echo $message.'<br />';
?>

When I click the button on send.html, I get the correct alert saying "Hello World!". But when I call the receive.php file, I get the following error message saying:

Notice: Undefined index: message in receive.php on line 3

Does anyone know the solution to this problem?

Thanks.

Remove , at the end of value in data parameter of jquery

$(document).ready(function(){
    $("button").click(function(){
      $.ajax({
        type: 'post',
        url: 'receive.php',
        data: {message : "Hello World!"},
        success: function(data) {
          //console.log(data);
          alert(data);
        }
      });
    });
  });

$_POST['message'] this will work in your receive.php only when you go to your php file by clicking the submit button as you have used ajax for calling your php file. But if you will call receive.php file without clicking submit button it will give error as nothing is posted on your php file. So for avoiding this error use isset() function:

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

For more Details on isset() see http://in3.php.net/isset

The ajax request should be like:

$.ajax({
  type: "POST",
  url: "receive.php",
  data: { message: "Hello World"}
 })
.done(function(data) {
  alert(data);
 })

Try to use the done construct instead of success as it is deprecated now. As far as the receive.php file is concerned, make sure the path is set correctly in the url parameter and best practice should be in the receive.php file:

<?php
  $message = "NULL";
  if(isset($_POST['message']))
      $message = $_POST['message'];
  echo $message.'<br />'; 
?>

This way you won't get a Undefined index message error when you run pull up receive.php file and would also help you debug it to some extent. Hope it helps.