I need to take an input (date) from a form in a php file, and use the date variable to select data from a mysql database and return an array in the same php file without refreshing the page. Right now, I have 3 files: index.php, global.js, and date.php
index.php takes an input (a date, in this case)
Date: <input type="text" id="date">
<input type="submit" id="date-submit" value="Submit">
<div id="date-data"></div>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="js/global.js"></script>
global.js listens for a click on the submit button and posts the input (date) to date.php
$('input#date-submit').on('click', function() {
var date = $('input#date').val();
$.post('../ajax/date.php', {date: date}, function(data) {
$('div#date-data').html(data);
alert(data);
});
});
date.php takes the date and queries the mysql database to return an array. This array needs to be passed back to index.php but I can’t figure out how to do it.
<?php
$con = mysql_connect('localhost', 'root', 'pass');
mysql_select_db('gymflow', $con);
$date = $_POST['date'];
$query = mysql_query("SELECT * FROM table WHERE `date` = $date");
$values = array();
while ($row = mysql_fetch_array($query))
{
$values[] = $row['utilization'];
}
echo json_encode($values);
?>
Ideally, I need to be able to have the $values variable from date.php passed to a $values variable in index.php
There must be an easier way to do this…
The purpose of your AJAX call is to not refresh
index.php, and instead deliver the result ofdata.phpstraight into the first page. You can modify the DOM via the javascript callback, and should make other database-requests indata.php. There is no purpose in lettingindex.phpaware of the output ofdata.php, simply because when the Javascript call is made, your first page has already been processed and sent to the client and possibly already rendered in the browser window.If you need to know the input value in subsequent requests to
index.phpyou may store in the value in the user’s session.