JQuery chained selects implementation - php

I am a newbie as far as JQuery, AJAX & PHP are concerned and I am trying to build a form with chained selects that will provide initial data for a new mysql record.
I have downloaded the JQuery chained select remote plugin and for the life of me I cannot figure out how to get the data returned for the second select dropdown. The first dropdown is populated using another function and when the user selects a value from this dropdown, I want that value to be used as the search string for the second dropdown.
The code snippet for the main form is:
<?php
<head>
<script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../js/jquery.chained.remote.js" charset="utf-8"></script>
</script>
<script type="text/javascript">
$('#series').remoteChained("#series", "../models/json.php");
</script>
</head>
<body>
<form action="" method="post">
<table border="1">
<tr>
<th>Season:</th>
<td><select name="season" id="mark">
<option value="">Select Season...</option>
<?php
$i = 0;
while ($i < count($showseason)){ // obtain seasons from getseason() function
?>
<option value="<?php echo $showseason[$i]; ?>">
<?php echo $showseason[$i]; ?> </option>
<?php
$i++;
} ?>
</select></td>
<th>Competition:</th><td><select name="competition" id="series">
<option value="">Competition type...</option>
</select></td>
The following is the code for the Mysql select (json.php)
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php';
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/db_connect.php';
try
{
$result = $pdo->prepare("SELECT sideid, competition FROM pennantsides");
$result->execute();
echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
}
catch (PDOException $e)
{
$output = 'Error selecting records - Please contact your Site Administrator';
include $_SERVER['DOCUMENT_ROOT'] . '/views/output.html.php';
exit();
}

Isn't it $('#mark').remoteChained("#series", "../models/json.php"); you're trying to do ?
Also, what's the content of the json file when you launch it on your browser (or via whatever GET method you use) ?

Related

Catching the selected option's value

I want to pass a select option value through hyperlink to the next page and for this I have this code:
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<form name="search_form" role="form" method="GET" id="search_form" action="SearchResults.php">
<?php
try {
$conn = new PDO('sqlite:db/MyDatabase.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM attributes WHERE attributename='mushtype'");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<select id="mushtype" name="mushtype">
<option value="*" selected>Mushroom types</option>
<?php foreach($data as $row): ?>
<option value="<?php echo $row['idattributevalue']; ?>"><?php echo $row['attributevalueEN']; ?></option>
<?php endforeach; ?>
</select>
<?php
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Find Your Mushroom
</form>
</body>
</html>
For the default selected option I want to use (*) as value because if no option are selected, will stand as SELECT (all) FROM for my SQL query on the second page.
So, i tried to construct my hyperlink, but i don't know how to catch the selected option.
I tried to adapt from here
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['Movies'])) {
$selected = $_POST['Movies'];
echo 'You have chosen: ' . $selected;
} else {
echo 'Please select the value.';
}
}
?>
but I'm unable to do it.
Rigth now, my code inserting a value, but is without any control upon it.
Please help me to catch the selected option and insert it as value in my hyperlink. Thank you.
When you use <a>, you do not submit the inputs to the next page. Instead of
Find Your Mushroom
simply use
<input type="submit" value="Find Your Mushroom">
before closing the form.
Edit:
Depending on the <form method= you use ("get" or "post"), you will then either have $_GET['mushtype'] or $_POST['mushtype'] available in the next page. (Thanks to #ADyson!)
In my tests using method="get", the form inputs make their way to $_GET, but my uri parameters were not there. Using method="post" gave me both my uri parameters in $_GET and form details in $_POST, just in case you want to use both.
If you do not like the button style however, you can change it using CSS to look just like a regular hyperlink.

Displaying SQL row in PHP-based webpage based on selection from drop-down menu

Hi I'm trying to create a web-page that selects and displays the SQL row connected to the selected name from a drop-down menu. I've gotten everything to work except actually displaying the row when selected by the drop-down, here is some code I've cobbled together from various sources including Stack Overflow.
$conn = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
//if your connection succeded
$sql = "SELECT * FROM Charities" ;
$result = mysqli_query($conn,$sql);
?>
<form method="post" action="<?= $_SERVER['PHP_SELF']; ?>">
<select name="list">
<?php while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)): ?>
<option value="<?= $row['Name']; ?>"><?= $row['Name']; ?></option>
<?php endwhile; ?>
</select>
<input type="submit" value="See Points">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function(){
$("select[name=list]").on("change", function () {
var valueSelected = $(this).val();
$("#value-selected").html(valueSelected);
});
});
</script>
Currently I'm a little confused where to place the php prompt to display the information, I'm very new to PHP and SQL. Thank you for your help!
You can just add :
<p id="value-selected"></p>
You can add it between the form and the first script or before the form, or anywhere else in the html code.

