Integrating href with $_GET value into a select option - php

I am trying to get some data of a certain item selected in a select option and automatically display it on the textfield as shown in this image:
But it is not working. Is there a remedy for this or such type of coding is not workable at all? Hopefully someone can help me on this.
Here is the code I made:
$credit_accounts = $db->query("SELECT * FROM credits");
echo'<select id="customer_order_id" name = "customer_order_id">
<option value = "">SELECT ACCOUNT</option>';
foreach($credit_accounts as $key){
$id = $key['purchase_order_id'];
$name = $key['customer_firstName']."\t\t".$key['customer_lastName'];
echo'<option value = "'.$id.'">'.$name.'</option>';
}
echo'
</select>';
Note: The link will execute a query that will retrieve certain data of the selected item. If link is declared outside the loop without the <option></option> tag, it works accordingly. But if it is place within the loop of course with the <option></option> tag, it is not working like a link at all. Please help me out.

Sorry for my english , I will write some long answer hopefully it will also help others,so i am giving solution for doing following.
Please not : this solution is written and use SIMPLE MYSQL,AJAX and PHP function If you further want DATA SECURITY refer [PHP MySQLI Prevent SQL Injection
Objective : To get/display DATA from DATABASE related to a particular(ly 1) user/product and then fetch/display it in HTML page (additionally: without page refresh ) IN A FORM.
CODE :
<?php
//php-database connection script
$db_config = mysqli_connect("localhost", "username", "pass", "database_name");
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
?>
<?php
//this pHP SCRIP FIRES when you select a USERNAME (if u want not to SELECT but type then change ONCHANGE to ONKEYUP function & change username input type to text)
if(isset($_POST['uname'])){
$u = $_POST['uname'];
$sql = "SELECT email , gender FROM credits WHERE username='$u' LIMIT 1";
$query= mysqli_query($db_config,$sql);
while($row2 = mysqli_fetch_array($query)){
//Here we form a STRING SEPRATED BY QUAMMAS and ECHO IT TO PAGE
//later on we will fill this data in input fields
echo $row2['email'].",".$row2['gender'];
exit();
}exit();}
?>
<!-- HERE is your form where user will select or type his username-->
<form >
Select username :<br/>
<select id="user_name" onchange="load_data()">
<option value=""> select an ouser</option>
<option value="v1111"> v111</option>
</select><br/>
Email<br/>
<input type ="text" id="email" value=""><br/>
Gender :
<select id="gender">
<option value='m'>male</option>
<option value='f'>female</option>
</select>
</form>
<span id='status' ></span>
<script>
//AJAX OBJECT CREATION script it works as get or post mechanism
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState === 4 && x.status === 200){
return true;
}
}
//here is function which fires when username is selected
function load_data(){
var value = document.getElementById('user_name').value;
//declare ajax obj, and name(url) of same page you are coding.
var ajax = ajaxObj("POST", "url.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var str = ajax.responseText;
//split STRING and extract individual data
var res = str.split(',');
//here we fetch his username into input field BINGO!do same for gender.
_('email').value = res[0];
//res[1] will have gender related data.
}
}
//Declaration to send URL encoded variable (username in this case)
ajax.send("uname="+value);
}
</script>
If you want further resources and info about data security see BRAD's comments in comments section

Related

How to get in a variable the value of the selection of a Select/Drop Down Menu PHP or HTML

