Andrew
Andrew

Reputation: 43153

Rails: ensure that $.post from jQuery is received as format.json in Controller

I have a jQuery script that is trying to post data like so:

$.post({
    $('div#location_select').data('cities-path'),
    { location_string: $('input#city_name').val() },
});

This works, but for some reason the server receives it as an HTML request instead of a JS request. What gives? Here's the respond block in my controller:

if @city.save
    respond_to do |format|
        format.html { redirect_to @city }
        format.json { render :json => @city, :status => :ok }
    end
else
    respond_to do |format|
        format.html { render :new }
        format.json { render :json => { :error => "Incorrect location format, please input a city and state or country, separated by a comma." }, :status => :unprocessable_entity }
    end
end

How do you ensure that an Ajax request is hitting the Controller and being handled by the format.js responder?


Update: When I changed from $.post to $.ajax and specifically defined the data type it works:

$.ajax({
  type: 'POST',
  url: $('div#location_select').data('cities-path'),
  data: { location_string: $('input#city_name').val() },
  dataType: 'json'
});

Upvotes: 1

Views: 1133

Answers (1)

John Plummer
John Plummer

Reputation: 1044

Are you passing the format through from the route in routes.rb?

"controller/action/(.:format)"

Upvotes: 3

Related Questions