Display Data from a dependent dropdown in php

i need help, i'm new to php and jquery
i created a two tier dependent dropdown list populated from mysql database,which uses two tables products and fieldo with pid as the foreign key.
//code for dropdown.php
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
</head><?php include "connectdb.php"; ?>
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "states.php",
data:'pid='+val,
success: function(data){
$("#state-list").html(data);
}
});
}
function showMsg()
{
$("#msgC").html($("SELECT name, email from fieldo where state = '#state-list option:selected'").text());
return false;
}
</script>
<body >
<form>
<label style="font-size:20px" >Products:</label>
<select name="product" id="product-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Products</option>
<?php
$sql="SELECT * FROM `Products` WHERE TYPE = 'BULK'";
$results=$dbhandle->query($sql);
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["pid"]; ?>"><?php echo $rs["Name"]; ?></option>
<?php
}
?>
</select>
<label style="font-size:20px" >State:</label>
<select id="state-list" name="state" >
<option value="">Select State</option>
</select>
<button value="submit" onclick="return showMsg()">Submit</button>
</form>
Result: <span id="msgC"></span><br>
</body>
</html>
//code for states.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">//alert("sdfsd");</script>
<body>
<?php
require_once("connectdb.php");
//$db_handle = new DBController();
$query ="SELECT oid,state FROM fieldo WHERE pid = '".$_POST["pid"]."'";
$results = $dbhandle->query($query);
?>
<option>Select State</option>
<?php
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["oid"]; ?>"><?php echo $rs["state"]; ?></option>
<?php
}
?>
</body>
</html>
this list is working correctly but i want to display the other columns of stated (email , name and contact) upon selection of the state.
its not working
Have you tried running the while loop without breaking the PHP script? It seems you are almost trying to run a for loop.
<?php
$sql="SELECT * FROM `Products` WHERE TYPE = 'BULK'";
$results=$dbhandle->query($sql);
while($rs=$results->fetch_assoc()) {
echo '<option value="' . $rs["pid"] . '">' . $rs["Name"] . '</option>';
}
?>
UPDATE
Okay, so I heard your comment, and I have used an ajax call to get the full display of the content; I was not really sure as to what you were trying to do with your showMsg() function. I was assuming you were wanting to create a new query request.
So I changed the function to create an Ajax call that would look something along these lines:
<script>
function showMsg()
{
var val;
val = $("#state-list").val();
$.ajax({
type: "POST",
url: "table.php",
data: "state_id="+val,
success: function(data){
$("#msgC").html(data);
}
});
}
</script>
And then table.php would be along these lines...
<?php
// check to see if state_id has been submitted
if(isset($_POST['state_id']))
{
$state_id = $_POST['state_id'];
}
// if it is not set, add something in place.
else
{
$state_id = "1";
}
// query goes here - ask for the ID
$query = "SELECT name, email from fieldo where state = " . $state_id;
$results = $dbhandle->query($query);
while($rs=$results->fetch_assoc()) {
//... create table with all content;
}
?>
PHP cannot react to what is happening in the browser. Once PHP has processed the page and the web server has sent it to the browser, JavaScript takes over.
This means that if a customer selects a new state, it will not automatically get PHP to populate the rest of the page with the matching email, name and contact. You need to change your approach a bit.
One approach is to use Ajax. It would work like so:
In jQuery, register an onChange event handler for the states dropdown.
When customer selects a new state, the event handler will be triggered. Within the handler, make an Ajax request that sends the PHP the selected state.
the PHP document that receives the request would query for the matching email, name and contact from the DB and send the results, perhaps as a JSON
Back in the jQuery handler, when data comes back from the PHP server (in the response callback), use that data to populate the page with the right email, name and contact.
An alternative, even simpler approach (if you don't have a lot of data) is to have PHP send all data at once in a multi-dimensional array when the page loads. This time when the user selects a new state, the jQuery event handler will look up the data under that state within the big array, and fill the form with the data.

Run different query based on a dynamic HTML dropdown list

I made some PHP code to generate this page. I successfully get all the items from a column into a HTML dropdown list (it's a dynamic list). I want to write some code so that when user selects an item from the list and hit submit, it will take user to a new page contains corresponding information on it. I have no idea what kind of code would be included in. Please help. Thanks!
For instance, if user select 50A-1, it will populate a table has all the items located at 50A-1.
Two pieces of code I wrote, first is the page gives you the dropdown list and the submit button. The second is the result page, but it only shows the whole inventory so far, it doesn't have a way to connect to the dropdown list option.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Inventory</title>
</head>
<body>
<div>
<a>SQL Connection test</a>
<form action="connect.php" method="POST">
<div class="center">
<input type="submit" value="Connect to MySQL" />
</div>
</form>
</div>
<div>
<section>
<article>
<p>
<select name="dropdown">
<?php query() ?>
</select>
<?php close() ?>
</p>
</article>
</section>
<div>
<input type="submit" value="Submit" />
</div>
</div>
</body>
</html>
Second page
<?php
include_once 'db.inc.php';
// connect
function connect() {
// Connect to the MySQL server
mysql_connect(DB_HOST,DB_USER,DB_PASS) or die ('Could not connect to server!' . mysql_error());
mysql_select_db(DB_NAME);
}
// close
function close() {
mysql_close();
}
// query
function query() {
$myData = mysql_query("SELECT DISTINCT * FROM sheet0_100 GROUP BY location");
while($record = mysql_fetch_array($myData)) {
echo '<option value="' . $record['location'] . '">' . $record['location'] . '</option>';
}
}
?>
That's the purpose of HTML forms :)
You need to create a form to encapsulate that select:
<form action="process.php" method="get">
<select name="inventory_id">
<!-- Here all options -->
</select>
<button type="submit">See items</button>
</form>
Then in process.php you need to get the selected element and query the database, for example (I assume that you're using PDO):
<?php
$inventory_id = $_GET['inventory_id'] // The name attribute of the select
// Then you prepare the query
$query = "SELECT * FROM sheet0_100 WHERE id = :inventory_id";
// Execute the query and show the data...
use Sessions
example:
on your first page
session_start();
$_SESSION['your-dropdown-list-value'] = 'Root';
on your new page
//error_reporting(E_ALL);
session_start();
if(isset($_SESSION['your-dropdown-list-value'])) {
echo "Your dropdown selection " . $_SESSION['your-dropdown-list-value'];
}

return data from php dropdownlist after submit

hey guys i've passed way more time on this then what i originally wanted to...
so i have this code here, where i have a drop list give me data from a sql database from the selection of 3 radio buttons, that all works fine.
My problem come when i want to submit my form and get info of the data in said droplist. all i want is put the selected radio and the selected item in the single drop list in variables in the submission.php that comes after the post method of the form...
anyway thats what i want to do for now
<?php
require "../Scripts/config.php"; // database connection here
?>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>test</title>
<SCRIPT language=JavaScript>
function reload()
{
for(var i=0; i < document.form1.type.length; i++){
if(document.form1.type[i].checked)
var val=document.form1.type[i].value
}
self.location='bob.php?type=' + val ;
}
</script>
</head>
<body>
<?Php
$tp=$_GET['type']; // getting the value from query string
if(strlen($tp) > 1){$sql="SELECT * FROM Subcategory where cat_id='$tp'";}
echo $sql;
echo "<form name=form1 id=form1 method=post action=submissions2.php>";
echo "<select name=Subcategory id=Subcategory value=''>Subcategory</option>"; // printing the list box select command
foreach ($dbo->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[cat_id]>$row[Subcategory]</option>";
/* Option values are added by looping through the array */
} echo "</select>";// Closing of list box
echo "<br>";
echo "<br>";
echo "<br>";
echo "
<b>Type</b>
<input type=radio name=type value='1_Cosplay' onclick=\"reload()\";>Cosplay
<input type=radio name=type value='1_Modeling' onclick=\"reload()\";>Modeling
<input type=radio name=type value='1_Zombie' onclick=\"reload()\";>Zombie
<input type=submit value=Submit> </form>";
echo "<br>";
echo "<br>";
echo "<br>";
?>
</body>
</html>
and this is the submissions2.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="../Scripts/jquery-1.8.0.min.js"></script>
</head>
<body>
<?php
function filter($data) {
/*$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);*/
return $data;
return $row;
}
foreach($_POST as $key => $value) {
$mydata[$key] = filter($value);
}
echo $mydata['Subcategory'];
echo "<br>";
?>
</body>
</html>
all i seem to be able to get is the radio button choice.
Here is an all-in-one solution. You need to change some references like what the name/local path of the file path is, but anyway, this contains all the code. I can not test the DB stuff but the ajax works if you have the correct url path in the jQuery portion. Note, this solution references itself, not a new page:
// Display errors for troubleshooting
ini_set('display_errors','1');
error_reporting(E_ALL);
class CategorySelector
{
public function LoadSubCat()
{
// You will be subjected to an injection hack if you don't filter or encode this variable
// You should do PDO with prepared statements
$parent_cat = htmlspecialchars($_GET['parent_cat'], ENT_QUOTES);
$query = $this->Fetch("SELECT id,subcategory_name FROM subcategories WHERE categoryID = '$parent_cat'");
// Uncomment this to see how this returns
// $this->PrintPre($query); ?>
<label for="sub_cat">Sub Category</label>
<select name="sub_cat" id="sub_cat">
<?php
if($query !== 0) {
foreach($query as $row) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['subcategory_name']; ?></option>
<?php
}
} ?>
</select>
<?php
}
public function Form()
{
// Get rows for categories
$results = $this->Fetch("SELECT id,category_name FROM categories");
// Uncomment this to see how this returns
// $this->PrintPre($results); ?>
<form name="form1" id="form1" method="post">
<label for="parent_cat">Parent Category</label>
<select name="parent_cat" id="parent_cat">
<?php
if($results !== 0) {
foreach($results as $row) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
<?php }
} ?>
</select>
<!-- This is a container that will load in your next menu -->
<div id="sub_cat_container"></div>
<input type="submit" name="submit" value="submit" />
</form>
<?php
}
public $rowCount;
// This is strictly a returning engine for SQL statements
protected function Fetch($_sql)
{
include_once('config.php');
// You really should do prepared statements (PDO)
// This way of calling sql is depricated
$query = mysql_query($_sql);
// Save the row count
$this->rowCount = mysql_num_rows($query);
// If there are rows return them
if($this->rowCount > 0) {
$_array = array();
// Loop through
while($result = mysql_fetch_array($query)) {
$_array[] = $result;
}
}
// Send back your query results for processing
// If no results, return false/0
return (isset($_array))? $_array:0;
}
protected function PrintPre($_array)
{ ?>
<pre>
<?php print_r($_array); ?>
</pre>
<?php
}
}
// Uncomment this for testing that the AJAX is working.
// print_r($_REQUEST);
// This is probably not the best way to do this all, but for sake
// of trying to get it all to work, this whole thing will ajax to
// itself, but if you can get it to work on this one page, you
// can split it up into two pages.
// Ok, so this creates a new instance of this whole system
$builder = new CategorySelector();
// If this page receives a GET request for $_GET['parent_cat'], just process it.
// That action is to call the sub_cat dropdown menu from this object
if(isset($_REQUEST['parent_cat']) && !empty($_REQUEST['parent_cat'])) {
$builder->LoadSubCat();
}
// If there is no request, display the html page
else {
// You should not have space before the <!doctype>. Some browsers act funky if there is space before
?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
// I'm not a javascript person, so this portion is kind of sloppy
$(document).ready(function(){
$('#parent_cat').change(function() {
// Get value
var ElmVal = $('#parent_cat').val();
$.ajax({
// You need to reference this page in the "thispage.php" whatever this page is called
url:"/thispage.php?parent_cat="+ElmVal,
success:function(result) {
$("#sub_cat_container").html(result);
}});
});
});
</script>
</head>
<body>
<?php
// Display the form.
$builder->Form(); ?>
</body>
</html>
<?php } ?>
Quote all your HTML attributes like name='Subcategory', and
echo "<option value=$row[cat_id]>$row[Subcategory]</option>"
should be
echo "<option value='{$row['cat_id']}'>{$row['Subcategory']}</option>";
Your coding practice is horrible, by the way. You are not testing to see how many rows you have in your MySQL query, and you don't need to echo on each line. You can do this:
echo '<br />'.
'<br />';
Of course, using line breaks like that is a bad practice, as well. Use CSS.

Categories