-1

I have an Ajax call:

callAjaxController: function(){
        var url = Routing.generate('ajax_price');

        $.ajax({
            type: "GET",
            url: url,
            cache: false,

            success: function (data, status) {
                // get the <body> markup to replace my actual body page
            }
        })
    },

In my Ajax response, I would like to get the <body> markup to replace my actual body page.

Is it possible? How can I do that?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Kevin
  • 4,823
  • 6
  • 36
  • 70

1 Answers1

0

Assuming your request retrieves the content of the body tag you want to use you can set the html() of the current body() element with the new content, like this:

success: function (data, status) {
    $('body').html(data);
}

Alternatively, if the response includes the <body> tag and all content within it, use replaceWith():

success: function (data, status) {
    $('body').replaceWith(data);
}

Also note that because you have destroyed all existing elements in the DOM you will need to use delegated event handlers, should you have any existing events that are handled in code.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • What if the response is a full html page including and elements – PHP Guru Oct 21 '20 at 19:24
  • In which case you'd be better off using `load()` and targeting the element you want to retrieve within the arguments you provide to the function. You should note that returning an entire HTML page to an AJAX request isn't good practice. – Rory McCrossan Oct 21 '20 at 19:26
  • The ajax is returning a full html page but I just want the body part like it says in the question. I tried $(html).find("body") but that doesn't work for some reason – PHP Guru Oct 21 '20 at 19:47