Using AJAX to reload only a Div
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
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:
1 | <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
1 2 |
PAGE 2 (saved as “property-detailed.php”)
The actual coding is really very simple:
1 2 3 4 5 6 7 8 9 | <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.
the
tag does not contain href and how it can be clicked ?
Ahsan, the clicking is registered; jQuery captures that click and makes it load the page we want.
Is it jQuery only or it does use ajax?
AJAX isn’t actually a different language; here, jQuery is being used to transport data as JSON text.
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.
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.
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
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!
It is not working. :/
Can you give a complete working example for clarity?
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.
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?
You can add variables to the end of the URL like normal. line 4: property-detailed.php?x=value
where to put the ajax code in page1 ??
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.
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?
If you’re refreshing the content, you’ll have to “attach” the javascript to the items again. For example, let’s say you have a button and you use AJAX to pull in a new page with a new button. Even if that button has the same ID or class, javascript is no longer connected to it. You have to re-bind the call to the button. Here’s a really good explanation in the answer for this stack overflow: https://stackoverflow.com/questions/13767919/jquery-event-wont-fire-after-ajax-call
How can I make the target p2mp page a variable, so that you can call different page elements into the viewing area?
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.
Ugh! Auto-correct- that should have read php page not p2mp page
Hi,
I found this while looking for a solution to my problem. I have a PHP page which is displaying a price :-
I added your example :-
2
<div id="main">£'.$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 :-
The price changes to the above text as expected. If I change property-detailed.php to :-
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!
I got it working 🙂
2
3
4
5
6
7
8
9
$(document).ready(function(){
setInterval(function(){
$("#here").load(window.location.href + " #here" );
}, 3000);
});
</script>
<div id="here">dynamic content ?</div>
Hope this help someone else!
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.
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.