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);
}
Related
I have a table with this structure and trying to use a dropdown to select a language from the list and then display the contents of respective language_id .. I am using mysql and php 5.4
My code is as follows, got stuck with looping and not sure how to get it
$sql=mysql_query("SELECT lang_id, lang_desc FROM languages ");
if(mysql_num_rows($sql))
{
$select= '<select lang_desc="select">';
while($rows=mysql_fetch_array($sql))
{
$select.='<option value="'.$rows['lang_id'].'">'.$rows['lang_desc'].'</option>';
}
}
$select.='</select>';
echo $select ;
$result = mysql_query("SELECT * FROM contents LEFT JOIN languages ON contents.lang_id = languages.lang_id WHERE contents.page_name = 'index' AND contents.lang_id = '$select'");
while ($row = mysql_fetch_array($result))
{
}
Please help
I think this want minimum 2 PHP pages 1st for show data and 2nd for creat data in hear I didn't create DB connection please add it
in 1st I use jquery for getting data from 2nd PHP
show.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<select id="lang" onchange="setlang(this.value)">
<?PHP
$sql=mysql_query("SELECT lang_id, lang_desc FROM languages");
while($rows=mysql_fetch_array($sqL,MYSQL_ASSOC)){
echo '<option value="'.$rows['lang_id'].'">'.$rows['lang_desc'].'</option>'
}
?>
</select>
<div id='dis'></div>
<script type="text/javascript">
$( document ).ready(function() {
setlang($('#lang').val());
});
function setlang(val) {
$.ajax({
url: "data.php",
type: "POST",
data:{val:val},
success: function(result){
$("#dis").html(result);
}
});
}
</script>
data.php
<?php
$result = mysql_query("SELECT * FROM contents LEFT JOIN languages ON contents.lang_id = languages.lang_id WHERE contents.page_name = 'index' AND contents.lang_id = '".$_POST['val']."'");
$data="";
while ($row = mysql_fetch_array($result))
$data.="your row data for dis";
//
}
echo $data;
?>
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 wanted to show/hide element based on MySql Value
$(document).bind('DOMNodeInserted', '#composeHeaderTable0', function(event) {
if ($('#data_parent_type0').val() == 'Leads') {
$("#email_template0 option[value='151ddf5a-3fe8-84bd-50db-533545893c67']").hide();
$("#email_template0 option[value='15a6040b-bbad-1a89-d62b-537de2b73832']").show();
}
if ($('#data_parent_type0').val() == 'Contacts') {
$("#email_template0 option[value='1b560788-07b2-0798-6b09-5335520bd9df']").hide();
$("#email_template0 option[value='f15bf4b4-d174-f0d6-6f09-537c8d3e9693']").show();
}
return false;
});
Above script works, but I need to show hide based on Mysql call:
I have partial php corresponding file
<?php
mysql_connect('mysql', 'admin', '123');
mysql_select_db('mydb');
$Leads0emailAddress0 = mysql_real_escape_string($_POST['Leads0emailAddress0']);
$result = mysql_query('select id from email_templates where description = 'Customers' and deleted = 0;');
...............
?>
Use a hidden form element, set its value to the result obtained from mysql. Assign a specific ID to that form element. From jQuery, refer that form element using the ID. That should do the trick.
Your mysql script has error
$result = mysql_query('select id from email_templates where description = 'Customers' and deleted = 0;');
change it to
$result = mysql_query(
"SELECT id FROM
email_templates
WHERE
description = 'Customers'
AND deleted = 0"
);
To list the result
$options = '';
while($row = mysql_fetch_assoc($result)) {
$options .= '<option value="'.$row['id'].'">'.$row['id'].'</option>' . "\n";
}
//display the options list in html where you want
<select id="email_template0">
<?php echo $options; ?>
</select>
now from jQuery handle event on dropdown change
$(function() {
$("#email_template0").change(function() {
alert( $('option:selected', this).val() );
//do your hide and select here
});
});
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script>
$(document).ready(function() {
var $article = null;
$('#category').change(function() {
var $categoryName = $('#category').val();
if ($article == null) {
$article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"><option value="0">Select A Business To View Listing</option></select>').appendTo('.query');
}
$("#business").load("php.php");
});
});
</script>
This is what I am currently doing, I am loading the php.php script, instead I want to pass the value of $categoryName to the WHERE clause in my query so it's like this:
<?php
$con = mysqli_connect(,,,,);
// Check connection
if (mysqli_connect_errno())
{
echo "<option>Failed to connect to MySQLi</option>" ;
}
$result = mysqli_query($con,"SELECT Bname, Category FROM Business WHERE Category='$categoryName'");
while($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['Bname']."'>".$row['Bname']."</option>";
}
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
The way this should work is, the first select box is populated by php on my server showing a list of categories. A user selects a category from that box and onchange, a second select box is created, added to the form, and will query, to populate all of the business name's listed in my database that share a category(i.e the selectedindex from the first box) Can you help me change this to work how I need it to?
UPDATE: This is the updated code, now the second select box never loads.
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script>
$(document).ready(function () {
var $article = null;
$('#category').change(function () {
var categoryName = $('#category').val();
if ($article == null) {
$article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"><option value="0">Select A Business To View Listing</option></select>').appendTo ('.query');
$("#business").load( "php.php",
data:{myVar:$categoryName}
);
}
});
});
</script>
Heres the php.php
<?php
$con = mysqli_connect(,,,,);
// Check connection
if (mysqli_connect_errno())
{
echo "<option>Failed to connect to MySQLi</option>" ;
}
$myVar = $_GET["myVar"];
$result = mysqli_query($con,"SELECT Bname, Category FROM Business WHERE Category='$myVar'");
while($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['Bname']."'>".$row['Bname']."</option>";
}
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
As seen below you can make a data object with one parameter myVar
JS:
$('#category').change(function() {
var $categoryName = $('#category').val();
if ($article == null) {
$article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"><option value="0">Select A Business To View Listing</option></select>').appendTo('.query');
}
$("#business").load("php.php",
data:{myVar:$categoryName}
);
});
Then get the variable in PHP like this
PHP:
$con = mysqli_connect(,,,,);
$myVar = $_GET["myVar"];
// Check connection
if (mysqli_connect_errno())
{
echo "<option>Failed to connect to MySQLi</option>" ;
}
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