21

Before going to the specific question I need to explain a few basic steps.

First, the application in question deals with the management of appointments online by customers.

The customer after filling a form with the treatments for the beauty center and providing their information comes to the confirmation page.

Now this page performing an ajax request to store the appointment on the database.

If everything is successful is shown a page containing the details of the appointment with the success message.

The problem is that the page is currently displayed only in the response, that is, in the tab network console browser.

So my question is simple: How can I replace the entire structure of the html page with actual one shown in the response?

I found a lot of questions on the web even on StackOverflow. But all of this is limited on an append to a div. I do not need to hang but also replace the <html>, how to rewrite the html page. I have no idea how to do this and I need some advice from you.

For completeness, this is the code that comes back to me ajax response html:

       $.ajax({
          'type': 'POST',
          'url': 'backend_api/ajax_save_appointment',
          'data': postData,
          'success': function(response)
           {
               console.log(response);
           },
           'error': function(jqXHR, textStatus, errorThrown)
           {
               console.log('Error on saving appointment:', jqXHR, textStatus, errorThrown);    
           }
       });
Martin54
  • 1,349
  • 2
  • 13
  • 34
Dillinger
  • 1,823
  • 4
  • 33
  • 78
  • 2
    if you're replacing the entire page, don't use AJAX! Just `POST` the data directly to the server and let the browser render the replacement page in its entirety. – Alnitak Nov 25 '15 at 10:40
  • I know this, but in this situation I am forced to use ajax. – Dillinger Nov 25 '15 at 10:49
  • forced how, exactly? – Alnitak Nov 25 '15 at 10:54
  • it's too long to explain here – Dillinger Nov 25 '15 at 11:02
  • Suppose you have a page that refreshes hourly. But the server it refreshes from reboots occasionally as well (other programmers exist, they reboot servers, it happens). But if the refreshing page tries to refresh during a reboot ... fail. Now you have a 404 dead page and have to manually refresh the page when you come back. But: If you had an AJAX refresher instead, you could put up a yellow banner on fail, and schedule the refresh for 10 minutes into the future (after the reboot). No more attention to the page. Ignore it forever. – TheSatinKnight Feb 03 '21 at 20:58

6 Answers6

33

If your response includes the <head> and <body> tags:

$("html").html(response);.

If not, and it's only content, then do:

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

L Ja
  • 1,384
  • 1
  • 11
  • 22
  • Yeah the html tag is included as I said, thank you! Have a good day :) – Dillinger Nov 25 '15 at 10:42
  • So your response is this? `......`? If thats the case, then use the first one, and **not** my 2nd (and Fribu's example). The thing you're doing with the 2nd one, is putting html tags in body tags. **This only applies if your response indeed is a FULL page.** – L Ja Nov 25 '15 at 10:43
  • @Dillinger it's unclear what (if any) scripts will work on the newly loaded content. Please consider my comment above and avoid using AJAX altogether. – Alnitak Nov 25 '15 at 10:43
  • Fair point, although OP was asking for just replacing the page. So I assumed the page wouldn't contain any scripts (Maybe just plain text?). – L Ja Nov 25 '15 at 10:48
  • @LJa if it doesn't contain any scripts, how's the _next_ page going to work? – Alnitak Nov 25 '15 at 10:52
  • @Alnitak A page doesn't need scripts to just display plain text though. – L Ja Nov 25 '15 at 11:00
  • when I pressed the back button in the browser then all of my ajax responses are displayed in HTML form instead of displaying web elements. How to solve this problem – CHARITRA SHRESTHA Oct 30 '19 at 03:25
12

if the response is the html content, you can use this line of code:

...
'success': function(response)
       {
           $("body").html(response);
       }
...

update:

this will be hard to replace the html tag, but what you can do:

...
'success': function(response)
       {
           $("html").html($("html", response).html());
       }
...

you parse the response with jquery, getting the content of html and replacing the content of the current html

Alexander_F
  • 2,831
  • 3
  • 28
  • 61
7

this question has already been treated here: Replace HTML page with contents retrieved via AJAX

Basically, you may try (My bad this is not working on IE):

document.open();
document.write(newContent);
document.close();

or, since you are using jquery

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

Regards

Community
  • 1
  • 1
AdZaf
  • 127
  • 8
  • if you'd read the comments, you'd have seen the notes saying this doesn't work on IE, and causes the new content to be appended (instead of replacing) in Chrome – Alnitak Nov 25 '15 at 10:53
  • I missed it.. but the second proposition is still valid. – AdZaf Nov 25 '15 at 10:56
  • This work for me like i am able to Replace the complete HTML with Ajax also j-query other function working without any issue... – Er Parwinder Hirkewal Jul 30 '20 at 18:08
  • there is diffrence with jquery , with the way javascript is execute if your document contains javascript with document ready event, the only way that it will start as REAL new page is by the document.write(newContent) approche ! – foxdanni Oct 30 '20 at 09:17
0

Perhaps you can use following code in your 'success'-function to redirect to a different route. window.location.href = 'http://host.local/path/to/appointment-details';

0

@JudgeProhet It seems to me that you do not need AJAX request for this purpose. There is no advantage in doing it this way. If the entire page is updated it could be done by an ordinary HTTP request. If you want to use AJAX, you could simply use JavaScript to redirect to new page, which contains appointment details.

$.ajax({
   'type': 'POST',
   'url': '/backend/ajax_save_appointment',
   'data': postData,
   'success': function(response)
   {
      console.log(response);
      // redirect browser to new location
      window.location.href = '/backend/appointment_details';
   },
   'error': function(xhr, status, error)
   {
      console.log('Error on saving appointment:', xhr, status, error);
      // display error message to the user
   }
});
0

I don't have enough reps to leave a comment (!!) but the UPDATE answer by @fribu-smart-solutions (https://stackoverflow.com/a/33914275/1428972) should be marked as the correct one, using:

$("html").html($("html", response).html());

This fully replaces the page via ajax. This does the job properly whereas others even using "html" doesn't fully work.

I know this is an old post but it just solved my problem on the same issue! :)