1
votes

Quite a bit of links, but I can't piece all of the info together.

I assume a controller, a view and routes are involved.

Regarding the url and routes, I have the generic folder structure, app/views/pages/home and app/controllers/pages_controller.rb. Can you guide me if I'm doing the routing and url correctly, also?

routes.rb

get pages/get_aj //Don't know if this is what you put

jQuery

$.ajax({ 
type: 'get'
url: '/pages/get_aj' //can someone confirm this is how you do it? 
dataType: "JSON" //I need to pass back values from the controller to JS. Do I use JSON?
}).success(function(data){
      alert("returned " + data);
});

//some other jQuery code that will depend on the data returned.

pages_controller.rb

def get_aj
   respond_to do |format|
      format.json{render :json => "we got here" } //Do I return .js?
   end
end

rake routes

   pages_home GET /pages/home(.:format)    pages#home
pages_contact GET /pages/contact(.:format) pages#contact
 pages_get_aj GET /pages/get_aj(.:format)  pages#get_aj
1
so what is the problem? - Wahtever
Being generic - it doesn't work. I was looking for confirmation, maybe I am overlooking some detail, because it does not return a value. I don't know even if it properly goes to rails. - Alexey
in your controller change format.json to format.js and post your rake routes regarding the pages_controller and the console message - Wahtever
Editted the question with routes. and do I change both format.js and js=> "we got here"? - Alexey
just replace the format.js, also what does the console in your browser say? - Wahtever

1 Answers

6
votes

Your code should work actually. The biggest thing you're misunderstanding is what JS alert does. It alerts strings, and data is an object. See this JS fiddle: http://jsfiddle.net/YNeA3/

To inspect objects from JS, use console.log() instead of alert. These will show up in your browser console. This is the basic bread and butter debugging tool for JS.

I'm not sure what the JSON object you're sending looks like, because you should be rendering a hash, not a string. That's the only real problem with your code, I think.

Also, a suggestion: if this controller action is only going to be for ajax you don't have to bother with the respond_to block. I would specify status though.

def get_aj
  data = {:message => "Alert this!"}
  render :json => data, :status => :ok
end

Now in your JS:

$.ajax({ 
  type: 'GET',
  url: '/pages/get_aj',
  success: function(data,status,xhr){
    console.log(data);
    alert(data.message);
  },
  error: function(xhr,status,error){
    console.log(xhr);
    alert(error);
  }
});

Data will be a JS object looking just like the hash you sent.