Topic: Form validation via AJAX

Hi all,
I'm adding fields to a form using JavaScript and when I submit the form, if there are some errors during the validation, the form is reloaded and the fields added with JavaScript are lost.
I know that I could avoid this by replicating the validation in a JavaScript file hooking the submit action, but I would like to take advantage of the validation I set up in the model.
Is it possible to use it via AJAX?

Thank you.

Re: Form validation via AJAX

You can submit the form via AJAX and get your errors without leaving the page:

http://trevorturk.com/2010/08/24/easy-a … nd-jquery/

Are you using 3.X ? 

If so,  you can access the errors like so:

def create
  @yourmodel = Yourmodel.new(params[:yourform])
  unless @yourmodel.save
    respond_to do |format|
      format.js {
        xm = Builder::XmlMarkup
        xm.ul {
          @yourmodel.errors.full_messages.each do |msg| 
              xm.li {
                xm << msg
              }
          end
        }
        render(:text=>xm)
      }
      format.html { flash.now[:error] = 'Error Saving';  render :action => "new"  }
   end
end

To make the form submit via AJAX:

form_for @yourmodel, :remote=>true , :id=>'yourform'

To get the error messages into your browser, see that this javascript is included in the view with your form:

    $("#yourform").bind("ajax:success", function(event, data, status, xhr) {
      $("#error_div").html(data);
    });

Where error_div is a div where you display error messages.

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Form validation via AJAX

Thank you for your help, but I get an error:

NameError in MytestController#create
uninitialized constant MytestController::Builder

Do I need to include something?

Re: Form validation via AJAX

require 'active_support/builder' unless defined?(Builder)

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Form validation via AJAX

I can't hook the ajax:success ...
In the JavaScript Console I see the right response, but the the jquery bind dosen't works.
any idea?
Oh... I'm using Rails 3.0.9 with jQuery

Re: Form validation via AJAX

Hmmmm.....

Look at the HTML that is generated,  make sure the id of the form is the same as the id in the JavaScript.

Post the generated HTML

Also, are you using jquery-ujs ?

https://github.com/rails/jquery-ujs

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Form validation via AJAX

I'm doing some steps backward.
If I try to display a message as a result of an AJAX call, it isn't display in the page although I see it in the JS console as response.
In the controller :

 def create
  respond_to do |format|
    if @pay_check.save
      [...]
    else
      format.js 
    end

In the create.js.erb file

$('#errorlist').html(<p>Hello</p>)

the code is shown in the JS Console (as response) instead of executed:

$('#errorlist').html(<p>Hello</p>)

Re: Form validation via AJAX

Yes I'm using the same adapter.
When I try to hook the ajax:success I have the following code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src="/javascripts/rails.js?1319108688" type="text/javascript"></script>
<script src="/javascripts/application.js?1319108688" type="text/javascript"></script>
<script src="/javascripts/pay_check_form.js?1319559249" type="text/javascript"></script>
</head>
<body>

<h1>New pay_check</h1>

<div id="errorlist"></div>

<form accept-charset="UTF-8" action="/pay_checks" class="new_pay_check" data-remote="true" id="new_pay_check" method="post">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="&#x2713;" />
<input name="authenticity_token" type="hidden" value="k1Yhr5MVUIAK0vAa4pOKFI6lLrOTpc0YBz1i/MAiozw=" />
</div>
  
<div class="field">
...

In the pay_check_form.js I have ...

$(document).ready(function() {
...
  $("#new_pay_check").bind("ajax:success", function(event, data, status, xhr) {
    $('#errorlist').html(data);
  });

And this is what I get in the console:

<ul><li>Work hours can't be blank</li><li>Month is not included in the list</li><li>Month can't be blank</li></ul><respond_to?:to_text/><to_text/>

Re: Form validation via AJAX

How are you including your JavaScript ?

Try brute force:

<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jq … ery.min.js", "jquery.rails.js", "application.js" %>



Also,  I don't actually do anything with 3.X,  so I'm not sure what the default application.js has in it.  But if it has a $(document).ready,  you're stepping on it with your pay_check_form.js,   try moving the new_pay_check bind from pay_check_form.js into application.js.

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Form validation via AJAX

It is included properly.
I tried to move it but the behaviour is the same.

Re: Form validation via AJAX

I didn't see one of your earlier posts, are you still getting JavaScript rendered in your view instead of executed?

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Form validation via AJAX

Yes, and I think this is the problem

Re: Form validation via AJAX

http://www.alfajango.com/blog/rails-3-r … th-jquery/

From that link:

Sometimes, the JavaScript response does not execute as it should, and instead just returns the response as a string. This usually means there is some malformed JavaScript somewhere in the response. It’s annoying, but it won’t throw any visible JavaScript errors from the automatically-executed response.

$('#errorlist').html(<p>Hello</p>)

should be:

$('#errorlist').html('<p>Hello</p>')
Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Form validation via AJAX

if ajax:success doesn't work, try ajax:complete

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Form validation via AJAX

Oh... I know that the .html() need a string, it's my fault.

I'm trying with ajax:complete and I'm showing the status.
I see a "parsererror" and this is the response:

<ul><li>Work hours can't be blank</li><li>Month is not included in the list</li><li>Month can't be blank</li></ul><respond_to?:to_text/><to_text/>

Re: Form validation via AJAX

        render(:text=>xm.to_s)

This will get rid of the <respond_to?:to_text><to_text/>

Sorry, I've never run on a browser that complained,  what browser are you using?

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Form validation via AJAX

nope, I get the same error but the reponse is:

<ul><li>Work hours can't be blank</li><li>Month is not included in the list</li><li>Month can't be blank</li></ul><to_s/>

It seems it understands to append a "to_s" tag

P.S. I'm using FF 7.0.1 and Chrome 14.0 on Mac OS X

Re: Form validation via AJAX

Hmm,

I use FF 7.0.1,  but the last time I was messing with stuff FF was several versions older????

You could try this

str = xm.to_s
render(:text=>str)

So,  you're getting an error complaining that JavaScript can't parse the HTML?

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Form validation via AJAX

Never mind,  It's been a while, try this

render(:text=>xm.target!)

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Form validation via AJAX

Where is this parseerror comming from??

The call to .html()?

weird???

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.