Search code examples
javascriptjqueryasp.net-web-apireplaceallreplacewith

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:

<script>
    $(document).ready(function () {
        $("#btnGetData").click(function () {
            document.body.style.cursor = 'wait';
            $.ajax({
                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) {
                    $("body").remove;
                    $("body").append($(returneddata));
                },
                error: function () {
                    console.log('hey, boo-boo!');
                }
            }); // ajax
            document.body.style.cursor = 'pointer';
        }); // button click
    }); // ready
</script>

...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.HttpGet]
[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}",
        beginningHtml,
        top10ItemsPurchasedHtml,
        pricingExceptionsHtml,
        forecastedSpendHtml,
        deliveryPerformanceHtml,
        endingHtml);

    return new HttpResponseMessage()
    {
        Content = new StringContent(
            HtmlToDisplay,
            Encoding.UTF8,
            "text/html"
        )
    };
}

...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.


Solution

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

    $("body").empty();  
    $("body").append($(returneddata));
    

    but it would be better to use

    $("body").html(returneddata);
    

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