23

I have a little ajax call that calls rails:

    $.ajax({
        type: "POST",
        url: '...',
        data: ({    ...
                }),
        success:    function(response, status) {
                    console.log(status);
        }
     });

In the rails controller I'm simply deleting an entry from the database, and I simply want to return if it was successful or not. What's the best way?

Should I just return JSON in respond_to? If so, what exactly would you have it contain?

99miles
  • 10,942
  • 18
  • 78
  • 123

4 Answers4

31

Best way to signify success in this way is to put the following in your controller...

def destroy
  # ... your code ...
  respond_to do |format|
    format.json { head :ok }
  end
end
Dave Pirotte
  • 3,806
  • 21
  • 14
  • 4
    thanks! for the record, for a failure it might be something like: format.json { render :json => @obj.errors, :status => :unprocessable_entity } – 99miles Sep 25 '10 at 06:25
  • 1
    I read that just returning ok may not work: http://stackoverflow.com/questions/4791499/jquery-doesnt-call-success-method-on-ajax-for-rails-standard-rest-delete-answ – lulalala Jun 14 '12 at 10:33
  • I was using `format.json { head :no_content }` as I don't want to send any data. But browser was trying to redirect to an url after ajax success, which is unexpected. I replaced it with `format.json { head :ok }` and unnecessary redirection gone. – Amit Patel Aug 21 '12 at 07:05
  • 17
    This didn't work for me. I ended up having to render nil with a status code: `render json: nil, status: :ok` – Joshua Pinter Oct 24 '13 at 00:07
11

try this it's working for me

def destroy 
  ...        
  render json: {}, status: 200
end
El Fadel Anas
  • 1,581
  • 2
  • 18
  • 25
4

I found this shorter way to do the job:

def destroy
  # ... your code ...
  head :ok # this will return HTTP 200 OK to jQuery!
end
Eugene
  • 607
  • 3
  • 8
  • 12
  • This returns a 200 to jQuery along with a single space in the reponse. jQuery does not interpret this as a success. So it will return success but not call the success callback. – JaeGeeTee Aug 29 '16 at 02:47
  • Wow, this was actually patched. I stand corrected! – JaeGeeTee Sep 02 '16 at 14:39
0

When you execute your query it might be returning some code that says it executed succesfully to confirm that row was deleted. So you can return that just to make sure query was also executed successfully along with the ajax call.

sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
  • Right, I know if my query was successful or not, but HOW do you suggest returning that? For example: format.json { "false" } or render :nothing => true, or ..? – 99miles Sep 25 '10 at 06:15