Load Box Content Dynamically using AJAX

Share this article

This is how you can create page box elements that are loaded via AJAX and can be refreshed instantly without a whole page reload. It uses a combination of jQuery and JavaScript code. It’s kinda like the facebook content box loader but i coded it myself from scratch.

Advantages of using this AJAX method

  • The page loads faster because it loads the content boxes after the DOM is ready
  • The content in the box can be reloaded without the whole page reloaded
  • All websites are moving towards doing it such as facebook, twitter, odesk etc…
  • New boxes can added without the need for any further CSS or JavaScript coding

How it works

loading-new-blogs new-blogs
  • After the web page loads jQuery calls a AJAX function for each box to load
  • A loading message is displayed
  • A server side script (such as PHP) file returns the HTML for the box
  • The content is loaded into the box on the web page
  • The content can easily be reloaded when the user hovers the box the refresh image will appear and once clicked the content will refresh
See Live Demo Download Source Files

How is it a dynamic?

Each box is a div that contains an id attribute that uniquely identifies that box. Each element inside this div is named with that id of the div. The jQuery picks up this id and uses it to match against a server side script (such as PHP) matches the id of the box and is loaded. This makes it dynamic because all variables are created based upon the id of the box.

jQuery code

This function loads after the web page is loaded and initialises the boxes for use attaching events.
jQuery(document).ready(function($) {
	//event to show the box controls when the mouse hovers the box
	//applies to all elements with class="box"
	$('.box').mouseover(function(){
		//replace string "box" with "controls"
		var dyn_var = "#" + this.id.replace("box","controls");
		$(dyn_var).show();
	});

	//initialize box controls
	$('.box .controls').hide(); //hide all box controls

//hide box when mouse exits box
	$('.box').mouseout(function(){
		$('.box .controls').hide();
	});

	//load box content (loads after page loads)
	loadboxcontent('box-id1');
	loadboxcontent('box-id2');
	//etc...
});
This function takes the id of the div and loads content into a child div with id = box_id parameter. It can be applied to any box control as it dynamically creates the js variables to pickup the objects. div container id = box_id php script name = box_id.php
function loadboxcontent(box_id){
	//perform an initial check to see if box_id has been supplied
	if (box_id == '') { return false; }

//show loading image
	var loading_image="/images/loader.gif"; //Full URL to "loading" image.
	var loading_text = ' Loading '+box_id.replace(/-/g," ")+'...';
	var script_path = "../php/"; //path to server side script
	var box_container = document.getElementById(box_id);
	box_container.innerHTML = loading_text;

	//record the result of the AJAX request
	//(async = false) they load in order and wait until the previous is finished
	//(async = true) they all load at the same time
	var result = false;
    $.ajax({
      url: script_path+box_id+".php",
      type: 'POST',
      async: true,
      data: {blogs: 30},
      success: function(data) {
      	 result = true;
      	 document.getElementById(box_id).innerHTML = data;
      }
    });
    if (result == false) { document.getElementById(box_id).innerHTML = 'Could not refesh data, try refreshing the page'; }
    else {  alert("Content refreshed successfully!");   }
}

HTML code

Box Name



New Blogs

CSS code

.box { text-align:left; min-height:50px; margin:0px 0px 0px 0px; padding:0px 0px 0px 0px; border:1px #FFFFFF groove; }
.box:hover { background-color:#F2F2F2; border:1px #E4DFF4 groove; }
.box h2 { margin:0; padding:5px 0px 5px 10px; background-color:#8973C8; color:white; text-shadow:1px 1px 1px #A999D7; }
.box h2 a img { vertical-align:middle; }

/* BOX CONTROLS */
.box .controls { float:right; position:relative; top:5px; right:5px; }
.box .controls a { opacity:0.8; }
.box .controls a:hover { opacity:1.0; }

Images

  • Loader.gif
  • Refresh.png
loader refresh

Frequently Asked Questions (FAQs) about Loading Box Content Dynamically with AJAX

How can I load dynamic content using AJAX in a specific div?

To load dynamic content using AJAX in a specific div, you need to use the jQuery AJAX method. This method allows you to load data from a server and place the returned HTML into the selected element. Here’s a simple example:

$.ajax({
url: "yourfile.html",
type: "GET",
success: function(data){
$("#yourDiv").html(data);
}
});
In this code, “yourfile.html” is the file from which you want to load data, and “#yourDiv” is the id of the div where you want to place the loaded data.

What are the benefits of using AJAX to load dynamic content?

AJAX allows you to update parts of a web page without reloading the whole page. This results in a faster, more responsive user interface. It also reduces the load on the server, as only necessary data is transferred.

Can I use AJAX with other programming languages like PHP?

Yes, AJAX can work with any server-side technology, including PHP. AJAX can send data to a server script, which can update a database, and then return the data back to the client.

How can I handle errors when loading content with AJAX?

You can handle errors by using the “error” callback function in the AJAX method. This function will be executed if the request fails.

$.ajax({
url: "yourfile.html",
type: "GET",
success: function(data){
$("#yourDiv").html(data);
},
error: function(){
alert("Error loading data");
}
});
In this code, if the request fails, an alert box with the message “Error loading data” will be displayed.

How can I load JSON data using AJAX?

You can load JSON data using the “getJSON” method in jQuery. This method loads JSON-encoded data from a server using a GET HTTP request.

$.getJSON("yourfile.json", function(data){
console.log(data);
});
In this code, “yourfile.json” is the file from which you want to load data. The loaded data is then logged to the console.

Can I use AJAX to load content from another domain?

By default, AJAX requests are subject to the same-origin policy, which means that AJAX can only load data from the same domain. However, you can bypass this restriction using JSONP or CORS.

How can I send data to the server using AJAX?

You can send data to the server by including it in the AJAX request. The data should be in the form of an object, where each property is a data field.

$.ajax({
url: "yourfile.php",
type: "POST",
data: {name: "John", location: "Boston"},
success: function(data){
console.log(data);
}
});
In this code, the data {name: “John”, location: “Boston”} is sent to the server.

How can I load XML data using AJAX?

You can load XML data using the “ajax” method in jQuery. This method allows you to specify the data type of the expected return data.

$.ajax({
url: "yourfile.xml",
type: "GET",
dataType: "xml",
success: function(data){
console.log(data);
}
});
In this code, “yourfile.xml” is the file from which you want to load data. The loaded data is then logged to the console.

Can I use AJAX with HTML forms?

Yes, you can use AJAX to submit HTML forms without reloading the page. This can be done by preventing the default form submission event and then using AJAX to send the form data to the server.

How can I update a part of a web page in real-time using AJAX?

You can update a part of a web page in real-time by periodically sending AJAX requests to the server and updating the page with the returned data. This can be done using the “setInterval” function in JavaScript, which allows you to execute a function repeatedly at specified intervals.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

ajax load contentdynamic content boxjQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week