Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Refresh Div Content Using jQuery

In this article we will see how to use jQuery JavaScript framework to implement a refresh into divs that have dynamic internal resources.

If you happen to be a regular on certain social networking sites, such as Twitter, you will have surely not missed how the new posts appear to automatically load and show up after a certain interval of time. This automatic loading feature is a very useful addition to have in many pages of the Web, and is a handy feature that can be performed, with not many lines of code involved in the process.

Why is automatic refreshing and loading of Div content required?

While there is certainly nothing wrong with having the option of manually loading div content on pages, these days, many of the sites would want to impress or rather cut some slack on the users’ part when it comes to dealing with such things. Therefore, the likes of Facebook, Twitter and even a number of RSS feeds make use of the automatic refresh feature to display content on their site’s pages. Additional search results are also often displayed in this manner.

If you have any kind of a website that displays the likes of news, or any other sort of important information, you can implement the automatic loading feature.

How Ajax is used in automatic refresh?

More of a related number of collective web development techniques, Ajax stand for asynchronous JavaScript and XML. Basically, Ajax is largely used to create web-based applications on the client-side. Such applications are generally employed in parts where there is the need to asynchronously retrieve and send data, remaining completely in the background. During this process, Ajax applications also do not affect the state of the original page, in the context of behavior and display.

Also, what is clearly a point to note is that Ajax essentially isn’t the use of a single technique. In fact, it basically makes up a group of various techniques where HTML, CSS and JavaScript can work in sync in order to implement various functions.

If you want to be more into Ajax subject, please refer to some of our other articles:

What is the role of jQuery?

In order to simplify the process of client-side HTML scripting, jQuery happens to be a popular library of JavaScript that can be implemented on numerous platforms. It is free and belongs to the open source software. The syntax of jQuery largely allows for the easy navigation of any document, handling of events, in the creation of animations and also, for the development of applications that are based on Ajax. Developers can also make use of jQuery to create plug-ins.Overall, one can expect to create very powerful web pages and applications that are very dynamic in nature. As of present, jQuery also happens to be the most largely used JavaScript library.

How are we going to implement this feature?

While refreshing of div content can largely be implemented by making use of jQuery, it also requires the use of Ajax. Besides this, we will also employ the use of PHP, HTML and CSS for the implementation of basic functionalities, design and layout.

Example 1

Listing 1: This is the code for the index1.html file

<html>

<head>
    <!-- We are using a jQuery version hosted by jQuery- But any version canbe downloaded any link to it in local deployment -->
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
    <script type="text/javascript">
        var auto_refresh = setInterval(
            function() {
                $('#loadtweets').load('count_record.php').fadeIn("slow");
            }, 15000); // refreshing after every 15000 milliseconds
    </script>

    <body>
        <div id="loadtweets"> </div>
    </body>

</html>

Different component of this code snippets are as follows

  • First, declaring a variable called ‘auto_refresh’ and calling the setInterval method. The return result of this calling is assigned to the variable.
  • Second, inside setInterval method, two parameters are passed. One is a function and second is a number representing refresh milliseconds.
  • Third, inside the function call, two other methods are called; one is load and second is fadeIn. The load method passes one PHP file as the parameter and fadeIn method set the fade-in effects.
  • Fourth, the body only describes the div id.

The code snippet shown above primarily describes the HTML code along with the JavaScript component. Now, one of the most important parts of the snippet is the load (‘count_record.php’). Here, we are basically calling the PHP file that is defined in Listing 2 and that is being displayed. Further, you can also take note of the function load that is basically implementing the auto refreshment option after every 15000 milliseconds or 15 seconds.

Listing 2: This is the code for the count_record1.php file

<?php
echo "Div content automatic refresh using jQuery";
?>

The following output will be displayed as the effect of this code.

Figure 1 – Displaying Div content refresh

Listing 2 contains the content that is basically displayed and then refreshed after an interval of 15 seconds. You can also substitute that with any other content that you might want to display.

The above, consisting of Listing 1 and Listing 2, is also an example of a classic simple feature that can be implemented to show the basic way to materialize the displaying of Div content using jQuery.

Example 2

Listing 3: This is the code for the index2.php file

<html>
	<head>
		<!-- We are using a jQuery version hosted by jQuery- But any version canbe downloaded any link to it in local deployment -->
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
		<script type="text/javascript">
			var auto_refresh = setInterval(
			function () {
				$('#loadtweets')
					.load('count_record.php?q=<?php echo $search_word; ?>')
					.fadeIn("slow");
			}, 15000); // refreshing every 15000 milliseconds/15 seconds
		</script>
	</head>
	<body>
		<div id="loadtweets"> </div>
	</body>
</html>

This employs the use of PHP and JavaScript code. You can also note how the count_record.php file has been summoned again as a part of the content that is to be displayed.

The $search_word is basically the variable that defines the string that is to be searched by Twitter or Facebook. This string can be inputted in the search box that is found on the sites. Finally, there’s the portion that defines the time interval and it has been set to 15000 milliseconds.

Listing 4: This is code for the count_record2.php file

<?php
include("db.php");
 $search_word=$_GET['q'];
 $sql_qry = mysqln_query($db,"Select unique_id form MessageTbl where message 
 LIKE '%$search_word%'");
 $count_record=mysqln_num_rows($sql_qry);
//Now display the count
echo $count_record;
?>

Now let me explain the components as follows.

  • In the first line, we have included the data base PHP file containing all the database related information.
  • In the second and third line we have declared two variables search_word and sql_qry. The first variable is calling a GET method (using parameter ‘q’) to retrieve the search word. The second query variable is actually calling the sql query function mysqln_query by passing the db and sql statement. It is also passing the search keyword as the third input parameter.
  • Now, the count_record variable is actually fetching the number of records
  • The last line is displaying the count.

In this piece of PHP code, we are calling the database, or rather accessing it, in order to count the number of tweets. The number of counted tweets is also displayed for the user to see.

Listing 5: This is the code for the database.php file

 <?php
 define('DB_SERVER_IP', 'localhost_ip');
 define('DB_USER_NAME', 'user_name');
 define('DB_PASS_WORD', 'pass_word');
 define('DB_DATABASE_NM', 'database_nm');
 $connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
 ?>

This piece of code snippet contains the database configuration code that is used for the second example. They contain username, database and password as such.

Load content on page load

The following example will show one procedure to load the content immediately on page load. This can be required when we need immediate update.

Listing 6: Immediate content load

 <html>
 <head>
<!-- We are using a jQuery version hosted by jQuery- But any version canbe downloaded any link to it in local deployment -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
 <script>
  $(document).ready(function() {
        $("#newresponsecontainer").load("newresponse.php");
       var newrefreshId = setInterval(function() {
      $("#newresponsecontainer").load('newresponse.php?randval='+ Math.random());
   }, 7000);
   $.ajaxSetup({ cache: false });
});
 </script>
 </head>
 <body>
 <div id="newresponsecontainer">
 </div>
 </body>

Now, let us have a look at different components. Here, we are calling a load function by passing a PHP page as parameter. Then we are calling the setInterval function as we did earlier. We are also using Math.random function to define some random value and also setting the time as 7000 milliseconds.

Conclusion

The implementation of refreshing Div content by making use of jQuery and Ajax is very useful to display search results or even tweets and posts on popular search engines, social networking and news websites.

With the automatic loading of posts, users will not need to additionally refresh the page at very frequent intervals to get the very latest content on the page. Such common and useful feature can be very easily implemented. You must have also noted that the overall implementation is also very simple and requires the use of very few lines of code.

In the top of the page you can also find the source code examples shown here. Good studies!



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login