views:

27

answers:

1

Hi!

I am calling a controller's create action via ajax so when the object saves successfully, the js response is triggered. However, if the object fails to save due to validation, then I want the response to be html. I hope to achieve this by not returning the js response in the else block (please see code below) but this produces a 406 Not Acceptable error.

Any ideas on how to do this?

I should also probably note that the reason why I want to do this is because I am unsure how to create an appropriate js response if the validation fails...

Thanks in advance!!! =]

Controller create action

respond_to do |format|
  if @person.save
    flash[:notice] = 'Successfully created.'
    format.html { redirect_to(@person) }
    format.js
  else
    flash[:error] = 'There are errors while trying to create a new Person'
    format.html { render :action => "new" }
  end
end
+1  A: 

If you are specifically requesting the js format in the URL, then you have to provide JS for your response. One option instead would be to not specify a format in the request, and then just filter your responses for xhr. Like so:

respond_to do |format|
  if @person.save
    flash[:notice] = 'Successfully created.'
    if request.xhr?
      format.js
    end
    format.html { redirect_to(@person) }
  else
    flash[:error] = 'There are errors while trying to create a new Person'
    format.html { render :action => "new" }
  end
end

This way, if you make a request without specifying ANY format, it will hit js first, IF it's an xhr request (ie, an AJAX request), whereas, if there is an error, it will return html, no matter what.

Does that make sense?

jasonpgignac
Ahhh, this is exactly what I was after for this situation! Thank you =]
Hadonkey Donk