Search code examples
rubyajaxjsonhandsontable

ajax only recognising json if I create it manually


I am trying to use the following code to check that data is being saved:

$parent.find('button[name=save]').click(function () {
  $.ajax({
    url: "/help.json",
    data: {"data": handsontable.getData()}, //returns all cells' data
    dataType: 'json',
    type: 'POST',
    success: function (res) {
      if (res.result === 'ok') {
        $console.text('Data saved');
      }
      else {
        $console.text('Save error');
      }
    },
    error: function () {
      $console.text('Save error, not working');
    }
  });
});

I am using rails for the server side code. If I manually create /help.json.erb and add the following to the page

{
  "result": "ok"
}

The I get a 'Data saved' message when I try the ajax code.

However, if I try to create the /help.json file with ruby I get an 'Save error, not working' error. My ruby code to create the /help.json file is as follows in my controller:

class StaticPagesController < ApplicationController
 respond_to :html, :json

  def home
  end

  def help
      the_hash = {"result"=>"ok"}
      respond_with(the_hash) 
  end
end

The above codes generates a /help.json file with

{"result": "ok"}

But I don't get the 'Data saved' message

What could be the reason that it works when I manually create the json file but not if I try with ruby?

The relevant part of my routes file is:

  root to: 'static_pages#home'
  match '/help',    to: 'static_pages#help'

On further inspection, the error message I am getting in 500 (internal server error)


Solution

  • I solved this issue by using the answer here:

    Rails respond_with acting different in index and create method

    I changed my respond_with statement to:

       respond_with({:result => "ok"}, :location => nil)