I am trying to use the jquery ajax api to retrieve data from a mysql database. The sql query I am using is working correctly as I have tested it by creating a user form and traditionally $_POSTing its content to see if it retrieves the correct data from my database.
However, I now want to retrieve the data from my mysql table without having to reload the page using the jquery ajax function. I am a novice when it comes to jquery, I haven't used it much before, and I would really very much appreciate it if someone could provide me with a nice example as to how it works. I have looked online at various articles and guides and I just cannot understand it.
Here is a form:
<form id="restaurant_reservation">
<label for="date">Reservation Date?</label>
<input type="text" name="date" id="date" value="yyyy-mm-dd" />
<label for="capacity">Amount of Customers?</label>
<input type="text" name="capacity" id="capacity" />
<label for="license">Smoking or Non-Smoking Area?</label>
<select id="license">
<option value="0" id="no">Smoking</option>
<option value="1" id="yes">Non-Smoking</option>
</select>
</form>
Here is the php code:
<?php
$user_reservation_date = $_POST['user_date'];
$user_customer_amount = $_POST['customer_amount'];
$user_smoking_non_smoking = $_POST['user_smoking_selection'];
$my_query = "SELECT * FROM restaurant
WHERE $user_reservation_date = date_available
AND $user_customer_amount >= max_seating
AND $user_smoking_non_smoking = smoking_choice";
$result =& $db->query($my_query);
if (PEAR::isError($result)) {
die($result->getMessage());
}
echo '<div id="output">';
echo'<table">';
echo '<th>restaurant name</th>';
echo '<th>Max Customer Seating</th>';
echo '<th>Smoking or Non Smoking</th>';
echo '<th>Average price per head</th>';
while($row =& $result->fetchRow()) {
echo '<tr>';
echo '<td>'.$row['rest_name'].'</td>'
echo '<td>'.$row['max_seating'].'</td>'
echo '<td>'.$row['smoking_choice'].'</td>'
echo '<td>'.$row['avg_price_per_head'].'</td>'
echo '</tr>';
}
echo '</table>';
?>
Here is my attempt at the jquery code:
$(function(){
$('#date').keyup(function(){
var user_input= $('#date').val();
});
});
$(function(){
$('#date').keyup(function(){
var user_input1=$('#date').val();
$.ajax({
type: 'POST',
data: ({user_date : user_input1}),
url: 'search.php',
success: function(data) {
$('#output_div').html(data);
}
});
});
});
I use the same code but change the #values for the other two fields from the form.
I would like to use jqeury ajax to get the input and selected values of this form and store them in a variable in my php document so that I can then use the users form data in my sql query to retrieve the appropriate restaurants.
I would really love to learn how to do this, and I would really apreciate any help. Thanks so much for reading. I'm sorry if I have been vague in describing my question properly. Thanks.
jquery.ajax
documentation? api.jquery.com/jQuery.ajax – undefined Apr 25 '12 at 15:25