Search code examples
ruby-on-railsajaxerror-handlingresponse

What does "Nil location provided. Can't build URI." mean when executing AJAX request in rails?


I have js file:

$('#some_btn').click(function() {    

    var valuesToSubmit = $('#some_form').serialize();
    var url = $('#some_form').attr('action');

    console.log("VALUE: " + valuesToSubmit);
    console.log("URL: " + search_url);

    $.ajax({
        type: 'POST',
        url: url, //sumbits it to the given url of the form
        data: valuesToSubmit,
        dataType: "JSON",
        success: function(data) {

            console.log("saved");
            console.log(data);

        }
    });

    return false;
});

Controller action which responses:

def some_action()

  ...

  @response = {resp: "ack"}

  respond_with @response do |format|
    format.json { render :layout => false, :text => @response }
  end

end

Route:

post '/abc/some_action', to: 'abc#some_action'

But after executing it I receive:

ArgumentError
Nil location provided. Can't build URI.


@response = {resp: "ack"}

respond_with @response do |format| # <--- Error here
  format.json { render :layout => false, :text => @response }
end

Solution

  • respond_with expects an AR object from which a route could be deduced.

    Change with:

    @response = {resp: "ack"}
    
    respond_to do |format|
      format.json { render json: @response }
      format.js   { render json: @response }
    end
    

    an alternative is to force the controller to render only json for a particular action. Weird because it means you were unable to send the proper request.

    But in this case:

    respond_to :json, :only => :some_action
    

    In your action:

    render json: @response