Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access id passed via onclick in php

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>
like image 563
sach jot Avatar asked Apr 05 '18 17:04

sach jot


People also ask

How do I get the clicked element id?

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 you use onclick with PHP?

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.

What is onclick attribute?

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.

What is it called when a person clicks a button on a form displayed by your JavaScript?

You will learn. Trigger a legacy popup when a button is clicked.


2 Answers

There are many ways you can go...

Based on your current approach--

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'];

Another approach -- not using inline 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];

});
like image 128
Rushikumar Avatar answered Oct 09 '22 00:10

Rushikumar


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"];
like image 27
Chico3001 Avatar answered Oct 09 '22 00:10

Chico3001