Dealing with ajax request in Rails - javascript

Stackoverflow community
I have a select in my view. Onchange of which my ajax request is sent.
<%= f.select :id, options_from_collection_for_select(#rtypes, "id", "typeName"),
{include_blank: true },
{'data-rtypes': #rtypes.to_json } %>
.I am using Jquery ajax. My ajax works. It send an id of rtype to the show_sub_types method.
$(function () {
// specify id or class for your select tag
$('select').on('change', function () {
var rtype = $(this).val();
$.ajax({
url: "/RequestTypes/show_sub_types/"+rtype,
type: "GET",
})
});
});
In my show_sub_types method I want to grab all subTypes (stypes) from RequestSubType model.
def show_sub_types
#rtype = params[:id];
#stypes = RequestSubType.where("RequestType_id"==#rtype).all
respond_to do |format|
... some code here
end
end
I do not know how to deal with ajax request, i dont know how to send my stypes array to the page, and how to deal with that response. I have read some tutorials, but still can not understand that respond_to part. Probably i would understand on my own example.
In my view i have div where i want to put data send by ajax (inserted into html).

Specify the id of select and read for data attribute.
Get that array in data variable, and pass it to post ajax request
var data = $(this).data('rtypes');
or
$(this).find(':selected').data('rtypes')
$.ajax({
type : "POST",
url : "/RequestTypes/show_sub_types/"+rtype,
dataType: 'json',
data: JSON.stringify(data),
dataType: "json",
contentType: 'application/json'
});

Related

Gon variable not passing to js from rails controller during Ajax request

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);
}
});

How to pass MVC view model into AJAX call with AntiForgeryToken

The code below is working for me, but I'm trying to find a way to read all values from the form instead of having to re-create the view model in JavaScript (vm is the name of the parameter of the object).
I tried to serialize the form and pass it in, but maybe my syntax is incorrect.
Any suggestions?
$.ajax({
type: "POST",
dataType: "json",
url: "/post-details-save",
data: addAntiForgeryToken({
vm: ({
Id: $("#PostImageDetails_Id").val(),
Title: $("#PostImageDetails_Title").val(),
Description: $("#PostImageDetails_Description").val(),
CopyrightOwner: $("#PostImageDetails_CopyrightOwner").val(),
CopyrightUrl: $("#PostImageDetails_CopyrightUrl").val(),
SourceName: $("#PostImageDetails_SourceName").val(),
SourceUrl: $("#PostImageDetails_SourceUrl").val(),
SourceLicenseType: $("#PostImageDetails_SourceLicenseType").val()
})
}),
success: postDetailsSaveSuccess,
error: postDetailsSaveError
});
Confirm Form Setup
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { #id = "formID" }))
I have done similar stuff with submitting forms in partial views.
Basically, you need to confirm that your html form is set up correctly:
The AntiForgeryToken
#Html.AntiForgeryToken()
Data Fields
Could look something like the following with the name attribute being important.
<input type="hidden" name="ApproveUserID" id="ApproveUserID" value="#Model.ApproveUserID" />
AJAX The Form
If your form is set up correctly like explained above, you will be able to submit the data via AJAX with something similar to the JS below.
var form = $("#formID");
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(), // data to be submitted
success: function (response) {
if (response == "Success") {
//DO SUCCESS STUFF
} else
{
//DO FAILURE STUFF
}
},
error: function () {
//DO ERROR STUFF
}
});
Pro Tip:
You can always expand the data you send by placing
var formData = form.serialize();
Into a variable and expanding it from there.
Good Luck.

Rails: Simple Ajax post to filter index results

