Reputation: 2940
I have a strange behavior where an ajax query fails parsing a JSON object returned by my rails 4.1.4 server (jquery-rails is 3.1.1). Yet, the controller is dead stupid:
class WelcomeController < ApplicationController
def create
respond_to do |format|
format.json{ render json: 'ok' }
end
end
end
and the Ajax query is all very standard (CoffeeScript):
window.Api = {}
(->
queryFx = (dataType, type, url, data, successFx, failureFx) ->
$.ajax
url: url
type: type
dataType: dataType
beforeSend: (xhr) ->
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
success: (json) ->
console.log(json)
error: (xhr, status, errorThrown) ->
console.log(status, errorThrown)
Api.post = (url) ->
queryFx('json', 'POST', url)
)()
$(document).ready( ->
$('#request').submit( (event) ->
event.preventDefault
window.Api.post($(this).attr('action'))
return false #Prevent the normal submission
)
)
the query goes fine, only when the reply comes, ajax throws:
"parsererror" SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Stack trace:
jQuery.parseJSON@http://localhost:3000/assets/jquery.js?body=1:8483:3
ajaxConvert@http://localhost:3000/assets/jquery.js?body=1:8809:8
done@http://localhost:3000/assets/jquery.js?body=1:9226:4
.send/callback@http://localhost:3000/assets/jquery.js?body=1:9686:8
Is there anything to do on the rails server so it outputs proper JSON for jquery?
Upvotes: 0
Views: 991
Reputation: 129
I've just faced the similar problem. I also advise you to check your ajax response string for invalid format first before using it as a json object. I'm not familiar with coffeescript, that's why I give you a native js sample. So try to put the following code into your AJAX complete callback function:
complete: function(data) {
var jsonRes = null;
try {
jsonRes = JSON.parse(data.responseText);
}
catch(e) {
jAlert('Invalid JSON object);
}
if (jsonRes===null || jsonRes.result===undefined) {
jAlert('Invalid Ajax response structure');
}
}
Upvotes: 0
Reputation: 2171
Your controller is dead stupid but does in fact render invalid json ;) You should pass an Hash to the json option of render. Try it like this :
class WelcomeController < ApplicationController
def create
respond_to do |format|
format.json{ render json: { ok: 'ok' } }
end
end
end
Upvotes: 4