Rahul

Rahul

  • 395
  • 3.8k
  • 1.9m

Form page with Recaptcha getting reload after Ajax call

Sep 10 2018 12:36 PM
Hi, I have a form with Google recaptcha which is being validated from client as well as server side without any issue. I am doing a AJAX post call to my api using jquery for validating captcha on server side and it returns response either success or fail. On failed response, I prevents the form to be submit and on success response, i allows form to go ahead and submit. Now the problem is, forms is getting reload, but not getting submit. I have mentioned my code below. I did a lot search and tried each and everything, but no success. Could anyone please help me out on this?
  1. <script type="text/javascript">  
  2. $(document).ready(function () {  
  3. $(".sfFormSubmit input[type='submit']").attr("disabled"true);  
  4. var captchaForm = $('.g-recaptcha').parents('form').first();  
  5. captchaForm.submit(function (e) {  
  6. var response = grecaptcha.getResponse();  
  7. if (response.length == 0) {  
  8. e.preventDefault();  
  9. grecaptcha.reset();  
  10. return false;  
  11. }  
  12. else {  
  13. e.preventDefault();  
  14. var self = this;  
  15. $.ajax(  
  16. {  
  17. url: "/api/Captcha/Validate/",  
  18. type: "POST",  
  19. dataType: 'json',  
  20. data: "=" + response //processData: false  
  21. }).done(function (result) {  
  22. var captchaResponse = jQuery.parseJSON(result);  
  23. if (captchaResponse.success) {  
  24. self.submit(); //return true;  
  25. else {  
  26. var error = captchaResponse["error-codes"][0];  
  27. $('#errStatus').html("RECaptcha error- " + error);  
  28. $('#errStatus').show(); //return false;  
  29. }  
  30. }).fail(function (xhr, status) {  
  31. var err = "Error " + " " + status;  
  32. if (xhr.responseText && xhr.responseText[0] == "{")  
  33. err = JSON.parse(xhr.responseText).message;  
  34. console.log(err);  
  35. $('#errStatus').html("RECaptcha api error- " + error);  
  36. $('#errStatus').show(); //return false;  
  37. });  
  38. }  
  39. }); });  
  40. function onReturnCallback() {  
  41. $(".sfFormSubmit input[type='submit']").attr("disabled"false);  
  42. }  
Thanks

Answers (1)