I have a Solspace FreeForm 4 form (free version) which I need to submit using Ajax. I can handle all the field validation in my JS but how do I handle a captcha error?
-
2Why not use something like snaptcha or honeepot so you don't need to validate as it'll pass by default unless the robot tries to fill it in.– CreateSeanNov 21, 2012 at 2:38
-
1Sean brings up a good point in that there are better options out there over captchas. Sean I'd consider adding that as an answer as it seems like a good option either way and could be helpful for someone in the future if not now.– NatetronnNov 21, 2012 at 6:33
-
1Just a quick note, for the ajax work - I'd look at something like jQuery Form Plugin. I've implemented on top of all sorts of EE forms - User profiles, Login & Registration forms...– Dave O'BrienNov 21, 2012 at 14:03
3 Answers
I've been using Snaptcha http://devot-ee.com/add-ons/snaptcha on my recent sites, I can attest that it works very well, No one enjoys filling out these captchas anyway, and their efficacy is doubtful anyway.
When a Freeform form is submitted with AJAX Freeform can provide JSON response containing errors or success, which can be used to display errors. This has worked well for me on previous versions of Freeform. The docs for the latest version of Freeform say that Freeform will detect AJAX automatically and provide a JSON response you can use to display user error/success feedback.
See the ajax
parameter in the documentation.
There is actually an example of ajax form submission with validation at the end of the documentation, too.
-
-
2Yes, it takes all the error messages that Freeform would normally show as a "system message" and returns them as JSON. Error messages such as "The captcha word you submitted is incorrect. Please go back and try again" or "In order to submit this form you must complete the captcha field" are included in the JSON as appropriate. Its basically the system message(s) and a status (error or sucess) returned as JSON so that you can use it as needed.– Alex Kendrick ♦Nov 21, 2012 at 19:15
The captcha message comes back when the form is successfully posted. You can grab it in the success function of the ajax call:
var form_data = $('#form_id').serialize();
$.ajax({
type: "POST",
url: 'desired_url',
dataType: 'html',
data: form_data,
success: function(responseText, statusText, jqXhr) {
if (responseText.includes("errors")) {
var msgArray = $.parseJSON(responseText);
var errorMessage = msgArray['errors'][0];
// do whatever you want with the errorMessage.
return false;
} else {
// continue
return false;
}
},
error: function(jqXhr, statusText, errorThrown) {
console.log(errorThrown);
return false;
}
});