Ruby on Rhodes using ajax call - ruby

I am trying to build a dynamic dropdown in ruby on rhodes.There are basically two dropdowns on my screen and i am using ajax to get the values of the second dropdown from the database depending on the value selected in the first dropdown..I am a newbie to ruby and do not know the syntax on how to use ajax in ruby on rhodes..
JavaScript Code I am using...
$.post("/app/Settings/dropdown",
{ value:a },
function(data){
alert(data);
});
-----Partial Controller Code
enter code here
def dropdown
#a = #params['value']
puts #a
if #a.eql?"Auto"
mystring="auto1|auto2|"
else
mystring="personal1|personal2|"
end
end
I can get any parameter sent via ajax call to controller..My Question is how to send back the data from controller to function in that ajax call so that i can use that information to create a dynamic dropdown..I want to send this mystring to function(data)??

In Rhodes, controller actions can only render other actions or return a string consisting of partials. So, in order to populate a dropdown using AJAX, you'll have to render the view associated with the action which will returned as response to the AJAX call.
Controller 'dropdown' action:-
def dropdown
#a = #params['value']
if #a.eql?"Auto"
#optionList[:auto1]="auto1"
#optionList[:auto2]="auto2"
else
#optionList[:personal1]="personal1"
#optionList[:personal2]="personal2"
end
render :action => "dropdown"
end
'dropdown.erb' view:-
<% optionList.each do |key, value| %>
<option value="<%= key %>"><%= value %></option>
<% end %>
AJAX call:-
$.post(
"/app/Settings/dropdown",
{ value:a },
function(data){
data = data.replace("<div>","");
data = data.replace("</div>","");
alert(data);
}
});
Make sure you replace the div tags in the AJAX response, since Rhodes automatically surrounds AJAX responses with div tags.

Related

Rails views to get variable from controller

I'm using form with :remote => true for ajax functionality, this form works fine but outside this form I have select_tag for other feature :
<%= select_tag "months", options_for_select(#dynamic_month.collect { |name|
name }, 'ALL'), id: 'chart_filter', :onchange =>"monthWise(this)" %>
Here I'm passing #dynamic_month from controller, but I'm not getting updated value from controller after submission of form, Is there any way we can achieve this keeping this select option outside the form and getting updated data from controller.
Thank you.

Calling a Ruby Method via a html button in sinatra

I'm trying to build an e-commerce site using Sinatra, as practice. I'm getting stumped on how to implement the 'Add to Cart' Button. My thought process about it is:
User clicks 'add to cart'
The button 'add to cart' invokes a ruby method, for example clicking on the following button
<input class='btn btn-primary' type='button' value='Add To Cart'></input>
should call a ruby method like
shop.add_to_cart(product, quantity)
An example of what this method might looking like:
class Shop
attr_reader :cart
def initialize
#cart = []
end
def add_to_cart(product, quantity)
#cart << product, quantity
end
end
In Rails, I think we use the helper_method in the controller? Is there anything similar I can do in Sinatra?
Thanks!
Note:
This is if you want to do it in ruby. You could probably also do it in javascript as mentioned in the other answer, but I cannot help you with that because I don't know javascript well enough.
To run the ruby method on button click you first need to create a <form> with only the button, then have that run a route in your app file that will run the method then redirect back to the page you were on. Here is my code (have not tested):
home.erb:
<form method="post" action="/runMethod">
<input type="hidden" name="product" value="whatever">
<input type="hidden" name="quantity" value="whatever">
<input class='btn btn-primary' type='submit' value='Add To Cart'>
</form>
You would set the values of the two hidden inputs (where I wrote "whatever") to the quantity and product according to their names.
App File:
class Shop
attr_reader :cart
def initialize
#cart = []
end
def add_to_cart(product, quantity)
#cart << product, quantity
end
end
get '/' do
erb :home
end
post '/runMethod' do
shop.add_to_cart(params[:product], params[:quantity])
redirect '/'
end
This can also be accomplished with ajax so that you dont have to leave the page:
$("#hideCarousel").submit(function() {
//posts the contents of the form to /action using ajax
$.post("/action", $("#myform").serialize(), function(result){
// assuming result is a string of the updated data in html
// and assuming that your data goes in an element with the id data-table
$("#data-table").html(result)
});
return false; // prevents the form from submitting normally
});
Rails/Sinatra run on the server side. If you want stuff happening in Rails directly you probably need a form and post back data.
nowadays people use javascript and it's javascript that makes the callbacks in an asynchronous fashion for this kinds of things.

Grails 2.4.2 Ajax not working for OnChange

