I am doing a fixeddeposit project, in which I am having three models:
1)fixeddeposit
2)interestrate
3)interestsetup
When I open a fixeddeposit, I have to type the number of days(365/730/1095/1460 & 1825) from number_field. Then in another text box I want to update the rate_of_interest based upon the number(365/730/1095/1460 & 1825) I typed.
Rate_of_interest should be taken from rate which is in the interestrates table field. Kindly see the screenshot of my interestrates table below.
Interestrates table
Example:
If i type number 365 in fixeddeposit form(which is number_field). It automatically select rate 9.5% from interestrates table using AJAX function.
And, if a customer age is above 58, and i type number 365 in fixeddeposit form. It automatically select (rate 9.5% + senior increment 0.5% ) = 10.0% from interestrates table using AJAX function.
Screenshot of FD
I googled it for a solution but, results showing with collection_select alone. I want to do the same in number_field. Though, i am new to Ruby on Rails and AJAX i am struggling with it.
I see that the rate is dependent on Time Period and Date of Birth. So, one way to do it is to attach an event listener to the two input fields. So let's say, dob input field has id = dob, you can write simple jQuery to attach a listener like $("#dob").change()....
Now, inside the listener function, you update the value of Rate of Interest based on the values of Time Period and DOB. For this, you could write the ROI logic in the code or send an ajax request to Rails app and get Interest Rate from there.
Lets go through the steps of ajax in rails
a. Create a route for your custom action, since we want to send data so it'll be post request
post "/rate" => "your_controller#calculate_rate" , as: "calculate_rate"
b. Write a javascript code that will listen to your periods input field.
$(document).on("change","#id_of_periods_input",function(){
var periods = $(this).val();
var age = $("#id_of_age_input").val();
$.ajax({
type: "POST",
url: "/rate",
data: { periods: periods, age: age } //this will enable you to use params[:periods] and params[:age] in your controller
});
});
This will work but i think it'll be better if you have some sort of button and when user clicks on it then calculate your rate of interest because if you'll use on change event then then lets say your periods value is 365 so your ajax call will fire 3 times( first time when you enter 3 then for 6 and then for 5)
If you want to use button then also you have to use same logic only this line will change
$(document).on("click","#id_of_btn",function(){
// same logic
});
c. Getting your data in controller and performing your logic
def calculate_rate
#periods = params[:periods]
#age = params[:age]
// perform your logic here and store rates value in lets say #rate
respond_to do |format|
format.js{} #this will make rails look for a file named calculate_rate.js.erb in your views
end
end
d. Filling rates input field by writing js in calculate_rate.js.erb
$("#id_of_rate_field").val(#rate);
Related
I currently have User model that has the name attribute and am using ajax to grab selected data.
JS looks like this:
$("#save").click(function(){
var checkedUser = [];
$.each($("input[name='selected_user']:checked"), function(){
checkedUser.push($(this).val());
});
$.ajax({
type: "POST",
url: "/users/<%= current_user.id %>/friend",
data: {checked_user: checkedUser},
})
controller action:
def friend
user = User.find(params[:user_id])
checked_user = params[:checked_user]
#user = User.where(id: checked_user)
end
I want to build a function that updates the data records based on checkbox input and want to give time range.
For example, if there is a user and has a friends list and the user checks friend 'A' and submit, the friend A should not show on the user's friends list as checked as block for set time (could be 24hrs or 10hours) and once time's up, I want them back to the list again so it is like:
user -> set friend A as not to show for 10mins -> showing friend A as checked on the friend list -> after 10mins -> the friend A is showing again.
Q1) Should I make a new attribute that has boolean type then do update the attribute? or is there any better way to do this?
Q2) How to handle the times like if I wanted to uncheck the checked user after 10mins, should I use JS?
1) I would add two attributes, duration and checked_at, or maybe just one like expires_at. This will make #2 easier.
2) You will want to use a worker to schedule a periodic background job, using it to delete any entries that have expired.
I have table user where id = primary key, lastchange = int with lastchange data (in seconds). And i have frontend page with js script. Also all users placed in div like table by pages. So, items has user id and used changed timevalue in attributes.
I want to request all changed user ids in 1 request (1 http and 1 sql). They can be changed by other user on site.
How can i do this? I dont want check every user in page by timer, there is too many requests.
In my mind it looks like:
js do get request with list of users in page in json format [{"id":1, "lastchange":123123},{"id":2, "lastchange":123123}...
Php does request in mysql like SELECT * FROM `users` WHERE `id` IN (1, 2, 3) AND `lastchange` NOT IN (123459, 123456, 123459); (this not works fine, there is no queue for lastchange, it checks all inside braces and result are wrong)
Php return only ids of different rows [1, 15, 22] etc. to js.
Js check every id separately in other request getting full info about user by id
I can check every user in php separately, but i want to know how can i do it with 1 SQL request
Sorry my bad English.
I think you might want to implement the solution differently as per the first comment.... but, if you want keep your current model the SQL you need would look something like:
SELECT * FROM users WHERE
(id = 1 AND lastchange <> 123123) OR
(id = 2 AND lastchange <> 123123) OR
...
This will keep the id's and the lastchange values that relate to each other being compared properly. It is pretty ugly SQL but not hard to generate in a loop.
Sorry my stupidness. I think i solve this.
Js request api with only user id in page
php response json like id, lastchange
js checking lastchange value and id in page
js request full data about changed user replaces old in page
Thx all for helping
I am continuing to work on my multi stage bootstrap form, and I have hit a roadblock trying to pull info from my DB.
The main page is PHP and is named quote_tool.php
I have the following functional requirements:
The data must come from the MySQL database.
The user should only receive data that they requested (i.e. a row from the db with info about user license should only be grabbed if the user checked a radio button to include user licenses on the form).
The information needs to be called from the DB without refreshing/reloading the page.
Currently I have a table in my DB with the following columns:
There are 3 different products in that table right now. The user can select a radio to say they want to include endpoints, and then there are 3 check boxes to allow the user to input a quantity for which endpoint(s) they want to include.
The input field looks like this:
<label for="device-9102" class="form-partner-label"><input type="checkbox" class="quote-chkbox" id="9102-chk"> 9102 IP Phone</label>
<input type="text" name="9102-quantity" class="form-endpoint-qty form-control" id="form-partner-9102" readonly value="0">
When the user checks the box and input a value this value is dynamically updated on the summary page as well in the following field:
<input type="text" readonly name="sum-9102-qty" class="summary-field sum-qty" id="sum-9102-qty">
There is also 2 other fields on the summary page regarding this product.
MSRP
Part Number
MSRP is a hidden field that will be used for additional calculations, but Part Number is visible on the summary page.
When the user inputs the value for the endpoint quantity I need to call the DB and pull the MSRP and Part Number from the refEndpoints table.
I am currently building a function to call the DB when the user hits the "Next" button on the form, and that looks like this:
//Call DB to fetch part number and msrp of 9102
$('#form-partner-9102').change(function()){
var quantity_9102 = $('#form-partner-9102').val();
if(quantity_9102 !== 0) {
}
});
This is the point that I am stuck at. I am not sure how to call the DB and place the values of the part number and the MSRP in the correct input fields on the summary page.
jQuery runs on the client side so it cannot connect to MySQL directly, however your question is tagged php, which runs on the server side and thus can connect to your database. First you will need to setup a PHP file that can respond to HTTP POST requests and return JSON. Here is a great answer that shows you how to do this: Returning JSON from PHP to JavaScript?
Once set up (and you will need to workout what parameters this PHP file takes in and how it converts this into a query so that it can respond) you can now setup some simple JavaScript to call this PHP file (lets call it query.php). Code that does this might look like this:
$.post('/query.php', {quantity: $('#form-partner-9102').val()}, function(resp) {
$('#PartNumber').html(resp.PartNumber);
});
Some important things to keep in mind are to always be sure to use prepared statements when taking user input and turning it into a query (don't just build a SELECT statement by joining strings). Also be sure to look at your event binding, you can probably write one generic handler for your inputs that takes the partner ID as a data-* attribute making your code smaller and easier to maintain.
I have an HTML form to update the address in the account that submits to a Java servlet.
The problem is that, the form should not accept free flowing address text. Instead the user should enter the zip code/house number/street name, and hit a search button.
This search needs to go to a webservice, perform authentication and get a list of valid addresses that match the search criteria.
This list of addresses should be displayed to the user in the same form (either unhide a hidden element or use a modal dialog), so the user can pick his address.
Only after the valid address is picked, the user should be able to hit the form submit button which sends the data back to the servlet.
I am not sure how to have these 2 buttons do different actions in the form. I am very new to JavaScript and any pointers or examples are much appreciated.
For your webservice build an output of the values based on a search result (a basic string). Put this data in a JSON statement or just a javascript array.
Return something that looks like this.
['SearchResult1', 'SearchResult2', 'SearchREsult3']
On your search box. Bind a function on change or blur.
$('#SearchBox').bind('change', function(){
var val = $(this).val();
//Please reference the Jquery Ajax function as im typing this from memory and i always mix one or two things up :).
$.ajax({
"type" : "post",
"url" : "yoururlhere",
"data" : { "search":val },
success : function(dataset){
//When it comes back here check to see if its valid data etc etc
//After you validate you can populate a picklist on the page with the values. Or do anything you want with the values like this
for(x in dataset){
$('#DocumentElement').append('<p>'+ dataset[x] +'</p>');
}
}
});
});
This should start you out. After that you can just do more things on the callback, or modify the dom in a way which suits you better :).
Hello people
I'm trying to figured this out, but I still can't do it.
I have a rails 3 app, I'm working with invoices and payments. In the form for payments I have a collection_select where I display all the invoices number (extracted from a postgres database), and what I'm trying to do is when i select an invoice autopopulate others text_fields (provider, address, etc.) without reloading the page, in the same form.
I know I should use ajax, js, jquery, but I'm a beginner in these languages, so i don't know how or where to start
hope you can help me... thanks
What you are going to want to do is route an ajax call to a controller, which will respond with json containing the information. you will then use jquery to populate the different fields.
In your routes:
get "invoice/:id/get_json", :controller=>"invoice", :action=>"get_json"
In your invoice_controller:
def get_json
invoice = Invoice.find(params[:invoice_id])
render :text => invoice.to_json
end
In your invoice model (if the default to_json method is not sufficent):
def to_json
json = "{"
json += "id:'#{self.id}'"
json += ",date_created:'#{self.date}'"
... //add other data you want to have here later
json += "}"
end
In your javascript file,
$("#invoice_selecter").change(function(){ //calls this function when the selected value changes
$.get("/invoice/"+$(this).val()+"/get_json",function(data, status, xhr){ //does ajax call to the invoice route we set up above
data = eval(data); //turn the response text into a javascript object
$("#field_1").val(data.date_created); //sets the value of the fields to the data returned
...
});
});
You are probably going to run into a few issues, i would highly recommend downloading and installing fire bug if you are not on google chrome.. and if you are, make sure you are using the development tools. I believe you can open them up by right clicking and hitting inspect element. Through this, you should be able to monitor the ajax request, and whether or not it succeeded and things.