Rails render partial Ajax Error BUT correct response shown in Debugger

ajax, javascript, ruby-on-rails

Solution

You do not explicitly specify the `dataType` option for `jQuery.ajax` so jQuery infers it to be `script` (relying on MIME type served by Rails). Since `JAVASCRIPT TEMPLATE !` is not a valid Javascript statement, parser error is thrown. There are two options to get `success` callback called instead of `error`:

Explicitly specify `dataType` as `text`:

jQuery.ajax({
    type: 'POST',
    dataType: 'text',
    // ...
});

Or return valid Javascript from controller:

respond_to do |format|
  format.html # show.html.erb
  format.js { render :inline => "{}" }
end

Problem

I'm trying to trigger an additionnal ajax query on an existing link using unobstrusive Javascript. The Query is going to the server and processed, returning for the test the string "javascript template ok". But, the ajax "success" function is never called. In place, it is the "error" function that is triggered... I looked in the Chrome Debugger and I can see the response text coming back from the server, but never is the "success" method called... :-( My call is ``` jQuery.ajax({ type: 'POST', success: function(response) { $("#details").html(response); console.log(response); }, error: function(){ alert("Error\nData could not be retrieve from the server"); }, url: '/treeview/show/1538.js', cache: false, }); ``` (url is harcoded in this example). The same Url in the browser gets the correct data with no layout :-) Removing the ".js" in the url returns the html template with layout and the update of the "details" div is achieved correctly... The controller is ``` respond_to do |format| format.html # show.html.erb format.js { render :inline => "JAVASCRIPT TEMPLATE !" } end ``` Thank you EDIT : Here is the object returned from the ajax query (first argument of error: function(jqXHR) ): ``` Object abort: function ( statusText ) { always: function () { complete: function () { done: function () { error: function () { fail: function () { getAllResponseHeaders: function () { getResponseHeader: function ( key ) { overrideMimeType: function ( type ) { pipe: function ( /* fnDone, fnFail, fnProgress */ ) { progress: function () { promise: function ( obj ) { readyState: 4 responseText: "JAVASCRIPT TEMPLATE !" setRequestHeader: function ( name, value ) { state: function () { status: 200 statusCode: function ( map ) { statusText: "OK" success: function () { then: function ( /* fnDone, fnFail, fnProgress */ ) { __proto__: Object ``` So I get the correct response text ??!! Where can be the error then ? :-s

Original source