In this article, I will write about Simple Shoutbox Application with JQuery. With Ajax (Asynchronous JavaScript and XML) , we can send a form submission and get response back without refreshing current page. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
Javascript Code :
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var comment = $("#comment").val();
var dataString = 'name='+ name + '&comment=' + comment;
if(name=='' || comment=='')
{
alert('Please Give Valide Details');
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="img/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "ajaxshoutbox.jsp",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#name").val('');
$("#comment").val('');
$("#name").focus();
$("#flash").hide();
}
});
return false;
}
});
});
Explanation :
$.ajax({}) is JQuery event to call ajax request, it’s has an object of key/value pairs , that are used to initialize and handle the request.
- type : The type of request to make ("POST" or "GET"), default is "GET"
- url: The url to request
- data: Data to be sent to the server
- chace : if set to false it will force the pages that you request to not be cached by the browser
- success : A function to be called if the request succeeds
Soutbox.jsp
<form action="#" method="post">
<label><input type="text" name="name" id="name"/>
<span class="titles">Name</span><span class="star">*</span>
</label><br />
<label>
<textarea name="comment" id="comment"></textarea>
<span class="titles">Comment</span>
</label><br />
<input type="submit" class="submit" value=" Submit Comment " /> </form>
ajaxshoutbox.jsp
><li class="box">
<span style=" font-weight:bold">Name :</span>
<span style="font-size:16px; color:#663399;"><%= request.getParameter("name") %></span> <br />
<span style=" font-weight:bold">Comment :</span> <%= request.getParameter("comment") %>
</li>
Download Sourcecode :
http://simpleshoutboxajax.googlecode.com/files/SimpleShoutboxAjax-JQuery.zip