Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda