By far the most requested and sought after ‘trick’ with jquery and php is to make a ‘div’ fade out, refresh/get new data, and fade back in. When done right, it looks absolutely magical and is also quite useful for bringing in new data to present the user without having to refresh a page.
Below is the code you will need to refresh a div (or any other kind of css selectable element) with new data from a php file.
mainfile.htm
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#theform").submit(function () {
// Create a variable with the value of the textinput class object
var payload = $(".textinput").val();
// Set the variables up to be sent in GET request
var dataString = 'payload=' + payload;
// Check if payload variable is empty
if (payload == '') {
// If payload is empty, send alert
alert('payload is empty');
}else{
// Display message while request is processing
$(".response").html('please wait');
$.ajax({
type: "GET",
url: "action.php",
data: dataString,
cache: false,
success: function (html) {
// Fade the processing message out
$(".response").fadeOut(100);
// Change the content of the message element
$(".response").html(html);
// Fade the element back in
$(".response").fadeIn(100);
}
});
}return false;
});
});
</script>
<div class="response">
the response and processing message goes here
</div>
<form id="theform" action="" method="GET">
<input type=text class="textinput">
<input type=submit value="submit">
</form>
action.php
<?php
$payload = $_GET['payload'];
// You can do whatever you want to with the payload at this point.
$response = "The payload you sent was...".$payload."";
echo $response;
?>

Comments are closed.