• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 106
  • Last Modified:

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:


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.
1 Solution
Chris StanyonCommented:
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>


<a href="logout.php">Click here to logout</a>
elepilAuthor Commented:
Thanks, Chris. I just needed to confirm my thoughts, your comments helped.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now