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.
receive.phpwith themessagevariable. Thereceive.phpscript gets the message and echos out "hello world" correctly which is why you see the alert box when you opensend.htmlin the browser and click on the button. However when you just openreceive.phpin the browser, the php file has no way of knowing the message variable as it is not set when you just "call" receive.php$messageto persist even when you directly call thereceive.phpfile. You want to store the string that you send to the php file in something called a session variable. So you should set up session variable like$_SESSION['message']=$message. This variable persists through out the session.The link should get you started in the right direction. Hope it helps.