I'm trying to use ajax on a select tag with 2 options, but it's not getting the $_POST for some reason. It prints out the "---", but it does not print out the $_POST value, which is either 1 or 2. I'm not sure what I did wrong. Please take a look at my code right here, and if you figure out which part of the code is wrong, please point it out with a working example. Thank you.
newtest.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,type,theName,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $(type+'[name='+theName+']').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>
<?php
echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"input\",\"name\",\"output\")'>";
echo "<option value = '1'> 1 </option>";
echo "<option value = '2'> 2 </option>";
echo "</select>";
echo "<div id = 'output'></div>";
?>
newtestx.php
<?php
$name = $_POST['name'];
echo $name."---";
?>
You need to change this line:
echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"select\",\"name\",\"output\")'>";
1: Maybe you want to post the value. data:{select:$("select[name='name']").val()}
. But selector is false. tag is select
not input
.
`echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"input\",\"name\",\"output\")'>";";`
`data: { select: $(type+'[name='+theName+']').val()},`
2: .php will not get the param. Because your data's key is select
, so $name = $_POST['select'];
. Finally, you want to return data, should use die($name)
;
`$name = $_POST['name'];
echo $name."---";`