Michael St Clair
Michael St Clair

Reputation: 6625

How to check if link (a) submit button is clicked

How do I check with PHP if this code has been clicked so I can use it in an if statement?

<form id="rating" action="index.php" method="post">
    <a href="#" onclick="document.getElementById('rating').submit();">Rating</a>
</form>

So if it is clicked I want to use this query:

if () {
$result = mysqli_query($con,"SELECT * FROM users WHERE `approved` = 1 ORDER BY `rating`");
}

Upvotes: 0

Views: 1623

Answers (2)

Gunr Jesra
Gunr Jesra

Reputation: 110

So since your current form doesn't submit any data i like the technique of if multiple buttons are inside a form each should have its propper name and a type of submit and on php you check like if (this button was pressed then) else if (this button was pressed then) else (redirect in none or what ever you need to do when landed)

your form, i changed the ahref to an input type submit with the name of button

<form id="rating" action="index.php" method="post">
      <input type="submit" name="button"
       onclick="document.getElementById('rating').submit();">Rating
</form>

the php action should look like this, you can later implement ajax calling here

    if (isset($_POST['button']) === true && empty($_POST['button']) === tre) 
    {
    $result = mysqli_query($con,"SELECT * FROM users WHERE `approved` = 1 ORDER BY `rating`");
    }

Upvotes: 0

maxton
maxton

Reputation: 392

You would have to add an input, like <input type="hidden" name="hidden_element" value="data"/> to your form, otherwise there is no POST data for the server to receive.

Then in the index.php script you can check if $_POST['hidden_element'] is set.

For your example:

if (isset($_POST['hidden_element']) {
$result = mysqli_query($con,"SELECT * FROM users WHERE `approved` = 1 ORDER BY `rating`");
}

Upvotes: 4

Related Questions