0

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);
      }
    });
  });
});
1
  • 1
    First, make sure you provide params[:attr1]. Commented Sep 11, 2015 at 20:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Woops, yea I forgot the param... after that it worked. Also, I tried using contentType: "application/json", but that returned an html page instead of a json object. dataType: "json" seemed to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.