How to execute PHP code from a JavaScript function

I'm new to PHP, so I'm kind of groping my way around.

Let's say I have a link that says "Log Out". When clicked, I need to unset() a PHP variable:

unset($_SESSION['userLoggedIn']);

Open in new window


But the anchor tag and PHP are different "realms". Is the only way to do this to redirect to a PHP page with a query parameter like:

<a href="location.href='somePage.php?action=logout'"/>

Open in new window


and then unset() the variable? That's the only thing I can think of, but I'd like to know if experienced PHP developers have a more graceful way of doing this without a page reload. Thanks.
elepilAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
You can make a call to the server (php code) using Javascript in a few ways, such as AJAX, but usually if you're doing a log out, then you want the page to refresh - assuming there is some difference to your page between logged in and logged out users.

You don't have to call a script with a querystring - you could just call a new page - logout.php for example.

And if you're using an <a> tag for a link, then you don't ned the location.href - you just drop in the target directly:

<a href="somePage.php?action=logout">Click here to logout</a>

or

<a href="logout.php">Click here to logout</a>
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
elepilAuthor Commented:
Thanks, Chris. I just needed to confirm my thoughts, your comments helped.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.