Senju
Senju

Reputation: 1035

Using Ajax to GET data from Rails controller

I am trying to get an instance of a modal (in JSON format) by using Ajax when a form is submitted. Currently, on the alert, it outputs nothing, blank.

alert('<%= @modal_data.to_json.html_safe %>'); outputs JSON data, but alert(data); called through Ajax does not output anything.

Controller

class ModalController < ApplicationController
  def modal_index
    @modal_data = Modal.where(:var => params[:attr1])
    respond_to do |format|
      format.html
      format.json {render json: @modal_data}
    end
  end
end

JavaScript

$(document).ready(function() {
  $('#my_form').on("submit", function () {
    $.ajax({
      type: "GET",
      dataType: "json",
      url: "/modal/modal_index",
      success: function(data){
        alert(data);
      }
    });
  });
});

Upvotes: 0

Views: 1307

Answers (1)

KensoDev
KensoDev

Reputation: 3285

In order for this to work with JSON you need to set the content type to application/json.

if your $.ajax call

$(document).ready(function() {
  $('#my_form').on("submit", function () {
    $.ajax({
      type: "GET",
      contentType: "application/json",      
      url: "/modal/modal_index",
      success: function(data){
        alert(data);
      }
    });
  });
});

Also, it doesn't seem you provided the param needed to find the model (attr1).

Keep your controllers standard, pass id or item_id to get in order to get the object you need.

Upvotes: 1

Related Questions