Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fail Ajax request in Rails?

When user clicks a specific item, I use jQuery's post method to update something in the database:

$.post("/posts/" + post_id + "/update_something", 
       { some_param: some_value }, 
       success_handler);

where update_something looks like this:

def update_something
  post = Post.find(params[:id])
  post.update_attributes(:some_field => params[:some_param])
  render :nothing => true
end

The problem is if update_attributes fails, the request still succeeds and success_handler is executed.

How could I cause the request to fail when update_attributes fails such that success_handler won't be executed?

like image 203
Misha Moroshko Avatar asked Feb 16 '12 05:02

Misha Moroshko


People also ask

How does AJAX work in Rails?

Ajax enables you to retrieve data for a web page without having to refresh the contents of the entire page. In the basic web architecture, the user clicks a link or submits a form. The form is submitted to the server, which then sends back a response. The response is then displayed for the user on a new page.

How rails send data using Ajax?

Use rails-ujs (no jQuery) Making an AJAX POST call with rails-ujs looks identical to making it with jQuery: Rails. ajax({ type: "POST", url: "/things", data: mydata, success: function(repsonse){...}, error: function(repsonse){...} })


1 Answers

Well, you have to add an error handler, and give it an error to handle. So, in your JavaScript:

$.post( "/posts/" + post_id + "/update_something",
        { some_param : some_value }
      )
  .done( successHandler )
  .fail( errorHandler )      // define errorHandler somewhere, obviously
;

And in Rails:

def update_something
  post    = Post.find params[ :id ]

  success = post.update_attributes :some_field => params[ :some_param ]

  head success ? :ok : :internal_server_error
end

Note: 500 may or may not be the appropriate error code here—choose whichever among the 400s and 500s is appropriate.

like image 191
Jordan Running Avatar answered Sep 30 '22 13:09

Jordan Running