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);
}
}
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 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.
a.html
function load(str)
{
xhttp.open("GET","a.php?q="+str,true);
xhttp.send();
}
}
<select name = "select" onchange ="load(this.value)">
<option selected = "selected">Select a movie</option>
<option value= "asc">Name in ascending order</option>
<option value = "genre">Genre</option>
</select>
a.php
$asc = $_POST['asc'];
$genre = $_POST['genre'];
if (!empty($_GET[$asc])) {
$sql = "SELECT * FROM movies order by Name ASC";
} else if (!empty($_GET[$genre])) {
$sql = "SELECT * FROM movies order by Genre ASC";
}
$db = mysql_connect("localhost","root","123");
$db_select = mysql_select_db('m',$db);
if ( ( $result = mysql_query( $sql, $db ) ) ) {
echo $result;
}
I want to select the value from dropdown button. For instance asc, and pass the value to a.php ($asc = $_POST['asc']). How could I do that?
<html>
<head></head>
<body>
<select class="movie" name="select">
<option selected = "selected">Select a movie</option>
<option value= "asc">Name in ascending order</option>
<option value = "genre">Genre</option>
</select>
<div class="showMovie"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$('.movie').change(function(){
var movieType= $('.movie').val();
$.ajax({url:"a.php?movieType="+movieType,cache:false,success:function(result){
$(".showMovie").html(result);
}});
});
</script>
</body>
</html>
a.php
<?php
$movieType = $_GET['movieType'];
if ($movieType == "asc") {
$sql = "SELECT * FROM movies order by Name ASC";
} else if ($movieType == "genre") {
$sql = "SELECT * FROM movies order by Genre ASC";
}
$db = mysql_connect("localhost","root","123");
$db_select = mysql_select_db('m',$db);
if (($result = mysql_query($sql, $db))) {
while($movieName = mysql_fetch_array($result)) {
echo $movieName['Name']."<br>";
}
}
?>
with your JS function, you send it via a "get" method.
so you have your value into $_GET['q'] ...
If you want to do a POST request, use a form, or an XmlHttp function:
function load(obj)
{
var xmlhttp = new XMLHttpRequest();
xmlxttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//called when xmlhttp event occurs, here when we receive the response
console.log(xmlhttp.responseText); //Print the response into the console
}
}
xmlhttp.open("POST", "a.php");
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); //we send it as form
xmlhttp.send(obj.value + "=" + encodeURICompopent(obj.innerHTML));
}
And call load(this) instead of load(this.value)
In php, to check is value is sent, just use isset:
if (isset($_POST['asc'])) //do something;
But I dislike this way to send values, it is deprecated: request parameters names should be static....
a.html
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#select_name').on('change', function() {
var str = $(this).val();
$.ajax({
type: "POST",
url: "a.php",
data: { q:str},
success: function(theResponse) {
// Output from ajaxpage.php
alert(theResponse); // comment this
}
});
});
});
</script>
<select name = "select_name" id = "select_name">
<option selected = "selected">Select a movie</option>
<option value= "asc">Name in ascending order</option>
<option value = "genre">Genre</option>
</select>
a.php
<?php
$db = mysql_connect("localhost","root","123");
$db_select = mysql_select_db('m',$db);
$q = isset($_POST['q']) ? $_POST['q'] : '';
if ($q == 'asc')
{
$sql = "SELECT * FROM movies order by Name ASC";
}
else if ($q == 'genre')
{
$sql = "SELECT * FROM movies order by Genre ASC";
}
else
{
echo 'Nothing';exit();
}
$qry = mysql_query($sql);
if (mysql_num_rows($qry) > 0)
{
$result = mysql_fetch_object($sql) ;
echo $result;
}
?>
<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'm stuck with this problem with in a week. What I have here is dropdown select with ajax posting value to another dropdown but now I need to post into textbox with autocomplete function. What I need is connect my autocomplete query and my ajax so that if I select for example ballpen, all ballpen will recommend in autocomplete. Please Help me with this. I need to finish it.
Here's my code
Ajax.php
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
</script>
</head>
<body>
<br/>
Drop1
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
Auto Complete <input id="tag">
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#tag').html(data);
}
});
});
</script>
getajax.php
In here I post the value in another dropdown but not I need to post into textbox.
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
while($row = $result1->fetch_assoc())
{
?>
<option value ="<?php echo $row['item_code'];?>"><?php echo $row['item'];?></option>';
<?php
}
}
?>
autocomplete.php
<?php
//$q=$_GET['q'];
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["q"]);
//$main = $mysqli->real_escape_string($_POST["mainlist_id"]); AND cat_code='$main'
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' GROUP BY id ORDER BY item" );
if($sql)
{
while($row=mysqli_fetch_array($sql))
{
echo $row['item']."\n";
}
}
?>
//whenever u select the tag field will get focus, and it automatically start searching so u no need to type see the callback focus function with $(this).autocomplete("search", ""); and minlength 0. u have to send the main value and get the response from here too
<script>
$(document).on("keyup", "#tag", function(){
$("#tag").autocomplete({
source: function(request, response) {
$.getJSON("autocomplete_gethere.php", { main: $("#main").val() }, response);
},
minLength:0
}).focus(function() {
$(this).autocomplete("search", "");
});
});
</script>
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#tag').focus(); //please note this, here we're focusing in that input field
}
});
});
</script>
untested, if any question post comment