DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Daniel has posted 2 posts at DZone. View Full User Profile

When Creating Dynamic Content With AJAX Don't Forget To...

  • submit to reddit
        When using AJAX to get data from the server to fill an HTML element, some peolpe find that the AJAX call only works the first time it is executed. If your request returns different data each time there is nothing to worry about but if the server returns the same data twice, nothing will happen on the page the second time. To prevent a null AJAX call you need to clear the HTML element (e.g. <div>) that is displaying the data before executing the request.

	<script type="text/javascript" src="jquery-1.2.6.js"></script>
	<script type="text/javascript" charset="utf-8">
		$(document).ready(function() {
			$('input#server_get').click(function() {
                                // Empty the contents of the div here!
		function ajaxRequest() {
			var Id = $('#input_id').val();
			var Name = $('#user_name').val();
			$.get('script.url', {id: Id, name: Name}, function(data) {
	<label>User ID: </label><input type="text" name="input_id" value="" id="input_id" />
	<label>User Name: </label><input type="text" name="user_name" value="" id="user_name" />
	<input type="button" name="server_get" value="Get Data from Server" id="server_get" />
	<h3>Data returned from the server</h3>
	<div id="serverReturn"></div>