Q:

Not able to fetch json data in RoR

This is my code in my view where I am making an ajax get request to method campaign_creation
$(document).ready(function(){
    $("#submit").click(function(){
        $.get("/configure_campaign/campaign_creation",{category_name: $("#category_name").val()}, function(data){

            $("#category_name").val('');
            $("#form_add_category").css("display","none");
            alert(data.category_name)

        })
    })
})

and here is my method code
def campaign_creation
    if(params[:page_id] and params[:page_access_token])

        abcd=params[:page_id].split("_")
        session[:page_id]=abcd[0]
        session[:page_access_token] = params[:page_access_token]

    else

        category=Category.new
        category.category_name=params[:category_name]
        category.page_id=session[:page_id]
        category.save
        @category=Category.find(1)
        @category.to_json

    end
end

I think I should be able to access @category in my variable data. If I simply put data in my alert box I get the complete code of the page and if data.category_name I get the result as undefined.

A:

From the code you've provided for your action alone, you're not going to be rendering a JSON response. Your campaign_creation method is going to try and find a campaign_creation.html.erb file and render a text/html response.
Instead you need to explicitly tell Rails to render JSON data and the end of the action and stop processing.
render json: @category and return

Now you can expect the data variable in your Ajax response to have accesss to the @campaign's :category_name attribute.

