B. Clay Shannon B. Clay Shannon - 11 months ago 48
Javascript Question

How can I replace the entire HTML of a page, or its body content, via an AJAX call's success callback?

I need to replace the entire HTML of a page, or its body content (rather than append more html to the existing content).

The accepted answer here showed me how to return data, but adding it to "body" doesn't quite work. This is the jQuery I have now:

$(document).ready(function () {
$("#btnGetData").click(function () {
document.body.style.cursor = 'wait';
type: 'GET',
url: '@Url.RouteUrl(routeName : "QuadrantData", routeValues : new { httpRoute = true , unit = "ABUELOS", begdate = "2016-08-20", enddate = "2016-08-27" })',
contentType: 'text/plain',
cache: false,
xhrFields: {
withCredentials: false
success: function (returneddata) {
error: function () {
console.log('hey, boo-boo!');
}); // ajax
document.body.style.cursor = 'pointer';
}); // button click
}); // ready

...So you can see I'm trying to first remove the html in the body, and then append the returned data to the body.

This REST method returns the html I want:

[System.Web.Http.Route("{unit}/{begdate}/{enddate}", Name = "QuadrantData")]
public HttpResponseMessage GetQuadrantData(string unit, string begdate, string enddate)
_unit = unit;
_beginDate = begdate;
_endDate = enddate;
string beginningHtml = GetBeginningHTML();
string top10ItemsPurchasedHtml = GetTop10ItemsPurchasedHTML();
string pricingExceptionsHtml = GetPricingExceptionsHTML();
string forecastedSpendHtml = GetForecastedSpendHTML();
string deliveryPerformanceHtml = GetDeliveryPerformanceHTML();
string endingHtml = GetEndingHTML();
String HtmlToDisplay = string.Format("{0}{1}{2}{3}{4}{5}",

return new HttpResponseMessage()
Content = new StringContent(

...but it appends the returned html rather than replacing it - the original body html is intact, and the returned html appears below it at the bottom of the page.

How can I replace, rather than append, this html? I tried replacewith and replaceall, but these didn't work for me.

Answer Source

remove() will remove the body element (instead of just clearing it out). You can use this to match what you are trying to do


but it would be better to use


You also may want to look into the jQuery load() function which will place the html into the element(s) for you.