How can I update php variable in HTML document without refreshing the whole page?

I have a web page that displays a list of files (pdf) that I have uploaded to a MYSQL database. When I upload a new file, I would like to automatically update this list to add the new file I downloaded without refreshing the entire web page.

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

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

      

I tried changing the div 'dynamic_listwrapper and then replacing it with a new one using javascript in the hopes that the updated mypdf_list variable gets updated. But it didn't work.

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);

      

+3


source to share


2 answers


Thanks everyone for the advice. Ajax called. 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);

}

      

+2


source


Use ajax for this.

The code will look something 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 file PHP

you will get all pdf uploads, result

in ajax variable will be echo

in your PHP fetch file.

Ajax Documentation

+1


source







All Articles