0

I am trying to add reCaptcha v2 to an HTML form. When the submit button is clicked, a PHP file is invoked which calls the reCaptcha API.

If the reCaptcha is unsuccessful, I want to call the alert function inside the HTML page from the PHP file.

I have researched a lot but I couldn't find anything for my use case. This post shows how to show alert inside PHP not inside an HTML file.

Right now when I click submit without doing reCaptcha, I've encountered a blank PHP page, but I expect to remain in the HTML form without deleting the form content and show an alert message asking the user to complete reCaptcha.

Thanks in advance!

Amir
  • 317
  • 5
  • 18

1 Answers1

0

That's not how this works. There's a separation of server and client side code. PHP runs on the server, then sends its results back to the browser on the client -- that is, it sends back the HTML / Javascript / CSS / etc. that the browser will show. You cannot submit a form to a PHP file and then expect PHP to call a JS function on the client side.

You should be doing this kind of validation on the client size in the first place. That means you shouldn't be waiting until the data has gotten to the PHP script before validating; you should validate that the reCaptcha is filled out with JavaScript, and if not, don't submit the form at all.

IceMetalPunk
  • 5,476
  • 3
  • 19
  • 26
  • I see! so I have to add the php code that calls the API inside my html file and submit the form upon successful completion of reCaptcha. But isn't that a security risk since the php code would have a secret key to access the api? – Amir Jul 09 '19 at 19:33
  • Wait, what? You shouldn't need any API calls to determine if a field is empty or not. Either way, PHP code is not visible to the client, so it's not too terrible to have the API key inside PHP code. (Though best practice is to store your keys in a file outside your web root and load them in with something like `file_get_contents`, just in case someone gets access to your PHP files directly.) – IceMetalPunk Jul 09 '19 at 19:36
  • yeah for reCaptcha there an API request that determines if the box is checked! – Amir Jul 09 '19 at 19:46
  • Ah, I see. In that case, you have three options: submit the form via AJAX in your JavaScript, use the client-side JS library for reCaptcha instead of the PHP one, or live with the page reload (and just output the submitted values into the inputs' `value` attributes if the reCaptcha fails, with `echo`). – IceMetalPunk Jul 09 '19 at 19:51