Populating Inputs Based on HTML Dropdown Selection - javascript

I know there are many questions like this one on Stack Overflow, but I am really needing something more related towards what I am doing...so that is why I am posting this question.
I have an HTML form with PHP that pulls data from an MSSQL database in order to populate a dropdown box. I want to be able to populate the contact information text boxes once I select a name from my dropdown box. So far, I have it to where, if I select a specific vendor, the vendor name gets entered automatically into the Name, Email, and Phone Number fields. However, I want to have different attributes entered into the text fields and not the vendor name itself. How could I do this?
The fields from my database with the name, email, and phone number that I want imported are named MR_POC_N, MR_POC_E, and MR_POC_P
Also the "MR_Name" that you see is the field with all names of the vendors FYI
Here is my code for the HTML dropdown:
<select name="vendor_dropdown" id="ven" onChange="updateinput();">
<option value="">Choose a Vendor</option>
<?php foreach($users->fetchAll() as $user): ?>
<option><?php echo $user['MR_Name'];?></option>
<?php endforeach; ?>
</select>
Here is my Contact Info code:
<table align="center">
<tr>
<td align="right">Name:</td>
<td><input class="textbox" type="text" id="name" name="name"></td>
</tr>
<tr>
<td align="right">Email:</td>
<td><input class="textbox" type="email" id="email" name="email"></td>
</tr>
<tr>
<td align="right">Phone Number:</td>
<td><input class="textbox" type="tel" id="tel" name="number"></td>
</tr>
</table>
Here is the update input function I have in JS. I know this is off but looking for some sort of direction as I am not the best in JS:
function updateinput() {
var e = document.getElementById("ven");
var venSelected = e.options[e.selectedIndex].value;
document.getElementById("name").value=venSelected;
document.getElementById("email").value=venSelected;
document.getElementById("tel").value=venSelected;
}

Keep your script the same as it currently is but change your JavaScript and the dropdown. In your dropdown try doing
<option value = "<?=$user['MR_Name'];?>"><?php echo $user['MR_Name'];?></option>
You want to make what's called an AJAX request. This will allow you to go off to another page get some data in your case you would be getting some user information, and return it to the page, without the user physically changing page!
Check this link out for more information on AJAX.
Your AJAX call will look something like this.
function updateinput() {
var e = $("#ven").val();
$.ajax({
url: "get-user-info.php",
type: "POST",
data: {e: e},
success: function(data){
data = JSON.parse(data);
var email = data[0];
var tel = data[1];
$("#email").val(email);
$("#tel").val(tel);
}
});
}
This script first gets the selected value of the dropdown. Then it starts the make the AJAX call, it's like submitting a form, we are POSTING the values across to the next page. So the page the AJAX will talk to is get-user-info.php it's posting the values from data. The data is sending across e which is what the dropdown value is. On success it will then do the code underneath which is saying parse data from a PHP array to JavaScript and then it is saying email is the first value of the array and tel is the second value from the array. Then we are saying the input with ID 'email' now equals email from the array and the input with ID 'tel' now equals tel from the array.
You will now need to create a php script in the same directory called get-user-info.php
In this script make a call to your database where the user is the same as the selected value e and return a PHP array that looks like this:
array(email, telephone)
This is pseudo-code for your PHP script get-user-info.php:
<?php
$e = $_POST["e"];
//Do your SQL
//In the loop
$array[] = $user["email"];
$array[] = $user["tel"];
echo json_encode($array);
?>

Related

Is there a way to display live calculation with an information taken from mysql database?

