Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace current page with ajax content

I have a page with a dialog window which sends ajax post data to server and receives a response. During development, there can be two responses - one regular (this is not the question) or one with an error. Server returns code 500 and a page with lot of debug informations. This is a regular page returned from a framework and contains some javascript code. I want to be able to display this error page in case it happens.

The problem is, I can not simply attach the returned result to body element or open a new link in a new page and load this error again. I simply get a html page instead of data and I have to display the page (in current window or in another one).

I am using jQuery.

like image 465
Bruce Avatar asked Dec 08 '10 12:12

Bruce


3 Answers

Configure jQuery ajax setup as follows:

$.ajaxSetup({
    error: handleXhrError
});

where handleXhrError function look like this:

function handleXhrError(xhr) {
    document.open();
    document.write(xhr.responseText);
    document.close();
}

See also:

  • Handling of server-side HTTP 4nn/5nn errors in jQuery
like image 83
BalusC Avatar answered Nov 05 '22 15:11

BalusC


You may also try to use data URL's, the latest versions of the major browsers supporting it:

function utf8_to_b64( str ) {
    return window.btoa(unescape(encodeURIComponent( str )));
}

function loadHtml(html)
{
    localtion.href='data:text/html;base64,'+utf8_to_b64(html);
}

This way, you can load any html page you want in runtime.

like image 3
Calmarius Avatar answered Nov 05 '22 16:11

Calmarius


In your ajax callback:

success: function (data) {
   $("html").html($(data).find("html").html());
}

That will replace the entire page's HTML content with the one received from your AJAX request. Works in Chrome... not sure about IE.

Despite that, I'm not sure why you'd want to include the <head> section... but you can easily modify the above to display just what's in the body of the AJAX response, and append it to a div or even a lightbox. Much nicer.

like image 2
David Tang Avatar answered Nov 05 '22 14:11

David Tang