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).
Related
I have a list of rooms in a table along with their rent cost. Rooms are listed in a drop down menu, and I want to get rent in "input" field value, "on page load" as well as on "dropdown value change". I wrote following code, but somehow it is not working as expected. Can someone help me with this please?
<?php
define("HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "testdb");
$conn = mysqli_connect(HOST, DB_USER, DB_PASS, DB_NAME);
if (!$conn) {
die(mysqli_error());
}
$ajax = false;
$dbValue = 1; //or the default value of your choice - matched to the default selection value of the dropdown
if (isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['dd'])) {
$dbValue = intval($_GET['dd']);
$ajax = true;
$res = mysqli_query($conn, "SELECT rent FROM `rooms` WHERE roomid = '$dbValue' limit 1");
$dataTable = '';
while ($data = mysqli_fetch_assoc($res)) {
$dataTable = $data['rent'];
}
}
// if ($ajax) return $dataTable;
?>
<html>
<head>
<title>jQuery Validation for select option</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<select class="form-control" id= "roomid" name="roomid" required="">
<?php
$troom_sql = "SELECT roomid FROM rooms WHERE (isactive='y' AND isassigned='n' AND roomid NOT IN (SELECT roomid from roomalloc))";
$troom_rs = mysqli_query($conn, $troom_sql);
while ($troom_mem = mysqli_fetch_assoc($troom_rs)) {
?>
<option value="<?php echo $troom_mem['roomid']; ?>"><?php echo $troom_mem['roomid']; ?></option>
<?php
} ?>
</select>
<input type="text" placeholder="Monthly Rent" class="form-control" id="rent" name="rent" required>
<br>
</body>
<script>
$('#roomid').change(function()
{
var first = $('#roomid').val();
var req = $.get('getDB.php', {dd: first, action: 'ajax'});
req.done(function(data)
{
console.log("asdasd");
$('#rent').val("<?php echo $dataTable; ?>");
});
});
</script>
</html>
Though you've written both PHP and JS in the same file, you still need to return the data from PHP side and handle it in JS.
if ($ajax) return json_encode($dataTable)
from PHP side
dat = JSON.parse(data)
in JS
Crate a JQuery AJAX Function that takes the parameter for POST/GET Request and call that Ajax function on JQuery Event. The Ajax Function Should be like,
function LoadComponentPage( param ){
$.ajax({
type: "POST",
url: "./controller/ajax/component_paginate.php",
data: "page="+param,
dataType: "text",
success: function(resultData){
let section = $('#ComponentsListing');
section.empty();
section.html(resultData);
},
error : function(e){
console.log(e);
}
});
}
and call that function upon event as onclick="LoadComponentPage(param)". you can post process the result of call to show result or error something as shown in example function.
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'm trying to update the database using a dropdown list without using a submit button.
Here's my dropdown:
<td>
<label for=""></label>
<select style="font-family: Questrial;" name="status" required>
<option disabled selected hidden>Select Status</option>
<option value="In Progress">In Progress</option>
<option value="Closed: Cancelled">Closed: Cancelled</option>
<option value="Closed: Solved">Closed: Solved</option>
</select>
</td>
Here's the script:
<script>
$(document).ready(function() {
$('option[name="status"]').click(function() {
var status = $(this).val();
$.ajax({
url: "update2.php",
method: "POST",
data: {
status: status
},
success: function(data) {
$('#result').html(data);
}
});
});
});
</script>
And here's update2.php:
<?php
//Insert Data
$hostname = "localhost";
$username = "root";
$password = "";
$databasename = "companydb";
try
{
$conn = new PDO("mysql:host=$hostname;dbname=$databasename",$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["status"]))
{
$query = "INSERT INTO tickets(status) VALUES (:status)";
$statement = $conn->prepare($query);
$statement->execute(
array('status' => $_POST["status"])
);
$count = $statement->rowCount();
if($count > 0)
{
echo "Data Inserted Successfully..!";
}
else
{
echo "Data Insertion Failed";
}
}
}
catch(PDOException $error)
{
echo $error->getMessage();
}
?>
Basically what I want to happen is to update the table values when I make a selection from the dropdown list.
Currently, nothing happens when I make a selection. (No page reload, No error message, just nothing)
Am I doing something wrong here?
Also here's my table schema:
table schema
You are targeting the wrong element
$('option[name="status"]') should be $('select[name="status"] option'
I suggest you to use id, they are more clear and faster.
In addition you will also be interested with the change event
https://api.jquery.com/change/
The selector should be select and the event should be change(). Try this :
$('select[name="status"]').change(function() {
instead of :
$('option[name="status"]').click(function() {
1) change $('option[name="status"]').click( to $('select[name="status"]').change(
the name "status" is an attribute of the select, not the options.
2) make sure you have an element with the id "result", or else the ajax success handler will not insert the received data/string anywhere.
These changes should make your code work.
I recommend adding an error handler to every ajax call you do. Also try to prevent your php files that are called by ajax methods to have cases where nothing is returned / echoed.
if(isset($_POST["status"]))
{
$query = "INSERT INTO tickets(status) VALUES (:status)";
$statement = $conn->prepare($query);
$statement->execute(array('status' => $_POST["status"]));
$count = $statement->rowCount();
if($count > 0)
{
echo "Data Inserted Successfully..!";
}
else
{
echo "Data Insertion Failed";
}
}
// ! add else statement
else
{
echo "unknown index: 'status'";
}
Also an interesting read about ajax error handling: setting response codes in PHP
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>
HI,
I have code like this. what I am doing is populating the first select with the MySQL data and based on the selection the first , using jQuery, I am populating the second one. Now, my question is, can I use the same combos_get.php to populate the another select based on user selection from the second select?
Is yes, then please look at the comment 'stuck at this point' where I am confused on how to get the data on the the third select.
<html>
<head>
<link href="style23.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title></title>
</head>
<body>
<div align="left" style="position:absolute;top:10px;">
<select name="select1" id="select1" size="10px;">
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "bob") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
$result = mysql_query("select * from results where ID NOT LIKE 'Ex%' ") or die(mysql_error());
// store the record of the "example" table into $row
while($row = mysql_fetch_array( $result )) {
// Print out the contents of the entry
?>
<option value="<?php echo $row['ID']; ?>"><?php echo $row['ID'] ?></option>
<?php
}
?>
</select><br>
<script type="text/javascript">
$(document).ready(function() {
$('#select1').change(getDropdownOptions);
// $('#select2').change(getDropdownOptions); // stuck at this point
});
function getDropdownOptions() {
var val = $(this).val();
//alert(val);
// fire a POST request to combos_get.php
$.post('combos_get.php', { value : val }, populateDropdown, 'html');
//alert('s');
}
function populateDropdown(data) {
if (data != 'error') {
$('#select2').html(data);
}
}
</script>
</div>
<div align="left" style="position:relative;left:250px;">
<select name="select2" size="10px;" id="select2">
<option value="--">--</option>
</select>
</div>
<div style="position:relative;left:450px;top:10px">
<select name="select3" size="10px;" id="select3">
<option value="--">--</option>
</select>
</div>
</body>
</html>
**combos_get.php**
<?php
if (!empty($_POST['value'])) {
$val = $_POST['value'];
mysql_connect("localhost", "root", "bob") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
$result = mysql_query("select ID2 from results where ID = \"$val\" ") or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
$html .= '<option value="1">'.$row['ID2'].'</option>';
}
die($html);
}
die('error');
?>
You will more than likely want another handler for this case. It's up to you whether or not the same PHP file can handle the query, however:
$(document).ready(function() {
$('#select1').change(getDropdownOptions);
$('#select2').change(getSecondDropdownOptions);
});
function getSecondDropdownOptions() {
var val = $(this).val();
$.post('combos_get.php', { value : val }, populateSecondDropdown, 'html');
}
function populateSecondDropdown(data) {
if (data != 'error') {
$('#YOURNEXTSELECT').html(data);
}
}
Common practice is to reuse as much code as possible. I don't have time to refactor since I just got to work but someone is more than welcome to clean this up for him.
In order to do that you need to make populateDropdown use a dynamic target.
something like:
function getDropdownOptions(event) {
var e = $(this);
var val = e.val();
// fire a POST request to combos_get.php
$.post('combos_get.php',{ value : val }, function(data){
populateDropdowns(data, e);
}, 'html');
}
function populateDropdown(data, e) {
// e is our originating select
/* HERE You need to come up with a way to determin the target to populate based on the element that triggered it. for example assuming you only have 3 selects:*/
switch(e.attr(id)){
case 'select2':
var targetSelector = '#select3';
break;
case 'select1':
var targetSelector = '#select2';
break;
default:
var targetSelector = null;
break;
}
if (data != 'error' && targetSelector) {
$(targetSelector).html(data);
}
}