Using AJAX to reload only a Div

April 2017

Ajax has become very popular because of the ease of use it incorporates into a website for the user. It isn’t a single language, but more a conglomeration of css, ajax, javascript and html. Basically, I’m going to show you how to get the iframe effect (not reloading the whole page, only part of it) but without the iframe (because really, no one should be using those anymore!).

If you’re looking to load a Div based on specific timing intervals, check out:

Refresh a Section of a Page at Specific Intervals 

Reloading AJAX - Coding

First, we have to set up our page. You will need to include a link to a jquery library source of your choice. I use google because, well, I like google and it’s easy:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">

Just paste that code between the tags of your page and you’ll be good to go. Second, you need to create divs and name them with IDs. If you don’t know how to do this, just check out some CSS articles. You need to create two pages, each one with the same div ID. I used “main” as my div ID below.

PAGE 1

<a id="detailed">LINK</a>

<div id="main">Hello - This is my main Div that will be reloaded using Jquery.</div>

PAGE 2 (saved as “property-detailed.php”)

<div id="main">Hello - This is the div that will be loading into the first div</div>

The actual coding is really very simple:

<script type="text/javascript" language="javascript">
$(document).ready(function() { /// Wait till page is loaded
   $('#detailed').click(function(){
      $('#main').load('property-detailed.php #main', function() {
           /// can add another function here
      });
   });
}); //// End of Wait till page is loaded
</script>

What is happening here??? Don’t worry! I’ll walk you through it. First, as with all jquery coding, we encase the actual coding into the “$(document).ready” function. This makes sure that the jquery coding doesn’t try (and fail) to work before the page is loaded.

Then the following is done: We take the Div ID “detailed” (this is a div surrounded by < a > tags on page one) and when it is clicked, we want the following function to run:
The Page 1 Div ID “main” will load the Page 2 (“property-detailed.php”) but only the Div ID “main” from that page. When that is done, I left a space for adding another function after the new Div loads.

That’s it! When you boil it down, it really is just one line of code. A nice little function for a nice little trick.

Just a minor note: you cannot do this cross-site. In other words, you can’t load part of another website into your website using this JQuery function.

LinkedInThreadsFacebook

23 Comments

  • ahsan says:

    the

    <a>

    tag does not contain href and how it can be clicked ?

  • Carlos says:

    Is it jQuery only or it does use ajax?

  • CHRISTOPHER CHUKS IGWUBOR says:

    hi , what if i just want to refresh a specific DIV in the same page ???
    for example i have

    Total(€) :
    and want to keep reloading this div section , so that if any value entered earlier is changed, the total is updated.

    Thanks in anticipation.

    • Kim Joy Fox, CEO says:

      This sounds like just a javascript/jquery change. You might not need AJAX to do this; AJAX is used if you need to get information from the database.
      If I’m misunderstanding and you do need to update just the div, the #main tag (line 4 of the last coding section in the article) references the Div with the ID of Main and loads the information from the PHP page into that specific div. The PHP page would then only have information for that Div in it: it would return only the Total. You would then call the .load function whenever the value is changed.

  • rickie knight says:

    Just wanted to say your brand name is dope. Appreciate the tutorial too. If I were to use Ajax to get new posts for a users feed and store it in a button that counts the number of new posts (similar to twitter). How would I go about doing that? Thanks in advance.

    Best,
    Rickie Knight

    • Kim Joy Fox, CEO says:

      Thanks Rickie!
      That problem is a little too big to solve here. I’d start by breaking this down into the smallest problems you can and looking for solutions to those. For example, step 1: getting new posts using AJAX. This tutorial will help you do that step. Then you’ll need to count all posts that are new – but to do that, you’ll need to keep track of what posts that person has already read. So you’ll need a new insert or field in the database. Then you can compare which posts they’ve read and which posts they haven’t, count that number, and then echo it into a button. Good luck!

  • Nishant Agarwal says:

    It is not working. :/
    Can you give a complete working example for clarity?

    • Kim Joy Fox, CEO says:

      Nishant, the code above is a complete example. Because you can’t load cross-site it gets complicated to try to provide a working example. I’d recommend checking your console errors and working starting there.

  • sachin says:

    Hi, I need to pass some variables from main page to the property-detailed.php so that I can perform a query on the page and display the result accordingly.
    can you please help me with that?

  • vishal says:

    where to put the ajax code in page1 ??

    • Kim Joy Fox, CEO says:

      The ajax code can be added at the top of the page or the bottom; I’d recommend the bottom, directly before the end of the body tag.

  • Nick says:

    This is a really neat trick. Where I have problem how ever is after the ajax refresh. All initialized Javascript functionalities stop functioning. Is there a way to work around this?

  • Mark Ireland-Spicer says:

    How can I make the target p2mp page a variable, so that you can call different page elements into the viewing area?

    • Kim Joy Fox says:

      To call the page elements instead of the entire page, include a Div ID (line 4 in the coding example) above. The #main is a Div ID.

  • Mark Ireland-Spicer says:

    Ugh! Auto-correct- that should have read php page not p2mp page

  • Dave says:

    Hi,

    I found this while looking for a solution to my problem. I have a PHP page which is displaying a price :-

    <td>&pound;'.$row['total'].'</td>

    I added your example :-

    <td><a id="detailed">LINK</a>
    <div id="main">&pound;'.$row['total'].'</td></div>

    Which displays the price and the LINK text as expected. If I run this code in the property-detailed.php file :-

    <div id="main"><td>Hello - This is the div that will be loading into the first div</td></div>

    The price changes to the above text as expected. If I change property-detailed.php to :-

    <div id="main"><td>'.$row['total'].'</td></div>

    The code is displayed literally rather than the latest price. Any ideas how to get this to work and also auto refresh after X seconds rather than require the LINK text to be pressed?

    Thanks in advance!

  • Dave says:

    I got it working :)

    <script>
    $(document).ready(function(){
    setInterval(function(){
          $("#here").load(window.location.href + " #here" );
    }, 3000);
    });
    </script>

    <div id="here">dynamic content ?</div>

    Hope this help someone else!

  • vidhya says:

    Hi, Thanks for posting this. Could anyone tell me how to make ajax div fixed after 1st event ? Before 1st event it should be 0 size, after 1st event it expand and then there after it should be constant. Otherwise this div is disturbing visual to eyes.

    • Kim Joy Fox says:

      If you’re adjusting the size per content loading, I would suggest using a jquery $(‘#test’).prop(‘scrollHeight’) function to find the height of the content. Otherwise, you can add a “height” function to the div that’s just stable.

Leave a Reply

Your email address will not be published. Required fields are marked *