0

I'm trying to get data from Controller while clicking something. I get the response and success, but the response data returns the whole page(returned content is perfectly O.K.). I can't figure out how to replace the current page with the returned data. When I use .html on the top most element in the tree I get blank page like the returned data was not there (but the whole data is visible via console.log(data), it starts with ). How can I replace the current page with the new whole page content ajax returned? I'm doing it like this and it doesn't work:

JavaScript:

$(document).ready(function(){
            $(document).on('click','#name',function(){  
                $.ajax({
                    url: "{{path('myPathOne',{'status' : 'ONE'})}}",
                    type: "POST",
                    cache:false,
                    data: { 'status' : status },
                    success: function(data) {
                        $(document.body).html(data);
                    }
               });
            });
        });
2
  • possible duplicate of inplace replace entire html document
    – rubikonx9
    Feb 25, 2015 at 11:13
  • Replacing the whole page, seems impractical. It would be better to add your AJAX URL to an exception file somewhere in your project, so that when it returns the data to the page, it only returns the data you want not surrounded by the header/footer/etc. Are you using Spring? if so, please include your controller method. Feb 25, 2015 at 11:17

4 Answers 4

-1

To replace the body, you can do what you're currently doing, but to replace the entire html, you should do:

$("html").html(data);

Edit

Another approach:

$("body").html($(data).find("body").html());
$("head").html($(data).find("head").html());

Edit2

You can also use document.write(data) as that will replace the old document with new html if called after the page has loaded. Details here: https://developer.mozilla.org/en-US/docs/Web/API/Document/write

14
  • tried this one and got: Uncaught TypeError: Cannot read property 'createDocumentFragment' of null Feb 25, 2015 at 11:21
  • I edited my code (and tested). It should work now :)
    – winhowes
    Feb 25, 2015 at 11:24
  • I also tried that and it's still resulting in blank page :( Feb 25, 2015 at 11:25
  • Really? I made a jsFiddle and it's working fine there: jsfiddle.net/y5s7zkfg/1. Can you tweak this fiddle to match your code better (then we can more easily work out what's going wrong)
    – winhowes
    Feb 25, 2015 at 11:30
  • 1
    Yeah, strange. I marked your answer as the correct one, because it contributed a lot to the solution. Thx! Feb 25, 2015 at 13:16
-1

Why do you want to do that? It doesn't feel right. But, anyway...

You can try with:

$('body').html( your html )

If you're using C# MVC, before returning HTML which can be written in Razor, render it in your controller

     protected string RenderPartialViewToString(string viewName, object model)
     {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
    }

Usage:

    public ActionResult Index()
    {
        var model = new MyModel();

        var html = RenderPartialViewToString("SomeView", model);           

        //return
    }
-1

Your data is a full html page right? I mean with <html> and <head> tags? If so you could try to find the body in the returned data and get it's html. Then fill your current body with the new html content of the received body.

This is not a good method though because you are receiving too much data. To do this more efficient you have to make changes server side so only the required data is send back (ie only the html content from the body).

ps: I did not tested this but it should work.

$.ajax({
    url: "{{path('myPathOne',{'status' : 'ONE'})}}",
    type: 'POST',
    cache: false,
    data: {'status': status},
})
.done(function(data) {
    newbody=$(data).find('body').html();
    $('body').html(newbody);
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});
7
  • This doesn't solve the problem that the head might be different
    – winhowes
    Feb 25, 2015 at 11:42
  • If the head needs to be different you don''t use ajax... then you just need to redirect to a new page. Feb 25, 2015 at 11:45
  • That's not true. Facebook and other sites replaces their <head>'s fairly frequently, because it saves time over a full page refresh/redirect
    – winhowes
    Feb 25, 2015 at 11:46
  • @winhowes: if you say so, can you give me an example? Feb 25, 2015 at 11:53
  • Facebook changing their <title> to indicate you have a notification.. but we're getting off topic
    – winhowes
    Feb 25, 2015 at 11:55
-1

try modifying

$.ajax({
                url: "{{path('myPathOne',{'status' : 'ONE'})}}",
                type: "POST",
                cache:false,
                dataType: 'json'
                data: { 'status' : status },
                success: function(data) {
                    $(document.body).html(data);
                }
           });

and then use this to populate data

$(document).html(data);

document indicates the current document. Hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.