longlost10
longlost10

Reputation: 57

How to get value from a php onclick statement

I have the following line of code:

    echo '<INPUT TYPE="submit" name="delete" value="Delete account" onClick="return confirm('Are you sure you want to delete this account?')">';

How would I be able to determine whether the user entered yes or no?

Upvotes: 0

Views: 2094

Answers (3)

rekire
rekire

Reputation: 47945

You have a syntax error in your code you need to escape the inner ':

echo '<INPUT TYPE="submit" name="delete" value="Delete account"
   onClick="return confirm(\'Are you sure you want to delete this account?\')">';

You could add a small script with adds with activated js a flag to detect if the deletion was confirmed. E.g.:

<input type="hidden" name="js_active" value="false">
<script type="text/javascript">
document.getElementsByName('js_active')[0]="true";
</script>

So if the formular is transmitted and js_active is true you can guess that the user has confirmed the deletion. If it is false javascript is maybe deactivated and you cannot know if the deletion was confirmed.

Upvotes: 1

Wouter J
Wouter J

Reputation: 41934

PHP is server-side it doesn't do anything on the client. A click is on the client, so PHP can't handle this.

An onclick event is JavaScript, which is on the client-side. Read more about the onclick event in the Mozilla Docs.

The confirm() returns a boolean, true or false. true when the user clicks 'Yes', false when the users clicks on 'No'.

If you want to send the boolean to PHP you need to use AJAX requests, but I don't think you want it because you want to stop the submitting of the form.

Upvotes: 2

Gordon
Gordon

Reputation: 316969

Since confirm will return true or false depending on what the user clicked, you will "know" that the user clicked Yes, when the Request reaches your server because if the user clicked No, you are preventing the submission.

Apart from that, there is no way to find out what the user clicked unless you are modifying the request content on click, e.g. you will have to send the result of the click as a param to the server, either as part of the form or via a URL param. But note that this will only be sent when the user has JavaScript activated in the browser.

Upvotes: 0

Related Questions