406 Invalid error when using jQuery $ .post in Firefox but not in Safari or Chrome

I am using the jquery (1.3.2) $ .post command to invoke the ajax call for the rails server.

This code works fine in Safari and Google Chrome (Mac), but when I tried it in Firefox (3.5.7), I got a strange 406 Not Acceptable error.

When I look at the headers, Firefox indicates that it only accepts "text / javascript" responses. And the Content-Type response was 'text / html; encoding = UTF-8'.

In Chrome, the accepted types were 'application / json, text / javascript, /, text / javascript' and the Content-Type response was 'application / json; encoding = UTF-8'.

I tried to force the content type in rails to "text / javascript"

format.json do render :json => @races.to_json, :content_type => 'text/javascript' end 

The content type is really changed in Chrome, but not in Firefox, where it remains "text / html".

Here is the code I used to start the ajax call.

 $.post( "/locator", params, function(data){...}, "json" ); 

Is there something I can do to make this work in Firefox? Thanks

+4
source share
5 answers

Add the .json extension to your url in the mail call

 $.post( "/locator.json" ... 

Or (perhaps better) add the following to application.js to set headers for all ajax requests.

 jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} }) 
+4
source

There was the same problem. This seems to be a problem with firefox.

It works:

 jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript,application/javascript,text/html")} }) 

Credit goes to this blog.

Sincerely. Asbjorn Morell

+4
source

It doesn't make sense that different browsers see different HTTP headers. Perhaps this is a caching issue.

0
source

I use the contentType parameter during a call to $ .ajaxSetup to explicitly specify the type of content. This works in browsers: http://api.jquery.com/jQuery.ajax/

0
source

None of the above suggestions (atmorell, Paul Groves) fixed this for me ... then I found jquery $ .ajax doesn't work in firefox against rails (406 answer) (works in chrome and IE)

As I commented, the accepted answer will work! (using format.js, not format.json, and "render: text => item.to_json")

For the record, I am not making a direct call to .ajax; rather, I use jQuery.UI autorun:

 $(document).ready(function() { $("input#task_summary_task_wbs").autocomplete({ source: "/tasks/summary.js" }); }); 

and this is in my TasksController:

 # GET /tasks/summary.js def summary @tasks = Task.find(:all, :conditions => ['is_summary = true AND wbs like ?', "%#{params[:term]}%"], :order => :wbs) respond_to do |format| format.js { render :text => @tasks.collect {|t| t.wbs_name}.to_json } end end 

a la Railscast # 102.

-1
source

Source: https://habr.com/ru/post/1300967/


All Articles