I'm trying to connect 2 drop-downs so in the first I show a list of countries and based on the selection of the country I show a list of the cities for the country selected.
I have my index.php file which load all the countries correctly as seen in this image:
Code to load my countries
<select name="country" id="country">
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$query = "SELECT country FROM countries";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value=Select>Select a Country</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[country]>$myrow[country]</option>");
}
?>
</select>
Now I'm trying to do the same based on the selection from the previous "Select" but it is not working. The issue I'm having is getting the value selected in the country select because if I hard-type a value of a country like: $query = "SELECT city FROM cities where country = Albania"; then it works. Also I tried to print the value of the country selected: (echo $selectedCountry;) and it not printing anything so I'm guessing neither $selectedCountry = $_GET['country']; or $selectedCountry = $_POST['country']; are getting the value of the country selected.
<select name="city" id="city">
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$selectedCountry = $_GET['country'];
$selectedCountry = $_POST['country'];
echo $selectedCountry;
$query = "SELECT city FROM cities where country = ' $selectedCountry '";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value=Select>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[city]>$myrow[city]</option>");
}
?>
</select>
Thank you very much in advance
UPDATE
This is what I see in the first Load. Where the country Select is loaded with all the values as per the image above and the city Select is empty (Only the "Select a city" value) waiting to be loaded with the values depending on the country selection.
LAST UPDATE - From Borna Suggestion
Borna,
I've tried your suggestion, below the exact code that I'm using. Using two countries as example. However, the cities are empty the first load and when I select a country nothing loads in the city Select and I get the following screen. It seams that it is actually not calling/running the getCities.php:
Index.html
<!DOCTYPE html>
<html>
<head>
<script>
function populateCities(citiesSelectBoxOptions){
document.getElementById("city").innerHTML = citiesSelectBoxOptions;
}
function httpGetAsync(theUrl, callback)
{
alert(theUrl);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
</script>
</head>
<body>
<select name="country" id="country" onchange="httpGetAsync('http://localhost/FillCity/getCities?country=' + this.value, populateCities)">
<option value="Angola">Angola</option>
<option value="Spain">Spain</option>
</select>
<select name="city" id="city">
</select>
</body>
</html>
getCities.php
<?php
include("config.php");
$db = pg_connect("$db_host $db_name $db_username $db_password");
$selectedCountry = $_GET['country'];
echo "country: " .$country;
$query = "SELECT city FROM cities where country = ' $selectedCountry '";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value='Select'>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value='$myrow[city]'>$myrow[city]</option>");
}
?>
UPDATE
If I run http://localhost/FillCity/getCities?country=Spain this is what I get
If I run just http://localhost/FillCity/getCities.php I get: (I'm getting the word country because I place and echo $country in the code to see the country selected)
This is my FillCity folder under my localhost (var/www/html)
And here is what I see when running the Index.html for the first time with Angola as default country.
If I select any country, Spain, as example this is what I get
LAST UPDATE
When I open the .html file and I select a country this is what I get (Still printing out that message on the screen):
Once I click Ok then it works and I can see all the cities for the country (But of course I would like not to have that message popping up)
Thanks again
Well, what you really need is AJAX call which allows you to communicate with server without reloading a page. All you have to do is basically send a new HTTP request with a country parameter to get the list of cities in it. The correct way would be to send (HTTP response) only the data(cities) in JSON or similar format, and not its presentation also (html), but for simplicity, you can continue to work like you started (return data with html).
Start by separating the code that generates HTML selectBoxOptions of cities in another script.
You will use that script to get the list of cities in particular country by using AJAX (XMLHttpRequest library).
Have a look at this, it's a working solution of your problem. HTTP request is sent whenever user changes the countrySelectBox option, that way your cities select box gets updated every time it needs.
All you have to do is change the url in the onchange attribute that points to your script (I previously said that you should move 2nd block of code into separate script).
<!DOCTYPE html>
<html>
<head>
<script>
function populateCities(citiesSelectBoxOptions){
document.getElementById("city").innerHTML = citiesSelectBoxOptions;
}
function httpGetAsync(theUrl, callback)
{
alert(theUrl);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
</script>
</head>
<body>
<select name="country" id="country" onchange="httpGetAsync('www.yourdomain.com/getCities.php?country=' + this.options[this.selectedIndex].value, populateCities)">
<option value="Country1">Country 1</option>
<option value="Country2">Country 2</option>
</select>
<select name="city" id="city">
</select>
</body>
</html>
getCities.php
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$selectedCountry = $_GET['country'];
$query = "SELECT city FROM cities where country = ' $selectedCountry '";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value='Select'>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value='$myrow[city]'>$myrow[city]</option>");
}
?>
EDIT:
httpGetAsync is native (only pure/vanilla javascript is used. No other libraries are used) javascript function that enables you to send HTTP request without reloading a page. I see you are using jQuery, which hides this function's complexity, same as form->submit, but I recommend you to learn how httpGetAsync works, because using a jQuery for such a simple task is overkill.
You don't need this javascript function
function getCity(countryId)
Instead, you should put your code that communicates with database in a .php file, not in javascript (remember, javascript is a client side, it executes on client machine, e.g. browser, while php executes on server). Your SQL should never be written in javascript. Client side code cannot communicate with a database directly, only through server side coding. To accomplish that, you must return a value of PHP script getCities.php back to the client(javascript) as a HTTP response.
When you send a HTTP request to some .php file, that scripts executes on a server, and everything that you said "echo" or "print", on the end of script, is automaticaly sent as HTTP response. You don't actualy have to write any code to send a HTTP response. Its done automaticaly. You just have to echo/print whatever you need on the client side. In your case, you need to print options for particular country.
How the script knows for which country it needs to select cities from database?
Well, you send HTTP request with a parameter "country". That is what you Form is doing automaticaly when you submit it. All HTML tags that are inside Form, and have a name attribute set, are gonna be send in HTTP request as parameters. But, since you cannot use submit, you must do this manualy.
To send a parameter inside HTTP GET request is very simple.
Have a look at the following url:
localhost/getCities?country=countryX&someOtherParam=something&myThirdParam=something3
On server side, the following variables are gonna be populated:
$_GET["country"] // value is 'countryX'
$_GET["someOtherParam"] // value is 'something'
$_GET["myThirdParam"] // value is 'something3'
To learn more about how GET and POST works, and what is the difference, check this
Get started by creating a getCities.php file, and copy paste the code that communicates with database and generates city options. It's basically what you already did, you just have to put that code in separate .php file. So, when a client (browser) asks for a list of cities in particular country, you are going to send a HTTP request (using httpGetAsync() function) to get that list from the server.
In your index.php copy paste this script
<script>
function populateCities(citiesSelectBoxOptions){
document.getElementById("city").innerHTML = citiesSelectBoxOptions;
}
function httpGetAsync(theUrl, callback)
{
alert(theUrl);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
</script>
Next, put onchange attribute on select box, remember, its all lower case, not onChange.
<select name="country" id="country" onchange="httpGetAsync('localhost/getCities?country=' + this.value, populateCities)">
For any question just ask... :)
Well, I suppose one way to do it would be with jQuery.
There's probably a few different ways to do this, but what you could do, is load all the cities into the city drop-down, regardless of country, but change the printf for the city options like this.
$query = "SELECT city, country FROM cities";
....
while($myrow = pg_fetch_assoc($result)) {
printf ("<option class="$myrow[country] city_select" value=$myrow[city]>$myrow[city]</option>");
}
And then in the javascript for the page, have something like
$('#country').bind('change', function(){
var country = $(this).val();
$('#city option.city_select').hide();
$('#city option.'+country+'').show();
});
It's not necessarily the most elegant solution, though.
You are missing the quotes inside your option, it should be something like
<option value=$myrow['city']>$myrow['city']</option>
try that

