I’ve been trying to send the value of a select value to a PHP file using Ajax and then use in a SQL query but I can’t seem to get it to work.
My select options
<select id="select">
<option value="yes">Yes</option>
<option value="no">No</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
My Ajax request to a PHP file which has the SQL query
$(document).ready(function () {
$('#select').on('change', function () {
var selectValue = $(this).val();
$.ajax({
type: "POST",
url: "phpsqlajax_genxml3_state.php",
data: {
selected: selectValue
},
success: function (data) {
console.log(data);
// Stuff
},
error: function (data) {
// Stuff
}
});
});
});
Then in my PHP file, I have tried this
if(isset($_POST["selected"]))
{
$selectedValue = $_POST['selected'];
$query = "SELECT * FROM customers WHERE delivered='$selectedValue'";
}
And this
$selectedValue = $_POST['selected'];
$query = "SELECT * FROM customers WHERE delivered='$selectedValue'";
The alert pops up the correct value, but it’s not updating the variable in the PHP file?
3
Answers
Please try below code for get value of parameter
in you php code use
First thing:
Instead of writing:
var selectValue = $('#select option:selected').val();
you can just use:
var selectValue = $('#select').val();
Second thing:
You have set the value of the select outside of your function, so when your listener for ‘change’ runs, the value of
selectValue
has already been set, you never overwrite it.You’ll want to move where you set the value of the variable to the following:
Third thing:
As mentioned in the comments, you are looking for the key
selectValue
in the below code:$selectedValue = $_POST['selectValue'];
When you should be looking for:
$selectedValue = $_POST['selected'];
because that’s what you sent through via AJAX, here:
Fourth thing:
You’ve not sanitized the users input at all, leaving you open to SQL injection.
To protect against SQL injection you’ll want to consider updating to PDO:
How to prevent SQL injection