I want to call php function in dropdown menu by onchange event. I want with choose one of the options, the appropriate valuse are read from database and are list in another dropdown menu.
code:
<?php
function read() {
mysql_connect("localhost", "username", "password");
mysql_select_db("database_name");
$sql = mysql_query("SELECT name FROM table");
if (mysql_num_rows($sql)) {
$select = '<select name="select">';
while ($rs = mysql_fetch_array($sql)) {
$select.='<option value="' . '">' . $rs['name'] . '</option>';
}
}
$select.='</select>';
echo $select;
}
?>
<!--html code -->
<select onchange="document.write('<?php read(); ?>');">
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
</select>
This code output:
My desired output:
How can I get My desired output ? Thanks
Just to explain:
PHP code is executed before the page is rendered in your user's browser (Server side).
In the other hand, Javascript is executed in the Client-side. It means that php finnished execution already.
If you wanna call a php function, you will have to make another request to the Server.
To do that "on the fly", you will have to use AJAX, as meantioned by #Jon in the comments.
Here is an example using jQuery (Just a javascript library, to simplify our task):
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javasript">
//Listen to select 'onchange' event
$('select#your_select_id').change(function(){
//Read selected value
var inputValue = $(this).val();
//Make an ajax call
$.post('ajaxscript.php', { value: inputValue }, function(data){
//The return of 'read' function will be accessible trough 'data'
//You may create DOM elements here
alert('Finnished');
});
});
</script>
and here is our ajaxscript.php content:
<?php
//Declare (or include) our function here
//function read(){ ... }
$value = $_POST['value']; //Selected option
//...
echo read();
Hi You can also use javascript form submit in this and call a php function
<?php
function read() {
mysql_connect("localhost", "username", "password");
mysql_select_db("database_name");
$sql = mysql_query("SELECT name FROM table");
if (mysql_num_rows($sql)) {
$select = '<select name="select">';
while ($rs = mysql_fetch_array($sql)) {
$select.='<option value="' . '">' . $rs['name'] . '</option>';
}
}
$select.='</select>';
echo $select;
}
if (isset($_POST['value'])) {
read($_POST['value']);
}
?>
<form method="POST">
<select name="value" onchange="this.form.submit()">
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
</select>
</form>
Related
I'm trying to make a combobox that when another combobox is changed it will dynamically update with information from a database. I'm finding a lot of solutions that do not seem to work with what I have and am lost on what to do next.
I've tried simplifying the code to figure out what part does not work, there are so many different versions of the code I tried I just know that some of the one I have right now works and some of it does not.
EDIT: better code (I hope)
Database connexion (root/config/config.php)
<?php
define("DB_HOST", "10.172.16.4");
define("DB_USER", "test2_user");
define("DB_PASS", "password");
define("DB_NAME", "test2");
$dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
$options = [PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
} catch (PDOException $error) {
echo "Connection error: " . $error->getMessage();
die();
}
?>
Header (root/online/templates/header.php)
<!DOCTYPE HTML>
<HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="js/javascript.js"></script>
</head>
<body>
The form (root/online/create.php)
<?php
require_once "templates/header.php";
require_once "../config/config.php";
?>
<form method="post" action="">
<label for="choose_type">Type</label>
<select name="choose_type_modele" id="choose_type" onchange="selectMarque()" required>
<option value="">Select Type</option>
<?php
$sql = "SELECT id, name FROM typeMateriel";
if($stmt = $pdo->prepare($sql)) {
if($stmt->execute()){
$typeMateriel = $stmt->fetchAll();
}
}
foreach($typeMateriel as $foundType){
$typeMateriel_id = $foundType['id'];
$typeMateriel_name = $foundType['name'];
?>
<option value="<?= $typeMateriel_id; ?>"><?= $typeMateriel_name; ?></option>
<?php } ?>
</select>
<label for="choose_marque">Marque</label>
<select name="choose_marque_modele" id="choose_marque" required>
<option value="">Select type first</option>
</select>
</form>
<p id="test"></p>
<?php require_once "templates/footer.php"; ?>
The function (root/online/js/javascript.php)
function selectMarque() {
var typeID = $('#choose_type').val();
var post_id = 'id='+ typeID;
document.getElementById("test").innerHTML = "You Selected " + typeID;
if(typeID){
$.ajax({
type:'POST',
url:'../ajax_marque.php',
data:post_id,
success:function(marque){
$('#choose_marque').html(marque);
}
});
}else{
document.getElementById("choose_marque").innerHTML = '<option value="">Select type first</option>';
}
};
the code for the dynamic stuff (root/online/ajax_marque.php)
<?php
include('../config/config.php');
if($_POST['id']){
$id=$_POST['id'];
if($id===0){
echo "<option>N/A</option>";
} else {
$sql = "SELECT marqueMateriel.id,marqueMateriel.name FROM type_marque, marqueMateriel WHERE marqueMateriel.id=type_marque.marqueMateriel_id AND type_marque.typeMateriel_id= :typeMateriel_id";
if($stmt = $pdo->prepare($sql)) {
$stmt->bindParam(':typeMateriel_id', $id, PDO::PARAM_INT);
if($stmt->execute()){
$marqueMateriel = $stmt->fetchAll();
}
}
echo "<option>Select Marque</option>";
foreach($marqueMateriel as $foundMarque) {
$marqueMateriel_id = $foundMarque['id'];
$marqueMateriel_name = $foundMarque['name'];
echo "<option value='<?php $marqueMateriel_id; ?>'><?php $marqueMateriel_name; ?></option>";
}
}
}
?>
Closing up (root/online/template/Footer.php)
</body>
</html>
The first combo box works, and that's pretty much it. Nothing changes and I'm sure I'm missing something somewhere. I can use the function to alert(typeID) and it does so , but not change the data :/
EDIT : Trying to make more sense ?
The combo box "choose_type_modele" works, it contains everything from the table "typeMateriel". When I select something it does not change the second box "choose_marque_modele". The onchange function is called, as the "test" is modified on selection with the appropriate ID. The code in "ajax_marque.php" works if I copy it inside "create.php" and manually tell it what "$id" is, but it won't do it automatically. I feel the problem is the $.ajax part of the code inside "javascript.js" but I cannot seem to figure out what part is wrong.
Any help would be greatly appreciated.
I don't think if you can add options to a select with html method. You have to create option objects to add select object. To archieve this, you'll change response of your ajax method to JSON object.
var selectMarque = function() {
// Remove current options from matque
$('#choose_marque').find("option").remove();
var typeID = $('#choose_type').val();
var post_id = 'id=' + typeID;
// There will be always value in post_id
// You have to check typeID to be sure if type picked
if (typeID) {
// sample ajax data
var testData = [{
"value": "1",
"text": "Option 1"
},
{
"value": "2",
"text": "Option 2"
},
];
// for each option data in testData
$.each(testData, function(offset, optionData) {
// append an option to select
$('#choose_marque').append($('<option>', {
value: optionData.value,
text: optionData.text
}));
});
} else {
// if empty value picked as type
// add sample option to marque
$('#choose_marque').append($('<option>', {
value: "",
text: "Select Type To Fill"
}));
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="choose_type_modele" id="choose_type" onchange="selectMarque()" required>
<option value="">Select Type</option>
<option value="1">Fill Select</option>
</select>
<select id="choose_marque" required>
<option value="">Select Type To Fill</option>
</select>
I had two errors in my code that made it impossible to work, the url and success parts of the ajax code.
Working code :
$.ajax({
type:'POST',
url:'ajax_marque.php',
data:post_id,
success:function(data){
$('#choose_marque').html(data);
}
});
For some reason I had "marque" instead of data (I might have changed it thinking it was something else ? ) and the url was "../ajax_marque.php". I thought I had to add the url from wherever the javascript.php file was, not from where it was called (create.php).
I have a PHP form with the following select list;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
I also have a text field ;
Telephone Number: </b> <?php echo $_SESSION["TeleNo"]; ?></p>
The PHP function called by the onchange command is ;
function findTeleNo($MatchCaptain){
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$_SESSION["TeleNo"] = $db_field['TeleNo'];
include "Match_sort.php";
break;
}
}
}
}
What I am trying to do is when the Match Captains name is changed in the SELECT dropdown list then I want the FUNCTION findTeleNo() to run. Which should then reload the form with the telephone number of the New Match Captain.
However, when I select a new Match Captain the onchange command is ignored.
As a Septuagenarian, just learning this language, I need some help!
Does onchange work in PHP? If not what should I use?
The onchange event is a javascript event, it cannot call your php function directly. You can create a javascript function that will be called when the selects value changes and then this can make an xhr(Ajax) request to a php file which will perform a database query and return what you need it to. You could then update the page with javascript.
PHP is a server side language, you need to use javascript for this.
this is example:
function findTeleNo (value) {
console.log(value);
$.ajax({
url: 'findTeleNo.php',
data: {
c_name: value
},
success: function (response) {
$('#cname').text(response.cname);
$('#teleno').text(response.teleno);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)">
<option>choose one</option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="C3">C3</option>
</select>
<div>
<div>
Captain Name is: <span id="cname">empty</span>
<div>
<div>
TeleNo is: <span id="teleno">empty</span>
<div>
and in file findTeleNo.php you print json has cname and teleno.
I have 4 dynamic dependent select boxes, now I want to combine the result of the 4 selects into a query. I have all the relative code below.
font-end part of the select boxes
<form class="select-boxes" action="<?php echo site_url("/part-search-result/"); ?>" method="POST" target="_blank">
<?php include(__DIR__.'/inc/part-search.php'); ?>
</form>
part-search.php
<?php
include( __DIR__.'/db-config.php' );
$query = $db->query("SELECT * FROM ps_manufact WHERE status = 1 ORDER BY manufact_name ASC");
$rowCount = $query->num_rows;
?>
<select name="manufacturer" id="manufact" onchange="manufactText(this)">
<option value="">Select Manufacturer</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['manufact_id'].'">'.$row['manufact_name'].'</option>';
}
}else{
echo '<option value="">Manufacturer Not Available</option>';
}
?>
</select>
<input id="manufacturer_text" type="hidden" name="manufacturer_text" value=""/>
<script type="text/javascript">
function manufactText(ddl) {
document.getElementById('manufacturer_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="type" id="type" onchange="typeText(this)">
<option value="">Select Manufacturer First</option>
</select>
<input id="type_text" type="hidden" name="type_text" value=""/>
<script type="text/javascript">
function typeText(ddl) {
document.getElementById('type_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="year" id="year" onchange="yearText(this)">
<option value="">Select Type First</option>
</select>
<input id="year_text" type="hidden" name="year_text" value=""/>
<script type="text/javascript">
function yearText(ddl) {
document.getElementById('year_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="model" id="model" onchange="modelText(this)">
<option value="">Select Year First</option>
</select>
<input id="model_text" type="hidden" name="model_text" value=""/>
<script type="text/javascript">
function modelText(ddl) {
document.getElementById('model_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<input type="submit" name="search" id="search" value="Search">
<script type="text/javascript">
jQuery(function($) {
$('#manufact').on('change',function(){
var manufactID = $(this).val();
if(manufactID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'manufact_id='+manufactID,
success:function(html){
$('#type').html(html);
$('#year').html('<option value="">Select Type First</option>');
}
});
}else{
$('#type').html('<option value="">Select Manufact First</option>');
$('#year').html('<option value="">Select Type First</option>');
}
});
$('#type').on('change',function(){
var typeID = $(this).val();
if(typeID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'type_id='+typeID,
success:function(html){
$('#year').html(html);
$('#model').html('<option value="">Select Year First</option>');
}
});
}else{
$('#year').html('<option value="">Select Type First</option>');
$('#model').html('<option value="">Select Year First</option>');
}
});
$('#year').on('change',function(){
var yearID = $(this).val();
if(yearID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'year_id='+yearID,
success:function(html){
$('#model').html(html);
}
});
}else{
$('#model').html('<option value="">Select Year First</option>');
}
});
});
</script>
ajax-data.php
<?php
include( __DIR__.'/db-config.php' );
if(isset($_POST["manufact_id"]) && !empty($_POST["manufact_id"])){
$query = $db->query("SELECT * FROM ps_type WHERE manufact_id = ".$_POST['manufact_id']." AND status = 1 ORDER BY type_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Type</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['type_id'].'">'.$row['type_name'].'</option>';
}
}else{
echo '<option value="">Type Not Available</option>';
}
}
if(isset($_POST["type_id"]) && !empty($_POST["type_id"])){
$query = $db->query("SELECT * FROM ps_year WHERE type_id = ".$_POST['type_id']." AND status = 1 ORDER BY year_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Year</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['year_id'].'">'.$row['year_name'].'</option>';
}
}else{
echo '<option value="">Year Not Available</option>';
}
}
if(isset($_POST["year_id"]) && !empty($_POST["year_id"])){
$query = $db->query("SELECT * FROM ps_model WHERE year_id = ".$_POST['year_id']." AND status = 1 ORDER BY model_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Model</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['model_id'].'">'.$row['model_name'].'</option>';
}
}else{
echo '<option value="">Model Not Available</option>';
}
}
?>
part-search-result.php
<?php
if (isset($_POST['search'])) {
$clauses = array();
if (isset($_POST['manufacturer_text']) && !empty($_POST['manufacturer_text'])) {
$clauses[] = "`manufacturer` = '{$_POST['manufacturer_text']}'";
}
if (isset($_POST['type_text']) && !empty($_POST['type_text'])) {
$clauses[] = "`type` = '{$_POST['type_text']}'";
}
if (isset($_POST['year_text']) && !empty($_POST['year_text'])) {
$clauses[] = "`year` = '{$_POST['year_text']}'";
}
if (isset($_POST['model_text']) && !empty($_POST['model_text'])) {
$clauses[] = "`model` = '{$_POST['model_text']}'";
}
$where = !empty( $clauses ) ? ' where '.implode(' and ',$clauses ) : '';
$sql = "SELECT * FROM `wp_products` ". $where;
$result = filterTable($sql);
} else {
$sql = "SELECT * FROM `wp_products` WHERE `manufacturer`=''";
$result = filterTable($sql);
}
function filterTable($sql) {
$con = mysqli_connect("localhost", "root", "root", "i2235990_wp2");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$filter_Result = mysqli_query($con, $sql);
return $filter_Result;
}
?>
<?php get_header(); ?>
<div class="container">
<div id="products" class="row list-group">
<?php while ( $rows = mysqli_fetch_array($result) ): ?>
<div class="item col-xs-12 col-sm-4 col-md-4 col-lg-4">
<div class="thumbnail">
<?php
echo '<img name="product-image" class="group list-group-image hvr-bob" src=' . $rows['image_url'] . ' width="400px" height="250px" alt="" />';
?>
<div class="caption">
<h4 class="group inner list-group-item-heading">
<?php
echo "Manufacturer:\t".$rows['manufacturer'].'<br>';
echo "Type:\t".$rows['type'].'<br>';
echo "Year:\t".$rows['year'].'<br>';
echo "Model:\t".$rows['model'].'<br>';
echo '<br>';
echo "Description:\t".$rows['description'].'<br>';
?>
</h4>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
<?php get_footer(); ?>
Now my problem is:
If only select the first one box, or select the first two boxes, and click the Search button, it successfully jumps to the result page. However, if continuously select the third box, the result page is gone and Chrome Console returns the error:
Failed to load resource: the server responded with a status of 404 (Not Found)
Let me ask you a question. You've tagged this as a WordPress website. Correct? Then why aren't you using the built-in database handler, $wpdb to both prepare and communicate with the database? It's the safest and fastest way for you to work with the database.
Revised Code
Here I've revised your code to do the following:
Use $wpdb->prepare to sanitize the $_POST values to protect the database from nefarious folks
Remove redundancies by looping through a list of column names and using the field naming pattern you specified by suffixing _text to the column name
Using $wpdb->get_results() to go fetch the results.
Here is the revised code:
/**
* Build the search's WHERE SQL from the form's $_POST fields.
*
* #since 1.0.0
*
* #return string
*/
function build_search_where_sql() {
global $wpdb;
$column_names = array(
'manufacturer',
'type',
'year',
'model',
);
$where_clauses = [];
foreach( $column_names as $column_name ) {
$post_key = $column_name . '_text';
if ( isset( $_POST[ $post_key ] ) && $_POST[ $post_key ] ) {
$where_clauses[] = $wpdb->prepare( "{$column_name} = %s", $_POST[ $post_key ] );
}
}
if ( empty( $where_clauses ) ) {
return '';
}
$where_sql = " WHERE " . join( ' AND ', $where_clauses );
return $where_sql;
}
/**
* Get the search results from the database. If the records
* do not exist or an error occurs, false is returned. Else,
* an array with stdClass objects for each record is returned.
*
* #since 1.0.0
*
* #return bool|array
*/
function get_search_database_results() {
$where_sql = isset( $_POST['search'] )
? build_search_where_sql()
: "WHERE manufacturer = ''";
if ( ! $where_sql ) {
return false;
}
global $wpdb;
$sql_query = "SELECT * FROM wp_products {$where_sql};";
$records = $wpdb->get_results( $sql_query );
if ( ! $records ) {
return false;
}
return $records;
}
UPDATE: Strategy for You
Now that I've seen the HTML code you are proposing as well as knowing you are learning about building websites, let's talk about a different architectural strategy for your project.
Don't use a custom database table.
Use a custom post type called products instead.
Use post metadata to set the attributes for each product, i.e. the manufacturer, model, year, type, etc.
Use a form plugin, such as Ninja Forms.
You can build the meta boxes yourself for the metadata, if you have the technical chops to do it. Else, you can use a third-party plugin such as CMB2 or ACF.
Custom Post Type
WordPress provides you the ability to add custom content. They provide built-in post types. We developers can add custom ones that are specific content context. Products is a good candidate for a custom post type.
You can generate the code on GenerateWP. It's literally a few lines of code to create it.
Where can you learn about Custom Post Types?
Well, there are plenty of tutorials. Codex gives you the documentation and examples. I teach it at Know the Code. Tuts+ has lots of tutorials. And many others....
Why Custom Post Type Instead of Custom Db Table?
Yes, you can build a custom database table. But it requires you to add the schema, seed the table, write the interface for admins to interact with the content, and then write and secure the interaction. To populate the options in the select, you'd have to query the database using $wpdb and then write a model to translate it into a view. Then you'd have to write the form processing to interact and save.
In other words, it's going to cost you time and money. Why? Because it's more code and not native to WordPress. You have to write, secure, test, and maintain it yourself.
If You Want to Stick With Your Current Strategy
If you prefer to stick with the custom database table strategy, then here are some suggestions to help you out:
You don't need the hidden input for each of the select elements. Why? When the form is posted, the option set for each select will post back to the server.
I'd change the select names to be an array, like this: name="part-select[manufacturer]" and then repeat for type, model, year, etc. Then you can grab the $_POST['part-select'] to get all of the values.
You are going to want to add nonce to protect the content. Make sure to pass it with the data packet when doing AJAX too.
Using AJAX, you can request the records from the database. You'll need to modify the code I gave to you in order to build the SQL query. Then loop through the results to build the HTML you want to send back to the front-end.
I like building the HTML markup on the server side and then sending that back to the front-end when doing AJAX.
Cheers.
I have a cascade menu using PHP, jQuery and mysql. It works like a charm, but if I try to import it in Joomla as an article (with a Joomla extension wich activates PHP code in articles) it won't work correctly. The problem is, I don't even know where to find the source of the problem... I can select the category, but whenever I do, the second level of the cascade dropdown menu (category -> type -> model is the order) won't load, actually it says 'Please wait...', and after a few seconds the select option will be blank. I tested it on localhost, only the cascade menu not in Joomla framework and it worked...
I've got some files:
script.php -> handles the jQuery effects, also the dropdowns:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#type").attr("disabled","disabled");
$("select#model").attr("disabled","disabled");
$("select#category").change(function(){
$("select#type").attr("disabled","disabled");
$("select#type").html("<option>Please wait...</option>");
var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {id:id}, function(data){
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
$("select#type").change(function(){
$("select#model").attr("disabled","disabled");
$("select#model").html("<option>Please wait...</option>");
var id2 = $("select#type option:selected").attr('value');
$.post("select_model.php", {id2:id2}, function(data){
$("select#model").removeAttr("disabled");
$("select#model").html(data);
});
});
$("select#model").change(function(){
var cat = $("select#category option:selected").attr('value');
var type = $("select#type option:selected").attr('value');
var model = $("select#model option:selected").attr('value');
if(cat>0 && type>0 && model >0)
{
var model = $("select#model option:selected").html();
var type = $("select#type option:selected").html();
$("#result").html('<br>Your choice: ' + type + ' ' + model + '.');
}
else
{
$("#result").html("<br>One of the inputs is empty!");
}
return false;
});
});
</script>
<form id="select_form">
Choose category: <select id="category">
<?php echo $opt->ShowCategory(); ?>
</select><br />
Choose type: <select id="type">
<option value="0">Please select...</option>
</select>
<br />
Choose model: <select id="model">
<option value="0">Please select...</option>
</select></form>
<div id="result"></div>
<br><br>
select_type.php -> after user selects category, this should show the types in that category in the second menu.
<?php
include "class.php";
echo $opt->ShowType();
?>
select_model.php -> same as select type, but it's under the type selection, so this is the last level of the cascade menu.
<?php
include "class.php";
echo $opt->ShowModel();
?>
And finally, the class.php, which connects to the database where I fetch the datas from to load them in the select menus.
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
$host = "localhost";
$user = "root";
$password = "usbw";
$db = "test";
$this->conn = mysql_connect($host,$user,$password) OR die("error!");
mysql_select_db($db,$this->conn) OR die("error!");
return TRUE;
}
public function ShowCategory()
{
$sql = "SELECT * FROM categories";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">Please select a category...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['id_cat'] . '">' . $row['name'] . '</option>';
}
return $category;
}
public function ShowType()
{
$sql = mysql_query( "SELECT * FROM type WHERE id_cat=$_POST[id]");
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">Please select a type...</option>';
while($row = mysql_fetch_array($sql))
{
$type .= '<option value="' . $row['id_type'] . '">' . $row['name'] . '</option>';
}
return $type;
}
public function ShowModel()
{
$sql = "SELECT * FROM model WHERE id_model=$_POST[id2]";
$res = mysql_query($sql,$this->conn);
$model = '<option value="0">Please select a model...</option>';
while($row = mysql_fetch_array($res))
{
$model .= '<option value="' . $row['id_model'] . '">' . $row['name'] . '</option>';
}
return $model;
}
}
$opt = new SelectList();
?>
A few points to go through:
don't use mysql_connect is this method of connecting to a database is deprecated, nor is it secure.
There is no need to manually connect to a database. You can use the JFactory::getDBO(); method. More information on that can be found here
I'm not sure how you're adding this custom code to your article, but I hope you realise that you should be usign a plugin such as Sourcerer
Rather than adding all this code into your article, I think it might be better off making a creating a custom module. By that I actually mean developing one and using you're code. It won't take too long. then you can embed the module into you article.
Rather than importing jQuery using the tags, please refer to my answer on the best method of importing it using Joomla coding standards here
If you haven't already looked at the Joomla Extensions Directory, I suggest you do so, as there are lots of menu modules that your could install and edit to your own liking.
Hope this helps
Inside my page I have an input ("Model") with a datalist attribute and a select menu ("Brand"). When a user select one of the options of the datalist from the Model, it will dynamically change the options value from the Brand select menu. Both options value from Model and Brand are called from the database. This is what I code so far;
<input type="text" name="type" id="type" list="datalist1" onchange="fw();"/>
<datalist id="datalist1">
<?php
$query9 = "SELECT DISTINCT model FROM server ORDER BY model ASC";
$result9 = mysql_query($query9);
while($row9 = mysql_fetch_assoc($result9))
{
echo '<option value="'.$row9['model'].'">';
} ?>
</datalist>
<select name="brand" id="test2"><option value="">-- Select Brand--</option></select>
Script;
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function fw()
{
var selname = $("#type").val();
$.ajax({ url: "getBrand.php",
data: {"brand":brand},
type: 'post',
success: function(output) {
document.getElementById('test2').options.length = 0;
document.getElementById('test2').options[0]=new Option(output,output);
// document.getElementById('test2').options[1]=new Option(output,output);
}
});
}
</script>
getBrand.php
<?php
define('DB_HOST1', 'localhost');
define('DB_NAME1', 'standby');
define('DB_USER1', 'root');
define('DB_PASS1', '');
$link = mysql_connect(DB_HOST1, DB_USER1, DB_PASS1);
if(!$link)
{
exit('Cannot connect to server "' . DB_HOST1 . '"');
}
mysql_select_db(DB_NAME1, $link) or die('Cannot use database "' . DB_NAME1 . '"');
if (isset($_POST['brand'])) {
$selname = $_POST['brand'];
$query = "SELECT * FROM server WHERE model='$brand'";
$res = mysql_query($query);
$aBrand= array();
while($rows = mysql_fetch_assoc($res)) {
$brand= $rows['brand'];
$aBrand[] = $brand;
echo $aBrand[0];
echo $aBrand[1];
}
} ?>
From what I have coded, I have succesfully change the select menu dynamically but there is one problem. When there is more one data is called from getBrand.php, the 'output' in the select menu will combine all of the data into one line. For example, if the data is "M3000" and "M4000", it will display as "M3000M4000". Now, how do I split it and make it as a normal select options?
I'm still learning Javascript and I hope anyone here can guide me.
NOTE : The code only works in Firefox because of the datalist attribute
Send your data from getBrand.php as
echo implode(";", $aBrand);
this will generate a string like M3000;M4000;M5000;M6000
and in your java script code break the string into array using this code.
StrArr = Str.split (";");
here 'Str' is your output given by getBrand.php, and 'StrArr' is the array which contains your brands.
add a special character in the string returned form php
PHP
elementcount=0;
while($row9 = mysql_fetch_assoc($result9))
{
if(elementcount>0)
echo '$<option value="'.$row9['model'].'">';//place a $ sign in start or you can for any special character
else
echo '<option value="'.$row9['model'].'">';
}
now in javascript
success: function(output) {
output = output.split("$");
document.getElementById('test2').options.length = 0;
//here now loop through the elements and add
for(var i=0,i<output.length-1)
document.getElementById('test2').options[0]=new Option(output[i],output[i]);
// document.getElementById('test2').options[1]=new Option(output,output);
}