I send data in json format for counting visits. Problem is when i use back arrow in browser - results are send second, third ... and more times and there is one em tag for every click in back arrow on browser. What i can do to overwrite results but not sending second in new place.
My controller:
visits_count = current_user.visits.where(:read => false).count.to_i
respond_to do |format|
format.json { render :json => visits_count }
And my js:
function unread(){
$('#visits p').each( function() {
$.ajax({
url: '/visits/unread_count',
dataType: 'json',
success: function(data) {
if (data > 0) {
$('#visits p').append('<em>' + data +'</em>');
}
}
});
});
};
and my view:
<%= link_to 'visits', visits_path, :id => "visits" %><p></p></li>
Related
I'm trying to create a jackpot betting site (just as a challenge). I have a method in my controller to update the pot when a user adds money to the pot. I display the pot total on the homepage and would like to update it with Ajax as soon as someone adds money to the pot. I'm using the gon gem to pass variables such as the pot total from my controller to my javascript. It works when the page is reloaded but not when the update method is called with ajax.
Heres my PagesController:
def home
#jackpot = Jackpot.last
gon.pot = #jackpot.pot
end
JackpotsController:
def update
#jackpot = Jackpot.find(params[:id])
if params.has_key?(:amount)
#jackpot.update(pot: #jackpot.pot + params[:amount].to_f)
gon.pot = #jackpot.pot
end
respond_to do |format|
format.js
end
end
Javascript: (In the url the :id is hardcoded for now)
$("#bet-btn").click(function() {
$.ajax({
type: "POST",
url: "/jackpot/update/21",
datatype: "json",
success: function() {
console.log("Pot size: " + gon.pot);
updatePot();
},
error: function() {
console.log("error")
}
});
});
This updates the donut progress bar for the pot
function updatePot() {
updateDonutChart('#jackpot-donut', gon.pot , true);
}
Button to place bet: (amount also hardcoded)
<%= link_to "Place Bet", update_pot_path(#jackpot, :amount =>
0.1), method: :post,:remote => true, id: "bet-btn", class: "btn btn-info btn-lg" %>
I'm pretty new to rails and especially javascript/ajax so any help would be appreciated. Thanks!
In the controller, simply respond to JSON:
respond_to do |format|
format.json { render json: { pot: #jackpot.pot } }
end
Specify the dataType when posting with $.ajax. Notice that the new data is bieng passed to the success function, so it's not gon.pot, but data.pot.
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data) {
console.log('pot', data.pot);
}
});
I've been all over the place plugging different things into this process and I still get no results.
Sometimes I get the infamous extra "<" error, sometimes absolutely nothing happens, and I'm not sure if this is the problem but I think Google developer is showing that the current page is being sent as the json file I'm asking for and not the json I'm sending (see later). This is what I see in google developer:
Which is definitly NOT my json file:
In any case, this is my javascript:
$('#q_name_cont').autocomplete({
url: "autocomplete/items",
dataType: 'json'
});
This is my route:
get 'autocomplete/items' => 'home#autocomplete_items', :defaults=>{:format=>'json'}
Controller Action (commented out part is another method I was trying for a while):
def autocomplete_items
# respond_to do |format|
# format.js {render 'autocomplete_items'}
#products = Item.all.order(:name)
respond_to do |format|
format.html
format.json {
render json: #products.map {|item| item.name}
}
end
end
Before I was using mapping, I was using this view for the render:
{
"items": [
<%Item.all.each do |i|%>
{ "<%=i.name%>","<%=i.name%>" },
<%#end%>
{ "value": "", "data": "" }
]
}
I've really been all over the place, trying for a very long time to get this to work. What am I missing?
IIRC, Your url and dataType options just do not exist in autocomplete's documentation. You could try source option instead:
$('#q_name_cont').autocomplete({
source: function (request, response) {
$.ajax({
url: "/autocomplete/items", // should be with '/'
dataType: 'json',
data: { query: request.term },
success: function(data) {
// call response to return the result to autocomplete box
response(data);
}
});
}
});
Of course, this is just for showing up all items, if you want to filter like real autocomplete box, you should modify controller to filter the result base on query:
def autocomplete_items
#products = Item.all.order(:name)
respond_to do |format|
format.html
format.json {
render json: #products
.where('name ILIKE ?', "%#{params[:query]}%")
.pluck(:name)
}
end
end
I am trying to get my json using jsonp
this is my json data
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$.ajax({
url: 'https://192.168.236.33/confbridge_participants/conference_participants.json?cid=0090000007',
type: "GET",
dataType: "jsonp",
jsonpCallback: 'callback',
contentType: "application/javascript",
success: function(data) {
console.log(data);
}
});
</script>
and i always get this error
Refused to execute script from 'https://192.168.236.33/confbridge_participants/conference_participants.json?cid=0090000007&callback=callback&_=1439798517979' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
here where do i get my json on my rails controller
def conference_participants
conditions = Hash.new
if params[:cid]
conditions[:cid] = params[:cid]
end
#conference_participant = ConfbridgeParticipant.where(conditions)
respond_to do |format|
format.html { render :html => #conference_participant }
format.text { render :text => #conference_participant.pluck(:id).first }
format.json { render :json => #conference_participant}
format.js { render :json => #conference_participant , :callback => params[:callback]}
end
end
thanks :)
I would like to post the result of an ajax request back to the same page that it was requested from. Here are the interacting parts:
AJAX in Jquery
var ids = 1
$(document).ready(function(){
$('#showbtn').on('click', function() {
$.ajax({
url: "http://localhost:3000/teamplayers.json",
data: {'resolution':ids},
type:"post",
dataType: "json",
cache: true,
success:function(){
$('#test3').val(1);
alert("test 3");
},
error: function(error) {
alert("Failed " + console.log(error) + " " + error)
}
});
});
});
This is supposed to set a variable here:
Teamplayer Controller
# GET /teamplayers
# GET /teamplayers.json
def index
#teamplayers = Teamplayer.all
#fteams = Fteam.all
#teamplayer2 = 1
tid = params[:resolution] <-It should set here per the data section above
#ids = tid
end
unfortunately it calls this section of the same controller
# POST /teamplayers
# POST /teamplayers.json
def create
#teamplayer = Teamplayer.new(teamplayer_params)
respond_to do |format|
if #teamplayer.save
format.html { redirect_to #teamplayer, notice: 'Teamplayer was successfully created.' }
format.json { render action: 'show', status: :created, location: #teamplayer }
else
format.html { render action: 'new' }
format.json { render json: #teamplayer.errors, status: :unprocessable_entity }
end
end
end
So what do I do to make it post to the same page.
You are POSTing the ajax, which means the create action will be hit, not the index action. You should be able to see this in your server log output when you hit the page.
If you want to hit the index action, you need to do an GET ajax request with the resolution data set so you can get the data you want.
Additionally, you probably maybe don't want to cache this ajax request if it is actually dynamic data, but it is up to you.
Edit from comments:
You need to add your parameter as a query string for a GET, not as generic "data".
Try something like this:
$.ajax({
url: "http://localhost:3000/teamplayers.json?resolution="+ids,
type:"GET",
dataType: "json",
success:function(){
$('#test3').val(1);
alert("test 3");
},
error: function(error) {
alert("Failed " + console.log(error) + " " + error)
}
});
});
Another edit from comments:
# GET /teamplayers
# GET /teamplayers.json
def index
#teamplayers = Teamplayer.all
#fteams = Fteam.all
#teamplayer2 = 1
tid = params.fetch(:resolution) { 0 } # make sure we got something
#ids = tid.to_i # coerce string param to integer
end
In a rails application i am working on, i would like to refresh/reload the index method of my controller without refreshing the view. For instance lets say i have this as my index:
def index
#title =params[:title]
end
And html.erb:
<script>
function changeField() {
var newTitle = "Alerts"
$.ajax({
url: 'index?title=' + newTitle,
type: 'POST',
contentType: 'application/json',
data: '',
dataType: 'script',
headers: {
'X-CSRF-Token': '<%= form_authenticity_token.to_s %>'
},
complete: function () {
alert('<%=#title%>');
}
});
}
</script>
<button type="button" onclick="changeField()"></button>
The problem i am having is that it does not reload the #title variable on the view so i get the original title and not the new title.
When page was loading alert('<%=#title%>') equals alert('first value') and after set a new value javascript code can't be reloaded. If you look html code you can see first value but not second
I think you can add this code to you controller
respond_to do |format|
format.html # index.html.erb
format.js { render :json { :title => params['title'] || #title }.to_json }
end
and add to js code success: function(data) { alert(data['title']) }