Reputation: 2649
I'm trying to write a function to get the value from a select statement, and echo the value to the screen. It works when I put the exact select name inside of the ajax function, but it stopped working when I tried to pass the select name through the parameters. I know it was passed through the parameter successfully, and I know it was the right select name by alerting it to the screen inside the function when I was testing it. So I think the actual problem might be on this line:
data: { select: $('select[name=theName]').val()},
But I'm not sure what is wrong with it. I have 2 versions of my codes below. The first version works, and the second version doesn't. The first version has the exact select name inside the parameter, and the second version is passed through the parameter called 'theName'. Please take a look:
ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,theName,id) {
alert(theName)
$.ajax({
type: "POST",
url: url,
data: { select: $('select[name="select1"]').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>
test1
<?php
echo "<select name = 'select1' onchange = 'ajax(\"test2.php\",\"select1\",\"output\")'>";
?>
^---This version works.
ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,theName,id) {
alert(theName)
$.ajax({
type: "POST",
url: url,
data: { select: $('select[name=theName]').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>
test1
<?php
echo "<select name = 'select1' onchange = 'ajax(\"test2.php\",\"select1\",\"output\")'>";
?>
^---This version does not work.
Upvotes: 0
Views: 609
Reputation: 9420
You have omitted double quotes and concatenation here:
data: { select: $('select[name="'+theName+'"]').val()},
Upvotes: 1