Currently im “polling”/checking every 1000ms by doing a GET to /moves:
jQuery(document).ready(function() {
setInterval(function() {
$.get("/moves", function(result){
$('#board').clearBoard();
var myobj = {fen : ""};
myobj.fen = result;
$('#board').chess(myobj); });
}, 1000);
$.ajaxSetup({ cache: false });
})
I want to replace that by updating after I get a POST in a controller:
class MovesController < ApplicationController
def create
m = Move.new
last_game = Game.last
if !last_game.nil?
m.game_id = last_game.id
end
m.move_data = params[:move_data]
if m.save
render :text => "#{m.move_data}"
**Update JavaScript here**
else
render :text => "FAIL"
end
end
def index
last_move = Move.last
if last_move.nil?
render :text => "FAIL"
else
render :text => "#{last_move.move_data}"
end
end
end
I’m not sure how to do the AJAX/Update from the controller.
Thanks!
The correct way to respond to ajax from the controller is to use a respond_to block. ex:
And then you need a corresponding app/views/my_controller/my_action.js.erb
the respond_to block will detect whether the users browser requested an html file, or a js file (like through an ajax request.)
If you want to do a post to the server, straight from js, I would recommend $.ajax.
The ‘type’ option allows you to specify ‘GET’ or ‘POST’. That method is documented here