I have a checkbox on my trailers index page that, when checked, should filter the results.
trailers_controller:
class TrailersController < ApplicationController
respond_to :html, :js
def index
trailers = Trailer.last(40).sort_by(&:published_at).reverse
trailers = trailers.select { |t| t.budget == "blockbuster" } if params[:show_indie] && params[:show_indie] == "false"
#trailers = Kaminari.paginate_array(trailers).page(params[:page]).per(6)
end
end
And my view:
<div class="trailers">
<%= render #trailers %>
</div>
And my js:
<script>
$(function(){
$('.checkbox-inline').on('change', function() {
var show_indie = $(this).find('input').prop('checked')
$.ajax({
url: '/trailers/filter',
type: "post",
async:true,
dataType: "html",
data: {show_indie},
success: function() {
console.log ("filtered")
},
error: function(){
console.log ("error with ajax")
}
});
})
});
</script>
routes:
post 'trailers/filter' => 'trailers#index'
And my index.js.erb:
console.log('index js loaded')
$('.trailers').html("<%= escape_javascript render(#trailers) %>");
Everything seems to work, the AJAX is posting okay. But the index.js.erb is not rendering. I have a feeling it's because my dataType is "html" instead of JSON or something.. But not really sure how that works, or how to fix it.
What am I doing wrong?
Is this the best way to handle this kind of filtering?
You need to specify dataType as "script"
$.ajax({
method: "GET",
url: "test.js",
dataType: "script"
});
To add to the answer, you need to remember not to store your javascript in your views directly. To make your application run efficiently & properly, you need to use the unobtrusive javascript pattern:
#app/assets/javascripts/application.js
$(document).on('change', '.checkbox-inline', function() {
var show_indie = $(this).find('input').prop('checked')
$.ajax({
url: '/trailers/filter',
type: "post",
dataType: "script",
data: {show_indie},
success: function() {
console.log ("filtered")
},
error: function(){
console.log ("error with ajax")
}
});
});
This will not only free up your views, but also allow you to factor the JS into your asset pipeline, making it more efficient.

How to pass Rails variable to AJAX response function?

In AJAX I write:
$.ajax({
URL: '/new_avatar',
type: 'POST',
data: { username: 'alizade' },
success: function(response){
alert(response);
},
})
Route.rb:
post '/new_avatar' => 'avatars#new_avatar'
Avatar.rb model:
self.new_avatar(username)
Avatar.where(username: username).select('avatar').last
end
Avatars_Controller:
def new_avatar
#username = params[:username]
#result = Avatar.new_avatar(#username)
end
So, how can send #result to AJAX response function and alert the database selection result?
Assuming you need only response from this service, you can use following way to get the result.
def new_avatar
#username = params[:username]
render :json => Avatar.new_avatar(#username)
end
you need to use render :text in your controller method
def new_avatar
#username = params[:username]
#result = Avatar.new_avatar(#username)
render :text => "#{#username} has this result:- #{#result.inspect}"
end

Passing Parameters of AJAX POST to Grails Controller

I´m building a social network with Grails and got stucked
on giving users inner their editprofile
page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video
the html looks like :
<g:textField name="videoinput" class="videoinput reLef" value="" />
<span class="daten_videouploadbtn reLef" ></span>
<g:render template="/forms/storedVideos" />
the JS looks like :
$('.daten_videouploadbtn').click(function() {
var string = document.editProfileForm.videoinput.value;
var neu = string.replace(/http[s]?:\/\/(?:[^\.]+\.)*(?:youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)|youtu.be\/)([\w\-\_]+)/i, '$1');
var id = RegExp.$1;
jQuery.ajax({
type:'POST',
data:RegExp.$1,
url:'${createLink(action: 'addVideo')}',
success:function(data,textStatus){jQuery('#storedvideos').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
});
the controller looks like :
def addVideo() {
def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}
and stored videos looks :
<div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>
i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,
can someone give a hint ? it is killing me
You should post the data like this:
jQuery.ajax({
type: 'POST',
data: { value: RegExp.$1 },
...
After that you can access the posted data inside your grails controller with params.value.
I got this working on Grails 2.0.4:
Javascript/Ajax
var data =
{requestId: 12456,
node: "node1",
host: "mynode.com"};
$.ajax({
url: '/myurl',
data: JSON.stringify(data),
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() ...
},
error: function() ...
}
});
In Grails....
def service(){
def jsonObj = request.JSON
}
I like this approach because request.JSON parses the data and returns a ready to use object.

Categories