I have been looking from an hour but no luck, I have an JavaScript on-click function on HTML tag. The on-click function redirects me to an another page. The content on the other page will depends on the id passed in the JavaScript on-click event. The problem is I don't know how to access the id in my PHP file so that I can run SQL query to display the data. I don't want the id to be displayed in the URL either.
My HTML on-click element:
<h1 onclick="ContentPage(this.id)" value='.$id.'>'.$title.'</h1>
My javasript function:
<script>
function ContentPage(){
location.href = "show-content.php";
};
</script>
To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.
Can I use onclick in PHP? Wrong Interpretation of Onclick Event in PHP In addition to that, PHP handles server-side client requests and database connections. PHP has nothing to relate to the user side, on-screen interaction. So, we can not set an on click event of client-side javascript with a PHP function.
The onclick event attribute in HTML works when the user clicks on the button. When the mouse clicked on the element then the script runs. Syntax: <element onclick = "script"> Attribute Value: This attribute contains a single value script that works when the mouse clicked on the element.
You will learn. Trigger a legacy popup when a button is clicked.
There are many ways you can go...
Modify your function as such:
function ContentPage(id){
location.href = "show-content.php?id="+id;
}
The value of id will be in the $_GET
variable; specifically of index id
so on your page page,
$passedId = $_GET['id'];
JS
--<h1 id="myTitle_'.$id.'" class="clickNavigate" value='.$id.'>'.$title.'</h1>
then your JavaScript code becomes
jQuery(".clickNavigate").on("click", function(e) {
var myID = jQuery(this).attr("id");
var idParts = myID.split("_");
location.href = "show-content.php?id="+idParts[1];
});
Fast example using GET, you can also use POST
https://www.tutorialspoint.com/php/php_get_post.htm
HTML
<h1 onclick="ContentPage(this)" value='.$id.' id="myid">'.$title.'</h1>
JAVASCRIPT
<script>
function ContentPage(elem){
location.href = "show-content.php" + "?id=" + elem.value;
};
</script>
PHP
$id = $_GET["id"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With