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.
$_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 https://www.php.net/isset
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With