I am developing a web application, and I need to display a live calculation as soon as the fields are filled with the information.
What I mean by a live calculation is something as live as a ng-model in a ng-app. The problem goes like this:
The user chooses a product from a dropdown list, which list's choices are coming from a mysql database and the price of the chosen product should be the first multiplyer, while the second multiplyer is the next input field where the customer should enter how many pieces they want.
I tried to take the price from the table where product is selected but I believe that php needs a submission in order to process the data and actually see which product has been selected.
So is there any way to display a live calculation and inform the customer how much their order will cost before they submit the form?
Thank you!
Update:
I came few steps further along the way but i got stuck again... so now i do retrieve the value of the chosen product but i fail to do the calculation because javascript says that the retrieved value is not a number (NaN) as soon as i try to do the operation.
This is the code that shows the value of the chosen product
<form action="#" method="POST">
<input type="text" name="clientname" class="fields" placeholder="Enter your name " required/>
<input type="text" name="contactinfo" class="fields" placeholder="Phone or Email" required/>
<input type="text" name="address" class="fields" placeholder="Street Address" required/>
<select class='dropdown' name='ordertype' id='ordertype' onchange='productPrice()' required>
<option value="" disabled selected>Select Product</option>
<?php
$query = "SELECT * FROM products";
$query_run = mysqli_query($mysqli, $query);
while($row = $query_run->fetch_assoc()){
echo"<option value=".$row['price'].">".$row['name']."</option>";
}
?>
</select>
<input ng-model="price" type="number" name="amount" class="fields" placeholder="How many pieces?" required/>
<button name="placeorder" class="regbutton">Place Order</button>
</form>
<script type="text/javascript">
function productPrice(){
var option = document.getElementById("ordertype").selectedIndex;
var value = document.getElementById("ordertype").options;
var result = (value[option].value);
document.getElementById("result").innerHTML = result + "$";
}
document.write('<p id="result"></p>' );
</script>
but the moment i try to do the calculation and multiply the given output * {{price}} or even when i try to multiply it * 2 it says NaN on page load (it has nothing to do with the dollar sign).
So do you know why is this happening and how can i fix it?
Thanks again!
Your PHP code isn't going to know when the data changes, so even though you could use comet or websockets to get data immediately from the PHP code to the browser, you still need to poll the database for changes. It's simpler to just trigger the polling on a schedule from the browser using Ajax.
This will give you idea,
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
<div id="result"></div>
demo_sse.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
use jQuery ajax call.
go step by step.
1st get the qty of any product or any thing that the have changed.
on ajax call i guess you are creating a cart. let every thing same just add product or any thing to the cart of your. and get the hole data.
append the recent value.
in this way the amount you have stored in php that you can have at your client side using ajax call

Dynamically fill multiple input fields from MySQL depending on the drop list item selected

I've searched through the site for this but am coming up empty handed. Here is what I am trying to do:
User selects one of a series of options from a drop list
Two input fields change to reflect this selection, filling the input boxes with data pulled from my database
See the image below for a visual representation of what I mean:
I know that I am going to need JavaScript for this solution, but my JS skills are not so hot (and I think I am having a momentary lapse of brain power today)!
Here's the code that I have so far (don't worry about the outdated PHP):
<select name="item" id="item">
<?php
while($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
$item_category = $row['item_category'];
$item_title = $row['item_title'];
$item_price = $row['item_price'];
$item_description = $row['item_description'];
echo "<option value=\"".$item_id."\">".$item_title."</option>";
}
?>
</select>
<script>
function update_txt() {
price = document.getElementById('item').selectedIndex.value;
document.getElementById('item_details').value = price;
document.getElementById('item_price').value = price;
}
</script>
<input id="item_details" type="text" class="validate">
<input id="item_price" type="text" class="validate" value="$">
Any help is greatly appreciated! Let me know if you need any clarification. :)
I would json encode the row and store it as a data-attribute on the option, then read the attribute on the selects change event:
<select name="item" id="item">
<?php
while($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
$item_title = $row['item_title'];
echo "<option value=\"".$item_id."\" data-json='" . json_encode($row) . "'>".$item_title."</option>";
}
?>
</select>
<input id="item_details" type="text" class="validate">
<input id="item_price" type="text" class="validate" value="$">
<script>
$('#item').on('change', function() {
var selected = $(this).find('option[value="' + $(this).val() + '"]').data('json');
$('#item_details').val(selected.item_description);
$('#item_price').val(selected.item_price);
});
</script>
You can use a combination of PHP, AJAX and JavaScript (or jQuery).
The general idea is as follows:
User selects an option(s)
JavaScript is used to detect the selection and the option(s)
selected
AJAX gets the options selected, formats it and passes it to a PHP "page"
PHP does the SQL queries and passes the values back
AJAX gets those values and populates the current page using standard JavaScript methods
There's a good tutorial here which shows how it fits together: http://www.tizag.com/ajaxTutorial/ajax-mysql-database.php. I would use prepared statements instead of the SQL queries shown in this example though.

Take ID From Form Option & Use It To Populate Multiple Fields