I have to dynamically load a set of values based on the value i chose in another drop down.
In Controller I have the following code,
def ajaxGetCities(params){
println params.id
def userCustPlantDetails = utilitySummaryService.fetchUserCustPlantDetails('PHILL00')
def data = []
userCustPlantDetails?.get('UserPlantList').collect{
data << it.pwr_plt_nme
}
[data: data]
}
In gsp I have :
<g:select class="btn btn-default" name="viewValue" from="${view}" onchange="${remoteFunction(
action:'ajaxGetCities',
params:'\'id=\' + escape(this.value)',
onSuccess :'updateCity(data)')}"></g:select>
When I change the value of dropdown , i see the trigger and controller action is called. Post that Javascript updateCity is not responding. What am I missing ? What is the difference between onComplete and OnSuccess.

Grails Ajax rendering list action

Trying to render all the Contacts using ajax (This is a snippet)
So on click, it will list the contacts in a div on the update action. I have tested with a basic date function (see commented out render action Controller) to make sure ajax part could work and that does, but handling the list I have hit a wall with and going round in circles
GSP:
<g:remoteLink controller="event" action="showContacts" update="divContactList">Show Contacts!</g:remoteLink>
<div id="divContactList">Show contacts Here...
<g:each in="${contactList}" status = "i" var="contact">
<p>${contact.forname}</p>
<p>${contact.email}</p>
</g:each>
</div>
Controller:
def showContacts = {
def contactList = Contact.findAllByUser(lookupPerson())
// render "The time is now ${new Date()}"
render([contactList: contactList])
}
So overall it's not showing anything from the contactList in the web page, help on this would be appreciated
_templateName.gsp:
<g:each in="${contactList}" status = "i" var="contact">
<p>${contact.forname}</p>
<p>${contact.email}</p>
</g:each>
GSP:
<g:remoteLink controller="event" action="showContacts" update="divContactList">Show Contacts!</g:remoteLink>
<div id="divContactList">Show contacts Here...
<g:render template="layouts/templateName" model="[contactList: contactList]" />
</div>
Controller:
def showContacts = {
def contactList = Contact.findAllByUser(lookupPerson())
// render "The time is now ${new Date()}"
render(template: 'layouts/templateName', model:[contactList: contactList])
}
Clicking the remote link will send an AJAX call to the showContacts action, get an HTML answer and update the content of divContactList with the returned answer.
The showContacts action will render a template with the same name, passing it the contactList as part of the model.
If you would like the AJAX call to render the list of contacts you can try one of the following options:
Content Centric Ajax - Have the showContacts action render a template which displays the list of contacts
Data Centric Ajax - Have the showContacts action send a JSON/XML response representing the list of contacts and have a client side JavaScript code render this JSON/XML as the contact list

Using AJAX in Rails: How do I change a button as soon as it's clicked?

Hey! I'm teaching myself Ruby, and have been stuck on this for a couple days:
I'm currently using MooTools-1.3-compat and Rails 3.
I'd like to replace one button (called "Follow") with another (called "Unfollow") as soon as someone clicks on it. I'm using :remote => true and have a file ending in .js.erb that's being called...I just need help figuring out what goes in this .js file
The "Follow" button is in a div with id="follow_form", but there are many buttons on the page, and they all have an id = "follow_form"...i.e. $("follow_form").set(...) replaces the first element and that's not correct. I need help replacing the button that made the call.
I looked at this tutorial, but the line below doesn't work for me. Could it be because I'm using MooTools instead of Prototype?
$("follow_form").update("<%= escape_javascript(render('users/unfollow')) %>")
ps. This is what I have so far, and this works:
in app/views/shared:
<%= form_for current_user.subscriptions.build(:event => #event), :remote => true do |f| %>
<div><%= f.hidden_field :event %></div>
<div class="actions"><%= f.submit "Follow" %></div>
<% end %>
in app/views/events/create.js.erb
alert("follow!"); //Temporary...this is what I'm trying to replace
*in app/controllers/subscriptions_controller.rb*
def create
#subscription = current_user.subscriptions.build(params[:subscription])
#subscription.save
respond_to do |format|
format.html { redirect_to(..) }
format.js {render :layout}
end
Any help would be greatly, greatly appreciated!
The ID selector should be used if there is only one of those elements on the page, as the Id selector us for unique IDs. A Class selector is what your looking for. Classes are used for multiple elements that have the same styles or same javascript events.
The code to replace Follow with Unfollow would be as follows in Mootools. I am not totally understanding your question, but you will need to assign a ID to the button.
document.addEvent('domready',function(){
$$('follow_form').addEvent('click',function(e){
//Ajax Here
this.set('value','Unfollow');
});
});
Mootools has a different set of functions than Prototype, so most (if not all) code designed for prototype will not work in Mootools. If you want to see the functions in Mootools, I recommend the Docs (its a good read): http://mootools.net/docs/
This code would work as well for you, if you do not/can not add unique IDs to each form element:
$$('input').addEvent('click',function(){
if(this.value == 'Follow') {
//Ajax Here
this.set('value','Unfollow');
}
});

Resources