views:

245

answers:

2

Hi, I loaded a content into a div using php get_file_contents, now i want to refresh it using ajax but i can't figure how to do it.

Sample code:

<script>
function refreshmydiv(){
...
}
</script>

<div id="mydiv"> <? echo nl2br(htmlspecialchars($myfile)); ?> <div>
<a href="#" onclick="refreshmydiv();">Refresh My Div</a>
+1  A: 

So, here is one way of doing it. First, the parts:

myrefreshfunction

This function needs to make an AJAX call to refresh.php or another page. Then, it should replace the contents of mydiv with the html that is sent back.


refresh.php

This page needs to return the HTML for the div. It doesn't need to return the whole page, it only needs to return the contents of the div.

In this case, it would just echo get_file_contents and nothing else.


Then, the refresh process looks like this:

  1. Your user presses the button to refresh the div.

  2. Your function requests a page.

  3. The page returns ONLY the contents of the div.

  4. Your function replaces the content of the div with the page it just requested.

There are other ways to do this, put this is a very straightforward way to do it.


If you use jQuery, your myrfreshfunction is basically one line of code:

$('mydiv').load('refresh.php');
Chacha102
thank u,u opened my eyes, it was easier than i thought ;)
JQman
A: 

If you use the Prototype JavaScript framework you can do it this way:

<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
    function refreshmydiv() {
        new Ajax.Request('/ajax/getdivcontents.php', {
            method: 'post' ,
            onSuccess: function(request) {
                $('mydiv').update(request.responseText);
            }
        });
    }
</script>
<div id="mydiv"> <? echo nl2br(htmlspecialchars($myfile)); ?> <div>
<a href="#" onclick="refreshmydiv();">Refresh My Div</a>

This will make an Ajax call when you click on the "Refresh My Div" link. The getdivcontents.php page will create the HTML you wish to display.

John Conde
that's a nice way to do it thx
JQman