aener
aener

Reputation: 23

Changing PHP variable from an <a href=""> link

I'm making a site using divs. I have one across the top with a row of links which I want to change what's in the main window. I would prefer to keep strictly to PHP and HTML and use a full page refresh as I am comfortable with them at current, rather than using an Ajax refresh as I don't have any knowledge of Ajax.

I don't want to use iframes. I thought the best way to do this would be as follows:

<div id="top">
<a href="news.html">News</a>
</div>
<div id="main">
<?php include($page); ?>
</div>

What I need is a way of changing the $page variable upon clicking the link. If this means changing the variable and then reloading the page then so be it.

A command following the logic of:

<a href="news.html" action="<?php $page="news.html"; ?>">News</a>

would be ideal! I thought about using a form, but it seems there should be an easier way.

Upvotes: 2

Views: 29618

Answers (4)

reformed
reformed

Reputation: 4780

You could also use

    $page = $_SERVER['PHP_SELF'];

At the top of the PHP script. If your page is "somepage.php" the above will output

    /somepage.php

as the value of $page.

To get rid of the slash and .php just use substr:

    $page = substr($_SERVER['PHP_SELF'],1,-4);

which will leave you with $page = somepage

Upvotes: 0

Andr&#233; Catita
Andr&#233; Catita

Reputation: 1323

If I understood correctly, to change the include on the fly, as you are talking, you need to use AJAX, otherwise you need a full refresh.

Send data back to the server, with a normal link.

<a href="page.php?page=newpage.html">link</a>

Then you can use the $_GET variable of PHP, which is a array that parse the parameters for a URL page.

Example:

$page = $_GET['page']
include $page;

If you use jQuery, or want to try a easy AJAX method, you can search for jQuery.load().

Upvotes: 1

Mike
Mike

Reputation: 781

you could use a GET request on the same page,

<a href="news.html?page=news.html">News</a>

This will cause a page refresh on click, with the value for the page variable passed to php, and accessible through

$page = $_GET['page'] //at this point, $page will be "news.html"

Upvotes: 1

Quentin
Quentin

Reputation: 943220

You can't change a variable, per se. Reloading the page means running the PHP program from scratch. You just have to provide it with different input. From a regular link, that is only possible through the URL.

<a href="foo.php?something=a_value">

Data in the query string is accessible via $_GET

echo htmlspecialchars($_GET['something']);

Upvotes: 4

Related Questions