Shripad Krishna
Shripad Krishna

Reputation: 10498

Jquery AJAX: How to display the Flash error message when validation on the server side fails?

I am using the Jquery form plugin to submit the form via ajax. I have set up validations on the server side in my models. Now when the validation fails i want to display the same flash[:error] message to the user using ajax. If the validation succeeds I can display the flash[:notice] as it is available after the request is completed. How do i go about displaying flash[:error]?

Upvotes: 2

Views: 3193

Answers (2)

Shripad Krishna
Shripad Krishna

Reputation: 10498

I found this.

https://github.com/augustl/live-validations/wiki

If anyone has a better solution, please do post, and I will accept it.

Upvotes: 0

BrendanDean
BrendanDean

Reputation: 285

Return an HTML error status from your Rails app. In the .ajaxForm() options, set the 'error' callback to handle error statuses.

Here's what your Rails controller might look like:

def update
  @widget = Widget.find(params[:id])

  if @widget.update_attributes(params[:widget])
    respond_to do |format|
      format.js { head :ok }
    end
  else
    respond_to do |format|
      format.js { render :json => @widget.errors.full_messages.join(' '), :status => 400 }
    end
  end
end

And here's what your .ajaxForm() call might look like (same goes for .ajaxSubmit()):

$('form.ajax').ajaxForm({
  success: function(data) {
    /* response for success */
  },
  error: function(data) {
    /* Display validation message response from Rails app */
    $('form.ajax').prepend('<p class="errors">' + data.responseText + '</p>');
  }
});

You can read more about the error callback in the jQuery API.
Paydrotalks also has a good tutorial on refactoring these types of responses.

Upvotes: 4

Related Questions