I am aware that my question has been asked many times here. I have already checked dozens of answers in the last few days but I still can't make it work.
I have a select list with options as you see below. Every time a new option is selected, I want to pass the value from my JavaScript variable to a PHP variable on the same page using AJAX without loading the page and echo my php variable after "you selected :"
Here is my code :
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<form method="post" action="">
<select name="country" id="country" class="form-control action">
<option value="UK">UK</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="Australia">Australia</option>
</select>
<br />
<p> you selected :
<?php
if( isset($_POST['myValue']) ){
echo $_POST['myValue'];
exit; }
?>
</p>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.action').change(function(){
if($(this).val() != '')
{
var selectedOption = $(this).val();
$.ajax({
type: 'post',
data: {myValue: selectedOption},
success: function(data){
console.log('country : ' + data);
}
});
}
});
});
</script>
when I check my console i see the result console.log('country : ' + data);
which means the data is passed to my variable. But the echo $_POST['myValue'];
doesn't show any result on my page.
Any ideas please why the echo is not shown on my page ? Thank you very much for your help.