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 :)
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 attempting to send back an error response to an ajax call in a rails controller.
Below is my create action in my controller the javascript function with the ajax call. I need to send back a error response so the error portion of the ajax request is called. I can not figure out how to get this to work.
def create
#company = Company.find(params["company_id"])
#campaign = #company.campaigns.build(campaign_params)
if #campaign.save
redirect_to campaign_get_campaigns_path(#company)
else
respond_to do |format|
format.json {render :json => {:error_message => #campaign.errors.full_messages, :success => false } }
end
end
end
$(document).on('click', '#submitCampaign', function (e) {
$form = $('.new_campaign');
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
dataType: "json"
});
error: function(data) {
newfunction(data);
}
});
The response I am getting in the terminal is:
Completed 200 OK in 269ms (Views: 0.2ms | ActiveRecord: 9.9ms)
You have to define response :status. In this case is the best choice 422 Unprocessable entity.
format.json { render :json => { :error_message => #campaign.errors.full_messages }, :status => :unprocessable_entity }
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>
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']) }