Skip to content

Instantly share code, notes, and snippets.

@MauMaGau
Created May 29, 2012 22:04
Show Gist options
  • Save MauMaGau/2831080 to your computer and use it in GitHub Desktop.
Save MauMaGau/2831080 to your computer and use it in GitHub Desktop.
AJAX: Non-blocking
<?php
// If this is an ajax call, just return what's needed
if(isset($_POST['ajax'])){
sleep(2); // Add some lag
echo $_POST['value']; // The input message
}else{
?>
<html>
<head>
<script src='jquery.js' type='text/javascript'></script>
<script>
$(document).ready(function(){
$('#message_input').keyup(function() {
$('#updatehere #astyped').html($('#message_input').val());
maybe_update();
});
// The user hits submit...
$('.nbajax').submit(function(){
save_input();
return false;
});
function save_input(){
// Let the user know we're working on it
$('#loading').html('<p class="saving">Saving in the background</p>');
$('#loading').stop();
$('#loading').fadeTo(1000, 1);
// Grab the user's input
message = $('#message_input').val();
$('#astyped').html('');
$('#assaved').append(message);
// Clear the text input
$('#message_input').val('');
// Party time
$.ajax({
url: $(this).attr('action'),
type: 'post',
data: {'ajax':'true', 'value':message},
dataType: 'html',
complete: function(response){
// Let the user know we've completed our mission
$('#loading').html('<p class="saved">Saved</p>');
$('#loading').stop();
$('#loading').fadeTo(1000,0.2);
// Add the users input to the page
//$('#updatehere #assaved').append(response.responseText);
}
});
};
function maybe_update(){
if( $('#message_input').val().length > 5 ){
save_input();
}
}
});
</script>
<style>
*{color:#000; font-family: Arial, "MS Trebuchet", sans-serif;}
#page_wrapper{width:260px; margin:100px auto;}
#loading p{padding:10px; font-weight:bold; color:#222;}
.saving{background-color:#d76e80;}
.saved{background-color:#b5e9af;}
#updatehere{font-weight:bold;}
#astyped{color:#aaa;}
#message_input{padding:10px;}
input[type=submit]{padding:10px;}
</style>
</head>
<body>
<section id='page_wrapper'>
<section id='updatehere'>
<!-- <h1>Your messages here</h1> -->
<span id='assaved'></span><span id='astyped'></span>
</section>
<form class='nbajax' method='post' action='' data-show='updatehere'>
<input type='text' name='data' id='message_input'>
<input type='submit' value='Save'>
</form>
<section id='loading'></section>
</section>
</body>
</html>
<?php } ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment