I want to grab my customers phone number from a MYSQL database and auto populate it into an input box based on users selection of customers in a prior dropdown box.
I've managed to do this in the past when filling in larger amounts of data but what I've previously used seems like a lot of code to auto fill a single input box.
I know how to fill the customer phone based on the data passed from the prior page (although I've deleted that bit here) but I want that data to change dynamically as users use the dropdown.
There's got to be an easy way to do this but I'm a complete newb at js (and only barely proficient at PHP & MYSQL). Can anyone give me a hand?
My PHP/HTML:
$result = mysql_query("SELECT cust_id, name, phone FROM customers ORDER BY name ASC");
$customers = mysql_fetch_array($result);
<label for="customer">Customer:</label>
<select name="customer">
<option value="0">Add New Customer</option>
<? foreach ($customers as $customer): ?>
<option value="<?=$customer['cust_id']?>" <?=($customer['cust_id'] == $parts['cust']) ? "selected" : ""?>><?=$customer['name']?></option>
<? endforeach; ?>
</select>
<label for="custphone">Customer Phone:</label>
<input type="text" name="custphone" value="">
Let me know if you need anything else from me and thanks in advance for helping me out on this.
For this answer, I will use the jQuery syntax, jQuery is a free javascript library, and you'll certainly use it in the future, read more.
To resume, we'll use an event triggered by your select element, when his value is changed, we'll process an AJAX request with some parameters to a PHP page (ajax.php) which returns the phone number of the customer previously choosen.
First you need to include in your HTML web page, the jQuery script, with the <script> tag.
<script src="path/to/jquery.js"></script>
In a second time, we'll create a new javascript script (assuming you add some id's to your HTML elements):
<script type="text/javascript">
$(document).ready(function(){ // When the document is ready
$("select#customers").on("change",function(){ // We attach the event onchange to the select element
var customer_id = this.value; // We retirve the customer's id
$.ajax({
url : "path/to/ajax.php", // path to you php file which returns the phone number
method : "post", // We want a POST request
data : "customer_id="+customer_id, // You'll retrieve this data in your $_POST variable in ajax.php : $_POST['customer_id']
success: function(response) { // The function to execute if the request is a -success-, response will be the customer phone number
$("input#custphone").value(response); // Fill the phone number input
}
});
});
});
</script>
Now, you've all the gear to continue, you should read about jQuery and AJAX.
You just have to create the "ajax.php", retrieve your customer id with the $_POST variable, process the SQL query to retrieve the phone number, then, return it with an echo.
Sounds like you want to look into AJAX. jQuery.ajax() makes it pretty easy.
Basically, you have a page on the server that queries the database and returns a JSON encoded string that the javascript can convert (using jQuery.parseJSON)back into an array and populate the list!
Use .change() to bind an event to the dropdown's change event. This will fire whenever the selection changes. Inside, you want to get the value (see demo on that page) and send an AJAX request to the server.
The PHP script on the server will query the database and return a JSON string. In the success function of the jQuery AJAX block you can populate the new list with the decoded information. See this page for a tutorial on how to add items to a select.
Related
My problem is that i have 2 dropdowns that get its content from my DB, a simple SELECT * with the category and then select a item from that category.
First dropdown : "dropdown_type" is the category.
Second dropdown : "dropdown_abo" is the item.
At the second dropdown, i am using a JQuery pluging that makes it possible to search inside the dropdown, to get the item faster then scrolling (theres gonna be a lot of items in it). You can see the plugin here
When you select a item from the second dropdown, a div(abo_info) below shall show all the info of the selected item.
My problem is that I'm stuck, and don't know how to proceed. How can i make it so, when i select a category, and then an item i get the content from that item shown in the div below?
I'm using PHP, JQuery and Mysql_*(to DB connect, know about PDO but im not that good at it).
Can i please get some help here, or some examples on how it can be done?
I have made a JSfiddle so you can see the complete code
You seem to be headed the correct way and doing a good job of it.
Please proceed further by using the following steps as a guideline,
Using jQuery.ajax() or jQuery.post() you can basically send a request to a PHP file.
In the PHP file you can connect to your DB using either PDO or normal mySQL connectors and return your required data back to the AJAX call.
The returned data can be rendered and displayed as required at the HTML sections.
Please use these following references that can give you a better idea code wise:
Beginner’s Guide to Ajax Development with PHP
jQuery Ajax POST example with PHP
as #WisdmLabs mentioned, you are on the right track...
The steps to continue shouls be:
Add a JS event once both dropboxes were selected (using onchange() or a submit button)
The event will fire an AJAX request for a PHP file with the POST
data of the item you want to get the data for.
On the PHP file you will run your SQL query and send back the information needed- preferable as in json.
On the JS AJAX function you will get the Json object and inserted neede info into the page DOM
JS Code
$(".dropboxClass").change(function(){ // you can use a button instead or any other event type
// here you can first check that bothdropboxes were selected
// now get the values of the dropboxes
drop1 = $("#dropbox1").val();
drop2 = $("#dropbox2").val();
// run the AJAX request for the PHP file
var request = $.ajax({
url: 'test2.php',
dataType: "json" ,
method: "POST",
data: { d1: drop1, d2:drop2 }
});
request.done(function(itemData){
// here you will get the Json object , get the data you need and insert into the DOM
console.log('Status:' + itemData['status']);
console.log('Name:' + itemData['name']);
alert('success');
});
request.fail(function(){
// AJAX call failed - do something.....
});
});
PHP Script
// connect to your DB and get the data you need into an array
$DB_data = array(
"status"=>"code",
"name"=>"item Name",
"desc"=>"Item Description"
);
echo json_encode($DB_data);
I'm not sure if this is possible since javascript is client side and php is server side, but what I have is a series of javascript functions that give a real time total to orders in a form. To clarify that, as the user selects items in the form it gives a total. On submission of the form php is submitting the order to the database. What I need to achieve is a way to submit the total (created by javascript) of the order to the database (via php obv). The javascript function that creates the total is:
function calculateTotal(){
var Price = getDropPrice() + getverifyPrice() + getmiscPrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "$"+Price;
}
The html where this is produced is pretty simple:
<div id="totalPrice"></div>
If you need me to post the other functions(getDropPrice, getverifyPrice, getmiscPrice) let me know, but basically drop is a drop down, verify and misc are radio buttons, I'm just adding their totals together to get the order total in the function above. My searches on SO and google have only shown me how to get php variables into javascript not the other way around so I certainly hope this can be done. Thanks!
Put your total in hidden input field. Then your PHP script will be able to read after the form is submited and do whatever you want.
<input type="hidden" name="hiddenInput" />
and then you get it as usual form $_POST['hiddenInput']; If you got more data to send back that way, you may either add more inputs, or stick to one but pack your all data into JSON and send that way. Once received, you do json_decode() on that field and you got it all back, no matter how many data was sent.
I, however would NOT recommend relying on user side provided data and rather send back which products are selected and calculate totals again, otherwise you may find yourself selling expensive goods for $1 one day :)
What you need is $.ajax from jQuery. This will send a POST request without reloading the page.
Lets say your button is called myButton then for the onClick() event you would call the function
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).success(function( msg ) {
alert( "Data Saved: " + msg );
});
In your some.php you would then just use $_POST['name'] and $_POST['location'] to retrieve the information.
Suppose you had an input field. You can retrieve information from such a field via jQuery as well. You can just then send the information from the input field via ajax to you php script
$('#yourInputField').val();
where yourInputField is the ID of the input field. With this you can get this information to the script. If you have multiple elements in a form you might want to look at the function serialize(). Does the same thing in principle, just compresses all the information into a JSON string.
This is why the authors made the "input" element with type of "hidden". Use one of them and set the "value" attribute of the element to the total amount that you want, then post your form to the database and you can simply access the hidden value like the other values on the form.
HTML:
<input type="hidden" id="TotalPrice_Input" />
Javascript:
document.getElementById("TotalPrice_Input").value = Price;
Hope it helps.
Mix Javascript with PHP:
<?php
$mixit = '<script type="text/javascript">';
$mixit .= 'function calculateTotal() {';
$mixit .= 'var Price = getDropPrice() + getverifyPrice() + getmiscPrice();';
$mixit .= 'var divobj = document.getElementById("totalPrice");';
$mixit .= 'divobj.style.display="block";';
$mixit .= 'divobj.innerHTML = '.$Price.';}';
$mixit .= '</script>';
echo $mixit;
?>
load different list of values(from a database) to listbox when changing another listbox value
for ex:
First list box : -select grade-
Second List box : -select Subject-
Please Help
Thank You
The basic idea is to submit that data to the server (either by POST back, or AJAX), and then respond with the data.
<select id="mySel" onChange="sendData()">
What I've done there is added a javascript function to be called every time the drop down value has changed.
function sendData() {
$.post("processData.php", {selected: $(this).val()}, updateData(data));
}
This is a skeleton of the function I'd write for the select onChange event. I've skipped a step or two here and used jQuery to help create an AJAX request back to the server. I will be calling my php script processData.php to help process which element was selected. The {} contain the data I want to send to the server, in this case the selected value. And Finally what to do once I get data back from the server.
Now I'd be in my php file and able to process the data I took in and run my query to get the new data. Once done I simply json_encode the data and respond with it.
Now back in the javascript world my UpdateData function is automatically called and passed the json data.
function updateData(data) {
var select = '<select name="sel2">';
$().each(data, function(index, val){
select += '<option name="'+ index+ '">'+ value+ '</option>';
});
$("#mySel").parent.append(select);
}
That would allow me to generate a new select list from the returned data (assuming a key/value paired array in json).
I haven't actually tested any code and it's designed to be more of a guide and pseudo-code.
When a user selects a value from one select element, send an XMLHttpRequest to get the data to populate the second select element.
I have two select box and the second select box value is dependent on the first select box. So basically what I am trying to do is that after a user makes a selection on the first select box, it will then store this value of the first select box as a variable. Then it will query my database to populate the second select box, based on the first selected value. Question is, how do I pass in the var I have in the first select box to PHP? I've read other post and people said it's impossible, but if it is then how do people do this? AJAX?
If I understand correctly, then yes, using AJAX is really your only choice.
Indeed, you can, with AJAX, call something like 'getSelectionData.php?data=' + select1.value, which returns a JSON array of data based on the selection in the first select box. You then parse the data and enter it into the second select box.
Add a onchange event listener to the first select box:
document.getElementById("select1").addEventListener("change", function(ev){
var yourstoredvariable = this.value;
someFunctionThatCallsAjax(yourstoredvariable);
}, true);
I assume that you have a Country/City dropdowns, You can do it in two ways, the good AJAX way and the bad way (refresh page on change), I'm gonna describe the good way in jQuery, or at least what I see it good.
this is the client-side (i.e. client) code:
<select id="country">
<option value="1">Canada</option>
<option value="2">UK</option>
</select>
<select id="city" disabled="disabled"></select>
<script type="text/javascript">
$('#country').change(function(){
$('#city').load('/ajax-city.php', {id: $(this).val()});
});
</script>
This is the ajax-city.php code (server):
<?php
$countryId = $_REQUEST['id'];
$cities = array(); // Get it from db, using mysql_query or anything you want to use
foreach($cities as $city) {
echo "<option id=\"{$city['id']}\">{$city['name']}</option>";
}
PS. you would need to include jQuery in your html code, and of course put the two files in the same directory (or change the $.load path).
This particular code is not tested, I've just written it. But it usually works fine to me this way.
You will have an onchange event on the first <select> that will query the server using Ajax with the value of the selected <option> that will return the <option> elements with which to populate the 2nd <select> element.
Question is, how do I pass in the var I have in the first select box to PHP?
I see no problem here.
Just usual, an ordinary html form using GET method.
What's so big about it?
If I see correct you're using Jquery. So you can do this like this:
$('#idOfSelectBox1').change(function(){
jQuery.ajax({
type: "GET",
url:"yourdomain.com/script.php",
data:"selectBox:'"+$('#idOfSelectBox1').val()+"'",
success:function(result){
//do smth with the returned data
}
});
});
in the script.php do your magic and echo what you want to pass back to js
I've done some reading on AJAX, and would like to create a listbox, that controls what is displayed in a separate textbox located within the same form. The backend of the website is handled in php, and the possible values and whatnot is stored within the MySQL database via php. What's the best way of obtaining the listbox values as well as the textbox values, and if your answer is JS, how do I create multiple selects in JS?
Well this is really a wide theme question.
My approach would be to create a listbox with php and put an onchange event that will call an ajax with value parameter, that ajax call will fill textbox.
You should use jquery, read some documentation here http://docs.jquery.com/Main_Page
multiple select listbox
<select id="choices" multiple="multiple" .. >
If you were using jQuery you could do something like:
$("#choices").change(function() {
var choices = {};
$("#choices option:selected").each(function() {
choices[this.id] = $(this).val();
});
$.post("http://example.com/choice_handler.php", choices, function(content) {
$("#textarea").val(content);
});
});
choice___handler.php would look at $_POST to retrieve the id/value pairs and produce content that would be returned and then assgned as the value of a textarea.
Note: i haven't tested/debugged any of this - just some code sketching here