Mallander
Mallander

Reputation: 336

Getting content from another page with PHP

This is a question based purely on my own curiosity. I don't have a problem that needs answering, nor do I have any idea myself how this would be done.

I was wondering if it would be possible using PHP to get the contents from another page and display it in place of the current content on the page you're on. In a way, to try and avoid refreshing the page.

For example:

Say I have my "homepage", with a slider and some main information but nothing much more.

I then click on "About" and rather than it moving to another page and refreshing, it simply grabs the elements inside the main containing div on "About" and replaces the existing contents on the "homepage", keeping everything intact and it appears you've moved page even with the URL, but you've actually not moved.

Would this be possible, and if so would anyone be able to give a small explanation/a link to somewhere that I would be able to learn this side of Web Development (My next goal to learn). And more importantly, is it a good thing to do or are there some limitations/issues with doing this?

Upvotes: 1

Views: 350

Answers (3)

Jonas Köritz
Jonas Köritz

Reputation: 2644

PHP is Server side, so no manipulation of the page can be done after it has been loaded by the browser. You have to use JavaScript (AJAX) to load parts of the page on user action.

Take a look at jQuery

Upvotes: 1

Rudie
Rudie

Reputation: 53821

A lot of sites do that these days: Medium, Twitter, Youtube etc. Mostly big boys, because it's hard to get right.

Tech:

  • AJAX to get the contents of the next page
  • history.pushState() to change the URL

The back-end language (eg PHP) doesn't matter.

I don't know a tutorial on the whole, but finding ajax or pushState explanations is easy.

It's not a good practice though. Page loads exist for a reason. Browsers like explicit page loads.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

Yes, but not with PHP.

Let's suppose you have <div id="content"> wrapping your page's content.

You can use AJAX to load about.php, then parse the response to find <div id="content">, get its contents, and drop that in the current document's content area.

However, keep in mind that there are problems with this approach. For instance, what should happen if you click more than once before the new page has loaded? What happens to the URL, should a user reload the page?

Upvotes: 2

Related Questions