Kendall Weihe
Kendall Weihe

Reputation: 2075

Rails 4/AJAX GET data from controller

I posted a very poor question about this earlier, so I am reposting and making it MVCE.

I'm building a messaging service with Rails and AJAX. So far I can submit a message through a form, it will update in the HTML DOM, an AJAX POST method will send it to the controller, and the controller will save it in the database.

Now I need to add an AJAX method that will GET the message that was just submitted -- so that other users (in other browsers) will be able to view it.

Currently, and this is a hack job way of doing it, in my JS code I set a timeout that calls an AJAX GET function every half second. Is there a better way to do this -- as in, once the controller saves the message can it call the AJAX function? The AJAX code looks like this:

function retrieveMessages(){
  var message;
  <%debugger%>
  $.ajax({
    type:"GET",
    url:"<%= messages_get_path %>",
    dataType:"json",
    data: { what_goes_here: "blah" }, //this is the part I do not understand -- see below
    success:function(data){
      message = data;
      console.log(data)
    }
  });

  setTimeout(retrieveMessages, 500);
}

$(document).ready(function(){
  //get messages
  setTimeout(retrieveMessages, 500);
... more irrelevant

The line data: { what_goes_here: "blah" } doesn't make sense to me. What is the syntax for the controller to send data back to be stored into data:? Furthermore, from the console I can see that what_goes_here is being passed as a parameter to the controller -- again this doesn't make sense to me.

My route looks like this get 'messages/get', :to => 'messages#get' (this might be incorrect?)

rake routes shows

  messages_get GET    /messages/get(.:format)        messages#get

And as of now, I don't have anything in my controller other than a respond_to because at this point I'm just trying to call the controller. What is the syntax to send data back to the AJAX method?

def get
  debugger
  respond_to do |format|
    format.html
    format.json {render json: @variable} //is this @variable being passed to the AJAX call?
  end
end

UPDATE

This makes more sense to me... the AJAX method simply calls the def get function. The def get function then finds the message in the database, and stores it in an instance variable. Subsequently, I can add some Javascript code that will insert it into the DOM. However I must have something wrong in my routing because I'm getting (in the console) http://localhost:3000/messages/get 404 (Not Found)

Upvotes: 1

Views: 716

Answers (1)

Nic Nilov
Nic Nilov

Reputation: 5155

What you are doing, as you suspect, is not effective. The more users are online the more will be load from these refreshing requests, most of them probably returning no new data.

You should consider more active way of notifying your browsers about changes on the server. One option is to use ActionCable.

Upvotes: 1

Related Questions