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);
                    }
               });
            });
        });
  • possible duplicate of [inplace replace entire html document](http://stackoverflow.com/questions/2825586/inplace-replace-entire-html-document) – rubikonx9 Feb 25 '15 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. – CodeNameGrant Feb 25 '15 at 11:17

4 Answers4

-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

winhowes
  • 7,845
  • 5
  • 28
  • 39
  • tried this one and got: Uncaught TypeError: Cannot read property 'createDocumentFragment' of null – user3873031 Feb 25 '15 at 11:21
  • I edited my code (and tested). It should work now :) – winhowes Feb 25 '15 at 11:24
  • I also tried that and it's still resulting in blank page :( – user3873031 Feb 25 '15 at 11:25
  • Really? I made a jsFiddle and it's working fine there: http://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 '15 at 11:30
  • Yeah, I know that it should work but it doesn't. My code starts with (...) It's too big to paste it there – user3873031 Feb 25 '15 at 11:35
  • Bizarre. Can you try pasting the contents of your html into the jsFiddle and see if it works? http://jsfiddle.net/y5s7zkfg/3/ You don't need to publish the fiddle, just confirm yes or no? – winhowes Feb 25 '15 at 11:41
  • Why the -1, whoever did that? – winhowes Feb 25 '15 at 11:42
  • It works on jsFiddle, your edited solution gave some progress because the page is not blank. The problem is now, that the content is not replaced by the returned data (I can console.log it and it's fine). I don't know where the problem is – user3873031 Feb 25 '15 at 12:18
  • Can you share a jsFiddle so I can better diagnose? – winhowes Feb 25 '15 at 12:22
  • It's not about JSFiddle I suppose, but something wrong in my system. Because when I take the content from returned data and replace it in Dev Tools, everything looks fine. So the content is fine, the $('html').... method works, but I can't figure why the content is not being replaced on success – user3873031 Feb 25 '15 at 12:32
  • update: $('html').html(data); gives blank page, and $("body").html($(data).find("body").html()); not (but the content is not replaced) – user3873031 Feb 25 '15 at 12:34
  • I've found a solution (temporarly?): document.write(data) replaced the page with the returned content – user3873031 Feb 25 '15 at 12:37
  • Yeah `document.write()` will rewrite the page :) That's bizarre though that those other methods aren't working :/ – winhowes Feb 25 '15 at 12:48
  • 1
    Yeah, strange. I marked your answer as the correct one, because it contributed a lot to the solution. Thx! – user3873031 Feb 25 '15 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
    }
Cosmin
  • 2,184
  • 21
  • 38
-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!

Ila
  • 195
  • 13
-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");
});
kasper Taeymans
  • 6,950
  • 5
  • 32
  • 51