Lown Lown - 24 days ago 7
PHP Question

Trigger PHP function when click on image

I am looking for a way to trigger a PHP function after a click on image using only PHP. I know it's possible to do this using AJAX but I have to do it with PHP.

Any ideas? Thanks

Answer

Make the image a link:

<a href="somePage.php"><img src="someImage.jpg" /></a>

Then in somePage.php perform the functionality you need and direct the user accordingly:

<?php
    yourFunction();

    // display output or redirect
?>

Whether you use AJAX, a link, a form post, etc. the bottom line is that you need to make a request to the server-side code. This approach is certainly less ideal than simply making an AJAX request and keeping the user on the same page. But, failing that and not allowing the use of JavaScript at all, you need to use a form or a link to make a request.

The link can even be to the same current page with just a query string value indicating that you perform some function. For example:

<a href="thisPage.php?runFunction=true"><img src="someImage.jpg" /></a>

Then in the same page which displays the image:

<?php
    if (isset($_GET['runFunction'])) {
        yourFunction();
    }

    // display page as normal
?>

That way you don't need a redirect to bring the user back to the page. Depends on how you want to organize your code, really. Whether that functionality should be part of the same request or a separate resource. RESTful arguments aside, it's an option.

Comments