Search code examples
javascripthtmlxmlhttprequest

reload page with XMLHTTPREQUEST POST response


i have an XMLHTTPREQUEST, and the request returns me a string with an HTML page that i want to charge on the page (the HTML contains Js and CSS) but i dont know how to do this. Here is my code:

xhr.onreadystatechange= function(){
      if (xhr.readyState ===4){
        if (xhr.status ===200){
            try{
                var data = JSON.parse(xhr.responseText);
                if(data.success){
                //.......here i obtain the HTML with xhr.repsonse;
                }else{
                    toastAlert(1,data.msg_response);
                }
            }
            catch{
                console.log("......")
            }
        }else{
            toastAlert(1,"......");
        }
      }
    };

Solution

  • You can use innerHTML property of DOM element to set have the response string parsed and added to DOM.

    MDN Link: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

    Example:

    document.getElementById('container').innerHTML = '<div>XHR Response...</div>';
    

    This approach will not do a full page refresh, but it will allow you to do some basic page content reloading using AJAX. I encourage you to take a look at Turbolinks project: https://github.com/turbolinks/turbolinks

    Cheers.