dave
dave

Reputation: 475

How to update a php variable in a HTML document without refreshing the whole page?

I have a webpage that echoes out a list of files(pdfs) that i have uploaded in a MYSQL database. When i upload a new file, i would like to automatically update this list to include the new file that i have uploaded without having to refresh the entire webpage.

This is my HTML code that displays the updated list through the variable $mypdf_list :

 <div id="listwrapper_hook">
    <div id="dynamic_listwrapper"><hr>
        <!--DYNAMIC PDF LIST CONTENT GOES HERE-->
        <?php echo $mypdf_list; ?>
    </div>
</div>

I have tried the to swap out the 'dynamic_listwrapper' div and then replace it with a new one through javascript in the hope that the displayed 'mypdf_list' variable is refreshed. But this has not worked.

MY javascript code:

 //UPDATE 'Recently Uploaded Files'
    var wrapper_hook = document.getElementById('listwrapper_hook');
    var list_wrap = document.getElementById('dynamic_listwrapper');

    wrapper_hook.removeChild(list_wrap);

    //Add child again to update the '$mypdf_list' 
    wrapper_hook.appendChild(list_wrap);

Upvotes: 4

Views: 301

Answers (2)

alexandreferris
alexandreferris

Reputation: 684

Use ajax for it.

The code will look slightly like this:

setInterval(function () {
    var url_to_fetch_pdfs = "www.yourdomain.com/fetch_pdfs.php";
    $.ajax({
        type: "POST",
        url: url_to_fetch_pdfs,
        cache: false,
        success: function(result){
            $("#dynamic_listwrapper").html("<hr>"+result);
        }
    });
}, 60000); // 1 Minute

In your PHP file you will fetch all the pdf downloads, the result in the ajax variable will be the echo in your PHP fetch file.

Ajax Documentation

Upvotes: 1

dave
dave

Reputation: 475

Thanks for all the advice everyone. Ajax call was the way. Here is my solution (which works) in javascript:

 // GET REFRESHED '$mypdf_list'
    // AJAX CALL
    var formdata = new FormData();
    formdata.append("update",'refresh');

    // create XMLHttpREquest object
    var xmlhttp = new XMLHttpRequest;

    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            // HANDLE RESPONSE HERE
            document.getElementById('dynamic_listwrapper').innerHTML = xmlhttp.responseText;
        }
    }

    xmlhttp.open("POST", "getMypdf_list.php");
    xmlhttp.send(formdata);

}

Upvotes: 3

Related Questions