-1

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.

Community
  • 1
  • 1
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

5 Answers5

6

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.

jlars62
  • 7,183
  • 7
  • 39
  • 60
0

Since you sending content type text/html your code should work as it is.

Try using Jquery.parseHTML function like this

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

Also you have a mistake in line

$("body").remove; 
//it should be empty() since remove() remove all the content including body it self
$("body").empty();

Link: https://api.jquery.com/jquery.parsehtml/

printfmyname
  • 983
  • 15
  • 30
0

You can do this by just using $.get() and .html(). Your .remove call would not have worked because of a syntax error (missing parentheses) and because .remove() would have removed the body altogether, so that you could not have appended anything to it afterwards. You would have had to do something like

$(document).append($('<body>').append(returneddata));

in order to re-create the BODY node and appending data to it.

Also, you should put the cursor reset code in the .always handler, though, otherwise it will be set and reset before the .get or .ajax call has a chance of executing.

In general,

console.log('this is executed first');
$.get('...', function(){
    console.log('this should be executed third... sooner or later');
});
console.log('this is almost certainly executed second');

So your code could be:

$('#btnGetData').on('click', function() {
    $('body').css({ cursor: 'wait'});
    $.get(
          '@Url.RouteUrl(routeName : "QuadrantData", routeValues : new { httpRoute = true , unit = "ABUELOS", begdate = "2016-08-20", enddate = "2016-08-27"  })'
            )
    .done(function(data) {
       // Replace 
       $('body').html(data);
    })
    .fail(function() {
       // Always plan for errors. Murphy rules.
       alert("error");
    })
    .always(function(){
        $('body').css({ cursor: 'pointer'});
    });
})

This is a fiddle of the above.

LSerni
  • 55,617
  • 10
  • 65
  • 107
0

Although you already use jquery, you don't really need to use it for this. In order to replace the html of the body element with html stored in the variable newHTMLstring, put this in your callback function:

document.body.innerHTML = newHTMLstring;

If you want to clear the html of the body element first, just set .innerHTML to an empty string:

document.body.innerHTML = '';

This vanilla js is faster and works in every browser.

Tomas Langkaas
  • 4,551
  • 2
  • 19
  • 34
0

You can directly set your ajax result to body as below:

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

Still it is not working then make sure jquery is loaded properly and also write your script on document ready,

$(document).ready(function(){

// Your AJAX call request

});