Edgars Rozenfelds Edgars Rozenfelds - 2 months ago 9
Ajax Question

Humanizer gem human validation Rails 4 with Ajax, Jquery

I am using Rails 4 with Humanizer gem that checks if user is human.
So far so good. But now in one specific form I need to check if user is human before allowing to submit form.

So far I have googled but didn't find any source or idea to do such thing.

I have done these things:

Created function that reacts on humanizer answer field, so after typing answer all data is sent to controller to check if that answer is correct.

Data that I am sending to controller for checking is: humanizer question, humanizer question id, humanizer answer.

My form:

<%= form_for(@advertisement,:html => {:id=>"new_advertisement","data-parsley-validate" => true,:multipart => true}) do |f| %>


<%= f.label :humanizer_answer, @advertisement.humanizer_question %>
<%= f.hidden_field :humanizer_question_id ,:id=> "humanizer_question_id"%>
<%= f.hidden_field :humanizer_question , :value=>@advertisement.humanizer_question, :id=> "humanizer_question"%>
<%= f.text_field :humanizer_answer, :'data-validate_humanizer' => '/blocked/checkhumanizer',:'data-parsley-conditionalrequired'=>'["[name=\"paid\"]:checked", "false"]',:'data-parsley-validate-if-empty data-parsley-success-class' =>""%>

<button type="submit" class="blue-button btn btn-default" style="width:380px !important;"><%= t('add') %></button>


Script:

$( '[data-validate_humanizer]').blur(function() {
$this = $(this);
$.get($this.data('validate_humanizer'), {
question_id: $('#humanizer_question_id').val(),
question: $('#humanizer_question').val(),
answer: $(this).val()

}).success(function() {

alert("sucess");

}).error(function() {

alert("Error");

});
});


Controller:

def checkhumanizer
if params[:question_id].present? && params[:question].present? && params[:answer].present?

render :nothing => true, :status => 200
else
render :nothing => true, :status => 404
end

end


Routes:

resources :blocked do
collection do
get 'checkhumanizer'
end
end


Note: So far I have everything I should need to make a validation.But I have not a single idea to start with.

Possible solution: Is it possible to access humanizer locales where all questions and answers are located ? Is it a good approach or bad?

Thank You!

Answer

You can try this, using the humanizer methods in your model

def checkhumanizer
  if params[:question_id].present? && params[:answer].present?

    ad = Advertisement.new
    ad.humanizer_question_id = params[:question_id]
    ad.humanizer_answer = params[:answer]

    if ad.humanizer_correct_answer?
      render :nothing => true, :status => 200
    else
      render :nothing => true, :status => 404
    end

  else
    render :nothing => true, :status => 404
  end

end