How can I best put a drop down list or select tag inside a html table - And then update a row if changed to mysql? complicated

I have a database containing a name and a status column. It contains data displayed in a table (obvious!). So, I want users to be able to select the status column's data and change it to any value listed in the drop down list. After the selection, they need to click a button that will update the selected row to the mySQL database.
How can I achieve this with PHP scripting and HTML?
Here is my code for displaying the data in a table on the website: (Pay no attention to phpReportGenerator.php- its only drawing the columns as per sql table)
<?php
include_once('includes/phpReportGenerator.php');
$prg = new phpReportGenerator();
$prg->width = "100%";
$prg->cellpad = "10";
$prg->cellspace = "0.5";
$prg->border = "1";
$prg->header_color = "#307D7E";
$prg->header_textcolor="#FFFFFF";
$prg->body_alignment = "left";
$prg->body_color = "#C6DEFF";
$prg->body_textcolor = "#000000";
$prg->surrounded = '1';
//$prg->font_name = "Boishakhi";
mysql_connect("localhost","username","password");
mysql_select_db("my_database");
$res = mysql_query("select * from table");
$prg->mysql_resource = $res;
//$prg->title = "Test Table";
$prg->generateReport();
?>
OR
Can somebody show me a easier/more effective way to do this?
Here is the sample code that you can use to update your mysql database by sending request to the server to access process_mysql.php :
<select onchange="update_mysql();">
<option value="1">option 1 </option>
<option value="2">option 2 </option>
</select>
Jquery function with ajax post request:
<script>
update_mysql(){
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"process_mysql.php",
data:"id="+id,
success:function(data){
alert('Successfully updated mysql database');
}
});
}
</script>

