Respond_to format.json not being called

Hi all,

I’m submitting a form using jQuery, but in the respond_to block only the
format.html action is called.

This is the javascrip:

send_button.on(‘click’, function(){
var form = $(this).closest(’.modal’).find(‘form’);

$.post(’/messages’, form.serialize(),
function(data, status, xhr){
console.log(data);
});
);
});

However, when this hits the controller, ‘console.log(data)’ outputs html
(either root_url or the validation array).

The code in the controller looks like:

respond_to do |format|
if @m.save
format.html {redirect_to root_url, :notice=>“Message sent”}
format.json {render :json=>@m, :status=>:created, :location=>@m}
else
format.html {render :action=>:new}
format.json {render :json=>@m.errors,
:status=>:unprocessable_entity}
end
end

Obviously, I’m not using link_to_function or anything, so I’m wondering
if the request format header isn’t being set properly without using the
built-in rails functions?

Any help would be appreciated.

Many thanks.

On 20.02.2012, at 22:57, Oliver F. wrote:

$.post(’/messages’, form.serialize(),
function(data, status, xhr){

You call pure Javascript request.

respond_to do |format|
if @m.save
format.html {redirect_to root_url, :notice=>“Message sent”}
format.json {render :json=>@m, :status=>:created, :location=>@m}

format.json - is NOT javascript hook,

use format.js

or old approach:
if request.xhr?
do action
end