reiallenramos
reiallenramos

Reputation: 1295

AJAX to fetch model data from view

I get [object Object] when printing the results of my AJAX calls. Please help me find which part I'm not doing right.

The Event model has columns name, description. Am I correct to expect this kind of output?

{ "1" =>
  {
    "name" => "some name",
    "description" => "some description"
  }
}

View:

function testAJAX() {
  var test_url = "#{foo_events_path}";
  $.ajax({
    type: "GET",
    url: test_url,
    data: {
      event_id: 1
    },
    success:function(data) {
      var response = JSON.parse(JSON.stringify(data));
      alert(response.events);
    }
  });

events_controller.rb

def foo
  @events = Event.where(id: params[:event_id])
  render json: { events: @events }.to_json
end

routes.rb

resources :events do
  collection do
    get 'foo'
  end
end

I tried googling but most of them uses AJAX for php. This is the closest I could find related to my question: Is it possible to refresh partial frequently using Ajax?

Upvotes: 0

Views: 303

Answers (1)

jvillian
jvillian

Reputation: 20263

Your controller method should look like:

def foo
  @events = Event.where(id: params[:event_id])
  render json: { events: @events }
end

The render json: will create a valid JSON response.

Then, you should be able access your data object like this:

function testAJAX() {
  var test_url = "#{foo_events_path}";
  $.ajax({
    type: "GET",
    url: test_url,
    data: {
      event_id: 1
    },
    success:function(data) {
      alert(data.events);
    }
  });

Upvotes: 2

Related Questions