Search code examples
ruby-on-railsruby-on-rails-3jsonujs

Rails: Manipulate rendered JSON when using UJS


I enhanced my app by allowing AJAX form submissions, using UJS. Here is my create#product action:

def create

    if Product.create params[:product]
        respond_to do |format|

            message = "New product created."
            format.html { redirect_to :back, :notice => message }
            format.js { render :json => { :status => true, :message => message } }

        end
    end

end

But I'm figuring out how to handle outputted JSON in my views/products/create.js.erb file??

I tried this simple console.log example, but without success (I mean, no console output):

$(function(){
    console.log(xhr.responseText);
});

Thanks in advance.


Solution

  • You could use:

    $('form.new_product').bind('ajax:success',function(event, data, status, xhr){
    
    });
    
    $('form.new_product').bind('ajax:error',function(event, xhr, status, error){
    
    });
    

    or even $('form.new_product').on(same_args).

    Just make sure new_product is the actual class of your form.