Using .selectmenu() with onchange event and ajax/passing variable
Hey,
Presumably due to my amateur abilities I'm having trouble with getting the JQuery UI selectmenu to work with my jquery script for passing a variable from the selected option of the dropdown menu to my php file.
It all works fine until I add the
$( "#users" ).selectmenu ()
then the jquery UI works and the passing of the variable and ajax doesn't. I have no doubt that I'm inserting it into my jquery wrong but I have been through the documentation and it does not seem to clear anything up for me.
I've tried lots of variations but the ajax/variable are not working. Can someone give me a bit of help integrating this into my code please? :)
I used a basic template from w3schools originally for the dropdown and converted the javascript to jquery so it was easier to work with:
- $(document).ready(function() {
var q = $('#users').val();
$('#users').on("change", function () {
q = $(this).val();
$.ajax({
url: 'searchtestphp.php',
data: 'q='+q,
success: function (data) {
$('#txtHint').html(data);
}
}).error(function() {
alert ('An error occured');
});
});
});
The php is:
- <?php
if (isset($_GET['q'])) {
$q = $_GET['q'];
}
$con = mysqli_connect(host','user','password','database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con);
$sql="SELECT * FROM user WHERE firstname LIKE \"%".$q."%\" ";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['hometown'] . "</td>";
echo "<td>" . $row['job'] . "</td>";
echo "<td>" .$q. "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The html:
- <form>
<select id="users" name="users">
<option value="">Select a person:</option>
<option value="peter">Peter Griffin</option>
<option value="lois">Lois Griffin</option>
<option value="joe">Joseph Swanson</option>
<option value="glenn">Glenn Quagmire</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
<script src="../jquery.js"></script>
<script type="text/javascript" src="../jquery-ui-1.11.1.custom/jquery-ui.js"></script>
This is probably extremely basic but thanks in advance!