I have a script that uses AJAX to display results from a separate PHP script on my page.
However, now I'd like to pass data from the form (the select menu) to the script. How do I do this? I'd just like to use the value selected in the select menu as part of the WHERE clause in my SQL command.
Web Page:
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "display.php",
dataType: "html",
data: {
"some-var": "some-value"
},
success: function(response){
$("#responsecontainer").html(response);
}
});
});
});
</script>
</head>
<body>
<form>
<select id="city" name="city">
<option value="">City:</option>
<option value="glasgow">Glasgow</option>
<option value="london">London</option>
</select>
<input type="button" id="display" value="Display All Data" />
</form>
<br>
<div id="responsecontainer"> </div>
</body>
</html>
PHP script:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM entries";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - City: " . $row["city"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
form.serialize(). When will you start reading manuals?data:$('form').serialize(), as @u_mulder have said