I have looked throughout the site and nothing has quite matched what I'm after. I have a form which starts of asking the client to choose the company name from a dropdown. The dropdown is populated from a query as such:
<select name='company_name' id='dropdown'><?php
$result = mysqli_query($con,"SELECT ID, TITLE FROM b_crm_company");
while($row = mysqli_fetch_array($result))
{
$companyName = $row['TITLE'];
$companyID = $row['ID'];
print "<option value='$companyID'>$companyName</option>";
}
?></select>
I then have 3 forms text fields that I need pre-populating based on what is selected from the above and I'm not sure how to do it. So my next three form fields:
<input type="text" value="$contactName" name="contactName">
<input type="text" value="$contactTelephone" name="contactTelephone">
<input type="text" value="$contactEmail" name="contactEmail">
The select statement I'd need to get these three values:
SELECT COMPANY_ID, NAME, TELEPHONE, EMAIL FROM b_crm_contact
WHERE COMPANY_ID = $companyID
The $companyID obviously being pulled from the dropdown at the start. How can I pull the information to the next fields? I'm assuming javascript but not sure how to write it.
Thanks in advance
you need to call ajax on click of your drop down select item
and then need to return string or json from that php file and then parse and put values in appropriate fields
something like this:
$("button").click(function(){
$.ajax({url:"demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});

Getting data that was posted from form

I have a simple drop down box inside a form. When a search button is clicked the value that was selected in the box is posted. I need to get the value that is posted, back and put it in a variable so I can add that field to a DTO and then run a database search based on what the field was. I want to use jquery to post and get the data back but unsure how to do this so Im just using plaing javascript for the post.
Javascript:
<form name="values" method="POST" action="MainPage.jsp">
<tr>
<td>
<select name="searchDropDown" id="searchDropDown">
<option value="Volleyball">Volleyball</option>
<option value="Basketball">Basketball</option>
<option value="Hockey">Hockey</option>
<option value="Soccer">Soccer</option>
</select>
<input type="submit" value="Search Video">
</td>
</tr>
</form>
Jquery:
<script>
$(document).ready(function() {
SportsDTO dto = new SportsDTO();
SportsDAO dao = new SportsDAO();
var searchValue = $('#searchDropDown').val();
dto.setSport(searchValue);
dao.findBySport(dto.getSport);
});
</script>
I know the DAO and DTO work because I have a junit test written that passes
Just need to get the value back so I can run the database search and return the values into a table.

ajax display text on submit

I have a simple form with a submit button (below). I am trying to let the user type in the text box then when he/she clicks submit the page will refresh and echo out what they typed in a div. The data the user types is stored in a database before being echoed. The problem is that when I click submit, the input doesnt show immediatly. I have to click refresh for it to show and when I do my browser gives me a popup (safari) asking to resend the data. This will result in duplicate data inserted in the DB. I have a feeling I need to use javascript and I could also make it more elegant with a fadeIn, but I dont know how to do that. I guess I'm asking if there's a way to use javascript to take a user's text and insert it into a mysql DB and also display it after submit is clicked all on 1 or 0 (prefereably) refreshes. thanks
Here's my code:
<form method='POST' action='index.php'>
<input type='text' name='text' id='text'>
<input type ='submit' value='submit' name='submit'>
</form>
<?php
$input=$_POST['text'];
$put=mysql_query("INSERT INTO table VALUES ('$input')");
echo "<div id='area'>";
//i connect to the DB and echo out the data here
echo "</div>";
?>
I would put the php statements before you're actual html code and would modify you're code like this
<?php
if (isset($_POST['text']))
{
$input = mysql_real_escape_string($_POST['text']);
$put=mysql_query("INSERT INTO table VALUES ('$input')"); //At this point the info has been put inside the DB
echo "<div id='area'>";
//i connect to the DB and echo out the data here
echo mysql_query("SELECT * FROM table");
echo "</div>";
}
?>
<form method='POST' action='index.php'>
<input type='text' name='text' id='text'>
<input type ='submit' value='submit' name='submit'>
</form>
The reason why you don't see it is that the HTML is loaded before you php I think. So I would do a php page where all the sql treatement would be done and once that is done recal you index.php and in there query you're information from the database.
Setting aside SQL injection attacks your code is vulnerable with, the standard practice is to respond to the POST with a redirect back to where the form was. In your case, it will be the page which runs SELECT from table.
No need to use AJAX here. Just make sure that you do one of the following:
Make sure you SELECT from the DB after you have INSERTed the data.
Better, is that if ($_SERVER['REQUEST_METHOD'] == 'POST'), then rather than performing an extra SQL query, just display the POSTed value since you already know it.
A side note on your code sample. If you don't have magic_quotes enabled, it's susceptible to SQL injection, so make sure you properly escape user input before using it in queries.

Categories