I’m facing an issue with my jQuery script when trying to post data as shown below:
$.post({
$('div#location_select').data('cities-path'),
{ location_string: $('input#city_name').val() },
});
Although this code works, the server inexplicably recognizes it as an HTML request instead of a JS request. What could be causing this? Here's the block in my controller that handles the response:
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
What steps can I take to ensure that an Ajax request is correctly reaching the Controller and being processed by the format.js
responder?
Update: Making a simple modification from $.post
to $.ajax
along with specifying the data type appears to resolve the issue:
$.ajax({
type: 'POST',
url: $('div#location_select').data('cities-path'),
data: { location_string: $('input#city_name').val() },
dataType: 'json'
});