Lets say your website page is already loaded but you need to poll your database for some extra info, or to check for an update on something. The way to go is using Ajax. jQuery makes working with Ajax really easy and even better if you return your data using Json.
Here is some code to get you started with jQuery, Ajax, Json and PHP really fast.
The code above is a simple script. It should update the temperature after clicking the provided link. jQuery listens for the click and starts an ajax request, passed on to ajax.php so it can poll the database with the provided parameters city and time, wich are passed with a POST method.
The variable request will trigger either request.done if success of request.fail if something went wrong when parsing the received Json (usually when the php page outputs an error).
The function request.fail will output to console the response of the php file in case of fail so it will be easier to debug.
<?php $city= $_POST['city']; $time = $_POST['time']; $query = "SELECT temperature FROM mytable WHERE city='$city' AND time='$time'"; //your methods for querying and handling the database info here. $response['emperature'] = $mydatabase_response_temperature; $response['code'] = 1; echo json_encode($response, JSON_FORCE_OBJECT); ?>
Leave a Reply