Reputation: 569
I have this JS code in my application.js:
$(document).ready(function(){
var kraken_btc_eur_old = 0;
setInterval(function(){
$.get('https://api.kraken.com/0/public/Ticker?pair=XXBTZEUR', function(data){
var kraken_btc_eur = data.result.XXBTZEUR.c[0];
kraken_btc_eur_old = kraken_btc_eur;
$(".kraken_btc_eur").text(kraken_btc_eur);
});
$.ajax({
type: "POST",
url: "/bets",
data: { parameter: kraken_btc_eur_old },
success: function (data) {
}
});
}, 10000);
});
So far so good, every 10 sec the page display the new value fetch from the API and place it to the corresponding class in the HTML without any page refresh. My problem is with the AJAX request. I can see that in the rails console that every 10 sec the post request hit the create action in my controller and that the code is executed accordingly:
def create
@bet = Bet.new
@bet.base_price = params["parameter"]
@bet.save
Bet.first.destroy
@bets = Bet.all
@bet_last = Bet.last
#render :js => "window.location = '#{root_path}'"
#redirect_to "index"
#render :inline => "<% @bets.each do |b| %><p><%= b.id %><p><% end %>"
end
However I do not manage to update the html view with the new values without having to refresh the page. Because every 10 sec new bets are created (AJAX), I want them to appear automatically in the page without any refresh to be done. I tried to render in different ways in my create action, I realized that there are documents created in my browser console under ressources -> XHR with the updated htm but I do not manage to have that replace by the showed one without any refresh.
Upvotes: 0
Views: 1658
Reputation: 1234
When you are sending a AJAX request, rails won't be able to update your view. That's because, as you said, you're not actually refreshing the page. So rails can't send the new HTML content to the browser.
In that case, you need to handle the logic of adding a new Bet
in the frontend (Javascript).
Something like:
$.ajax({
type: "POST",
url: "/bets",
data: { parameter: kraken_btc_eur_old },
success: function (data) {
var newBet = "<div>" + data.base_price + "</div>";
$('list_of_bets').append(newBet);
}
});
And on the rails side, you need to return the new Bet
you just created as a JSON:
def create
# your logic here
render json: @bet
end
Upvotes: 1