Pre Populating a PHP Dynamic Select Option with Stored Session Variable

Im scratching my head once again and need your help.
What I have is a form that submits to a second page, with sessions enabled, i am storing the name value 2 fields on the form and setting their value names in the session so that if a user returns to a page their Username will already be populated in the text field. I have this working ok ..
The second page i am storing
$_SESSION['captured_by'] = $_POST['captured_by'];
$_SESSION['prid'] = $_POST['prid'];
HOWEVER..
Where i am stuck is getting a select option that is populated from a query to have the same functionality, so that when a user returns to the page, the selected option which has been saved in the session will keep that selection in the box rather than having to select it again.
Here is what i have as follows:
Form Page:
This does work and does return the captured_by text when i return to the page
<fieldset><legend>Lesson Added By *</legend>
<p class="multiple">(Required - Logon ID)</p>
<input name="captured_by" maxlength="12" id="searchfield" type="text" value="<?php
if(isset($_SESSION['captured_by'])){print stripslashes($_SESSION['captured_by']);}
else{print " ";} ?>">
</fieldset>
The problem code is this
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'">'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
I need to edit this last section so that it picks up the previously selected option value from the stored session value.
Hope someone can help?
Many Thanks.
Tazzy
Try this,
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'"'. ((isset($_SESSION['prid']) && !empty($_SESSION['prid']) && ($_SESSION['prid'] == $row['project_id'])) ? 'selected="selected"' : '') .'>'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
You could simply use ajax when someone change the selection.
$('select#searchfield').change(function(){
$.ajax({
type: 'GET',
url: 'changeSession.php', // This is the url that will be requested
data: {prid: $('select#searchfield').val()},
success: function(html){
// nothing really happens because you simply update your session
},
dataType: 'html'
});
});
Then in changeSession.php
if(isset($_GET['projectId']{
$_SESSION['captured_by'] = $_POST['prid'];
}
That should do the job. You then add a condition when the form is generated and you add selected='selected' if $_SESSION['prid'] is not empty.

Inserting SQL data into HTML textarea

I've been reading lots of questions at stackoverflow that have made my life easier, first time I ask something though.
Here is my problem. I need to be able to insert different values from my SQL database into a selected < textarea > field, depending on what option is selected in a < select > input on the same form.
The basic idea is that I want to edit news from the database, edit title and body. To do that, I want to show what (title / body) data contains my db to the user, by getting them from my SQL db. User may have multiple entries in the database, so when I select one entry at the < select > combobox, I'd like to change the contents to those from the selected entry from the db.
Its a simple idea difficult to express due to my poor English...
HTML form would be more or less as follows:
<form action="edit.php" method="post">
<select name="id">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<textarea name="newsBody"></textarea>
<input name="submit" type="submit" value="Edit" />
</form>
SQL database structure goes more or less as follows:
DB name: database
DB table: news (fields id, body, title, author, timestamp)
I'd like to be able to select news from my < select > getting their 'id' / 'option value', then get from the DB the corrrect value, and show it in the corresponding < textarea >.
I'm new into website coding, and do it just as a hobby, so my knowledge in PHP, MySQL is very basic. I dont provide any PHP code or options, simply because I have no idea how to resolve it... I can understand sql, php syntax though.
I thought using < select > event 'onchange' and javascript, but couldn't make it work... Neither could I using jQuery / ajax, probably because the lack of useful examples!!
Hope that someone understands and can provide a solution!
Many thanks in advance!
You can use Ajax.
Create the following .html page:
<html>
<head>
<script>
function showData(str)
{
if (str=="")
{
document.getElementById("ajax-content").innerHTML="";
return;
}
// Code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// Code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax-content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showData.php?id="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="news" onchange="showData(this.value)">
<option value="">Select ID:</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
<div id="ajax-content"></div>
</body>
</html>
And the following .php script (showData.php in my example):
<?php
// Receive variable from URI
$id=$_GET["id"];
// Connect to your database
$con = mysql_connect('localhost', 'user1591005', 'stackOverflow');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db("myDatabase", $con);
// Select all fields from your table
$sql="SELECT * FROM news WHERE id = '".$id."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<input type='text' value='" . $row['title'] . "'>";
echo "<textarea>" . $row['content'] . "</textarea>";
}
// Close the connection
mysql_close($con);
?>
Alright Ill give you a quick idea before my lunch... :)
Setup an AJAX request to pass the selected dropdown box value to a PHP script.
In this PHP script, fetch the data for the selected value from your database.
Return the data and set the textbox's value to that.
Sending an AJAX Request
It seems that you need to use AJAX and Mysql+PHP for this. The first thing is to collect data from the table.
for example $result = mysql_query('SELECT * FROM new_table WHERE author = author's id')
The second thing is to output the html code with the results from the table you could use
you can do this by using foreach() loop. Then you need to use ajax (from the jQuery framework) and to pull data from the database again on user selection.
Hope this helps
To get the data from the database, you'll have to use a server-side language, such as PHP. To react to the change in the <select> element, you'll have to use JavaScript. AJAX is what will bridge the gap between the two languages.
Firstly write some JavaScript to make the query. If you're using jQuery, this is very straightforward.
<script>
var selector = $("#mySelectorID"); // first select the <select> elm
selector.change(function(e) { // attach a function to it's change event
jQuery.get("getContents.php", // when it changes, make an AJAX call
{id:selector.val()}, // passing the value of the <select> as data
function(returnVal) { // after a successful AJAX ...
$("#myTextAreaID").val(returnVal); // ... set the textarea to the correct value
});
});
</script>
Then create a new php file (slightly simplified, but this would work):
<?php
$id = $_GET['id']; // get the id that was passed through the URL
$connection = mysql_connect("hostname","username","password"); // connect to db
mysql_select_db("database", $connection ); // select the db
$result = mysql_query("SELECT * FROM news WHERE ID = $id"); // make SQL query
if ($row = mysql_fetch_array($result)) { // fetch the first row
echo $row['body']; // output the contents of the row
}
connection mysql_close($connection ); // close the connection
?>
More info on AJAX with jQuery: http://api.jquery.com/jQuery.get/
I am imagining you want to work on a simple html/PHP solution before branching out to Ajax ...
<?php
$title = "" ; // set the variables
$body = "" ;
$action = "" ;
$submit = "Edit";
if(isset($_POST['id']) && (int) $_POST['id'] > 0 ){
// a positive integer was sent to your form
// so now construct your sql statement: ie
// "select title, body from new where id= " . $_POST['id'] ;
// assign your rows to your variables
// $title = $row['title'] ;
// $body = $row['body'] ;
// now re-use your empty form to display the variables
// re-assign the form variables
// $action = "save.php" ;
// $submit = "Save changes";
}
?>
// have the form submit to itself by default
<form action="<?php echo $action; ?>" method="post">
<select name="id">
<option value="1" <?php if($_POST['id'] == 1 ) echo "selected=selected; ?>>Option 1</option>
<option value="2" <?php if($_POST['id'] == 1 ) echo "selected=selected; ?>>Option 2</option>
</select>
// have your html form values the same name as your db table columns
<input type="text" name="title" value="<?php echo $title; ?>"/>
<textarea name="body"><?php echo $body; ?></textarea>
<input name="submit" type="submit" value="<?php echo $submit; ?>" />
</form>
save.php then stores the new values in your database and perhaps redirects back to this page...
I am really paring this down, you'd likely generate your ids from a select from the database, and they'd probably be id, title in alphabetical order:
A big story
Big story
etc
There is lots else to take into consideration, but this is one way to go about it.
If you are using php with SQL to retrieve data from a database you can insert the database field using the following code.
echo '<textarea name="MyText" id="MyText" rows="8" cols="80" >' . $MySelectedText . '</textarea></p>';
Where MySelectedText is the data base field name of your SQL text you have selected from the database.

Using Jquery, mysql, and php I need the results of one dropdown select to alter the choices in a second dropdown

I have 2 dropdown select boxes in my form. The first one allows the user to choose a car make "vmake". Once a vmake is chosen a "vmodel" select box appears from thin air and then the user can choose the vmodel. However, I want the vmodel box to be there on page load, so it doesnt just appear out of thin air. It would be empty if the user tries to open it until they select a vmake. Heres my html
<select name="vmake" id="vmake">
<option value"" selected="selected">Make</option>
<?php getTierOne()l ?>
</select>
<select name="vmodel" id="vmodel">
<option value"" selected="selected">Model</option>
</select>
<span id="wait_1"></span>
<span id="result_1"></span>
Heres the jquery:
$(document).ready(function(){
$('#wait_1').show();
$('#vmake').change(function(){
$('#wait_1').show();
$('#result_1').hide();
$.get("func.php", {
func" "vmake",
drop_varL $('#vmake').val()
}, function(response){
$('#result_1').fadeOut();
setTimeout(finishAjax('result_1', '"+escape(response)+"')", 400);
});
return false;
]);
});
lastly the php which connects to my database
function getTierOne()
{
$result = mysql_query("SELECT DISTINT vmake FROM vmake")
or die(mysql_error());
while($tier = mysql_fetch_array( $result ))
{ echo '<option value="'.tier['vmake'].'">'.$tier['vmake'].'</option>';
}}
if($_GET['func'] == "vmake" && isset ($_GET['func'])) {
vmake($_GET['drop_var']);}
function vmake($drop_var)
{ include_once('db.php');
$result = mysql_query("SELECT * FROM vmake WHERE vmake='$drop_var'")
or die(mysql_error());
echo '<option value=" " selected="selected">Model</option>';
while($drop_2 = mysql_fetch_array( $result))
{ echo '<option value="'.$drop_2['vmodel'].'">'.$drop_2['vmodel'].'</option>';
}}
I got some help with the original code form an open source website and now I just need to change it a little to make it do what I want. As it stands it will create a new vmodel select box next to the existing one, but I just want it to populate the select box that appears on page load. Any help is very much appreciated. Thanks for everything.
Did you try using jQuery .load?
Example:
$('#vmodel').load('func.php',{vmake:$('#vmake').val()});
Would need to change the PHP as well, so you make a normal array of values and then send it through json_encode().

Categories