Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load a new page using ajax

Tags:

ajax

load

I am new to ajax and i wanted to know if we can load a complete new page and not just a part of it using ajax. Please give a small example script for understanding if this is possible. Here i am trying to display only one url to user while i change from one page to another when he clicks on any of the links in the page.

like image 242
Srk Avatar asked Oct 30 '25 03:10

Srk


2 Answers

You can of course request for a new page and load it via body.innerHTML = ajax.responseText;

I would strongly recommend against this though for reasons outlined in this post: Why not just using ajax for Page Requests to load the page content?

The whole premise really is that with AJAX you don't need to reload the whole page to update a small percentage of that webpage. This saves bandwidth and is usually much quicker than reloading the whole page.

But if you are using AJAX to load the whole page this is in fact counterproductive. You have to write customised routines to deal with the callback of the AJAX data. Its a whole lot of extra work for little to no increase in performance.

General rule for where to use AJAX: If your updating >50% of your page, just reload, else use AJAX.

You will not only need to request for the new page, but then also take care of ensuring the old styles on the current page are removed and don't interfere with the new page. Theres all sorts of problems associated with what your trying to do. It's possible, but I recommend not to do it.

edit: actually you might be able to just do document.write(ajax.responseText) which should take care of overwriting everything in the document, including css styles etc. Though still don't recommend it.

like image 127
Gary Green Avatar answered Nov 01 '25 12:11

Gary Green


When you're finished with processing the AJAX request simply use this JS line:

window.location.replace('<URL of the new page>');

This has exactly the effect of loading the new page via

<a href="<URL of the new page>">...</a>.
like image 23
Tijger Avatar answered Nov 01 '25 13:11

Tijger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!