Reputation: 4323
I have my code set up like this:
First a select:
<select id="select_order">
<option value="0">Pick One</option>
<option value="1">Ascending</option>
<option value="2">Descending</option>
</select>
And in my javascript:
var sortv= "database_percent";
var sorto= "asc";
$("#select_order").change(function(){
if (("#select_order").val == 1) {
sortv = "database_percent";
sorto = "asc";
}
else if (("#select_order").val == 2 ){
sortv = "database_percent";
sorto = "desc";
}
else {
alert("Pick something");
}
});
$.ajax({
url: 'all_get_2.php?category=ethnicity',
type: 'GET',
dataType: 'JSON',
data: {sortvalue: sortv ,sortorder:sorto},
})
What I'm hoping to do is get the value selected from the dropdown and then pass those new variables (for sortv and sorto) into ajax. The AJAX is getting JSON from my PHP file, which is used to draw a Flot chart.
I set the variables of sortv and sorto above the if...else code, so that the AJAX has some variables to load the chart at first (and so it won't throw an error). However, when I select something different from the select, I'm getting the alert that corresponds with my ELSE condition. I have no idea why though.
Assuming I (i.e., you) can fix this, is this even the right approach to pass new data variables in AJAX? Should I actually expect my charts to redraw when those variables change if that code is my .done statement (not shown)?
Any thoughts would be appreciated.
Upvotes: 1
Views: 708
Reputation: 2810
Use .val() not .val to receive the value. val() is a function which can get or set the value for your field.
Also you should use $(this) inside the eventhandler function, because in your code, the event is called by your select field, so you don't need to reselect it by id:
$("#select_order").change(function(){
var call = true;
switch(parseInt($(this).val())) {
case 1:
sortv = "database_percent";
sorto = "asc";
break;
case 2:
sortv = "database_percent";
sorto = "desc";
break;
default:
call = false;
alert("Pick something");
break;
}
if(call) {
$.ajax({
url: 'all_get_2.php?category=ethnicity',
type: 'GET',
dataType: 'JSON',
data: {sortvalue: sortv ,sortorder:sorto},
success: function(data) {
// your response handler here
}
});
}
});
Upvotes: 1