Allow form to send POST request but prevent page from reloading - Javascript

Charlie Cureton

I am working on a signup form with an integrated v2 reCAPTCHA and I ran into the issue that when submitting the form which includes the reCAPTCHA, it is reloading the page. I have a php function to validate the reCAPTCHA:
if (isset($_POST['g-recaptcha-response'])) {
  function CheckCaptcha($userResponse) {
    $fields_string = '';
    $fields = array(
        'secret' =>' 6LcGWeEcAAAAAMALbpP873Pt40Wgwn6e0SuVn7EV',
        'response' => $userResponse
    );
    foreach($fields as $key=>$value)
    $fields_string .= $key . '=' . $value . '&';
    $fields_string = rtrim($fields_string, '&');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);

    $res = curl_exec($ch);
    curl_close($ch);

    return json_decode($res, true);
  }
  $result = CheckCaptcha($_POST['g-recaptcha-response']);

  if ($result['success']) {
      echo 'Success!';

  } else {
     echo 'Error';
  }
}

When the form submits it gives a POST variable g-recaptcha-response to the page it's on as there is no action attribute to the form

So, I need to get the POST request but I can't let the page reload because that would get rid of other data on the page. I tried using event.preventDefault(); when the form is submitted, but that also prevented the form from submitting the POST variable.

I have no idea how I would get the POST variable through javascript because the reCAPTCHA is not actually an input.

But if there was a way to get the value of the reCAPTCHA through javascript, then I could use ajax to send the POST request to the function.

Charlie C

If you include the query strings in the script url:

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"async defer></script>

then you can use grecaptcha.getResponse as it says in the google reCAPTCHA documentation:
https://developers.google.com/recaptcha/docs/display

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"async defer></script>
<script type="text/javascript">
  var verifyCallBack = function(response) {
    alert(response);
  };
  var widgetId;
  var onloadCallback = function() {
    widgetId = grecaptcha.render('recaptcha', {
      'sitekey' : 's',
      'theme' : 'light'
    });
  }
</script>

<form>
  <div id="recaptcha"></div>
  <input type="submit" name="submit" value="submit">
</form>

$('form').submit(function(e) {
  e.preventDefault();
  var response = grecaptcha.getResponse(widgetId);
  $.ajax({
    url: 'validate_captcha.php',
    type: 'POST',
    data: {'g-recaptcha-response': response},
    success: function(data) {
      alert(data);
    },
    error: function(error) {
      alert(error);
    }
  });
});

And then in validate_captcha.php:

<?php
if (isset($_POST['g-recaptcha-response'])) {
  function CheckCaptcha($userResponse) {
    $fields_string = '';
    $fields = array(
        'secret' => 'secret_key',
        'response' => $userResponse
    );
    foreach($fields as $key=>$value)
    $fields_string .= $key . '=' . $value . '&';
    $fields_string = rtrim($fields_string, '&');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);

    $res = curl_exec($ch);
    curl_close($ch);

    return json_decode($res, true);
  }
  $result = CheckCaptcha($_POST['g-recaptcha-response']);

  if ($result['success']) {
      echo 'success';

  } else {
     echo 'error';
  }
}
?>

So now in your javascript, you can use the data variable inside success:function(data) in an if statement:

if(data == 'success') {
  registerUser(name, email, password); // not a real function, just an example
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to prevent page from refreshing after JavaScript fetch post request?

How to prevent page from reloading after form submit - JQuery

How to send form values to php using javascript without reloading the page

Prevent page form reloading after reroute Laravel

Python POST request without reloading the page

Django. POST request after reloading a page. Sign up form

Prevent modal from reloading after form submission

Prevent form reloading from parent to child in React

Send post request with Javascript

Submit form without page reloading, and link to javascript

Django: How to prevent a page from reloading when I click button with Ajax/Javascript? (not jQuery)

Send Post Request from Windows Form C#

Send a post request from HTML form to NodeJS app

how to send form values to php using AJAX without reloading page?

Django/Js: how to post a form without reloading whole page

Submit form on same page without reloading and use POST variable

Send dictionary via http post request from Javascript to python

form is not reloading current page

Prevent page from reloading after onchange a select menu

Allow to send special characher in the url while doing Post request from UI side

How to send POST request without using form

axios post request to send form data

How to send form with ajax post request with rails

Send JSON Post Request to Contact Form 7

How to send form data in a POST request in Ballerina?

Python - Unable to Send Post Request to login form

Cannot send a POST request in HTML Form

Ajax send post request to the current page php

Javascript form post to another page

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive