HTML
<form method="post">
<select name="MySelect" onchange="run(this)">
<option value="year 1">year 1</option>
<option value="year 2">year 2</option>
<option value="year 3">year 3</option>
</select>
</form>
I am trying to get the selected option text and store this in a php variable. To use later down the page.
The onChange event calls the run() function. In my script.js file.
Js/Ajax
function run(sel) {
var i = sel.selectedIndex;
alert(i);
alert(sel.options[i].text);
if (i != -1) {
$.ajax({
type: "POST",
url: "home.php",
data: { opValue : sel.options[i].text},
success: function(data)
{
alert(data);
}
});
}
}
The data opValue gets stored in the $_POST array. Then below i am trying to print the array, store in variable
Home.php
<?php
print_r($_POST);
if(isset($_POST['opValue']))
{
echo 'set';
print_r($_POST);
$option = $_POST['opValue'];
echo $option ;
}
?>
Though it doesn't work, it doesn't reach the echo set. Which suggest the post variable is not being set. What am i doing wrong here, this is fairly new to me and i am still a beginner in php/ajax/js.
P.S i have opted to do it this way as i do not want the page to reload/refresh.
regards.
EDIT:
- Added alert(data)
Now when i select year 2 in the response i am receiving this notable info.
Array
(
[opValue] => year 2
)
1year 2year 2Array
(
[opValue] => year 2
)
$(sel).val()to get the selected valuealert()for troubleshooting. Useconsole.log()instead.dataobject soconsole.logthedatato see if it is there rather than just alerting success