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 :).
Related
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 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);
There are lots of inputs in a single page... These inputs are need to be posted to server to generate custom documents. In other words, every each element will be used on serverside.
Traditionally
Every input can have a name. So, at server-side php can get all these inputs by
$_POST[nameOfInput]
Or
Every input tag can be listened by jquery and on change, values can be saved to an array and post to server by ajax later ... so php can get these values as in javascript ... by
$.ajax({
url: baseUrl+"chat.php",
data: a,
type: 'post',
success: function(data) {
alert(data);
}
})
But in this project i got little bit confused about these method because;
On this page, number of the inputs and number of input types are dynamic. While user fills the input. According to values typed by user,simultaneously, new input elements are generated. So i am able to post these values to server but i dont have any idea about how to use these in a php page.
I have a very complex form which contains multiple tabs. Each tab contains a unique Plupload instance (for uploading multiple images). The form allows a user to upload a medical image 'case' where each case is made up of multiple imaging 'studies' (e.g. CT scans) and each study contains multiple images.
When the user clicks the 'submit' button, I intercept the click with jQuery because I need to do the following:
Check the required fields are entered [easy]
Get a unique id number from my server. This id number is required by each Plupload instance to know which directory to upload to.
In my function called upon form submission I have the following code snippet:
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
});
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
return false;
}
With my current logic, I need the script to pause UNTIL it gets case_id. This was possible before jQuery 1.8 but the $.ajax() async : false property has been deprecated.
My question is two-fold:
Is there a way to hold up the script until I get the required case_id?
If not, any idea how I could change my logic to work around this?
You might be wondering why case_id is so important. The plupload instances do their upload before the form submits and they need a directory to upload to. I want the images being uploaded to go into a folder on my server called case_id. This will let the PHP script on the server figure out what to do with them once it gets the rest of the form POSTed data.
This is a very common 'problem' that can be solved pretty easily by using callbacks appropriately.
$("#submitButton").click(function (event) {
event.preventDefault(); //Don't submit the form, we'll submit it manually.
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
alert("something went wrong");
} else {
$("#referenceToTheForm").submit();
}
});
});
Long story short, keeping the "deal with problems or submit the form" inside of the callback to the $.get call will essentially cause the script to 'pause' until it gets the data back. Then you can use something like spin.js to give the user a good waiting experience until it's done.
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.