Can't $_GET or $_POST Dynamic Drop Down Variables - javascript

JavaScript
// JQuery script is on ajax.php page
// JQUERY PIECE TO PROCESS STATE AND CITY VALUES
// BASED ON COUNTRY SELECTION
function change_CountryNo() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "ajax.php?CountryNo=" + document.getElementById("CountryNodd").value, false);
xmlhttp.send(null);
document.getElementById("StateID").innerHTML = xmlhttp.responseText;
if (document.getElementById("CountryNodd").value == "CountryNo") {
document.getElementById("CityID").innerHTML = "<select><option>City</option></select>";
}
}
function change_StateID() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "ajax.php?StateID=" + document.getElementById("StateIDdd").value, false);
xmlhttp.send(null);
document.getElementById("CityID").innerHTML = xmlhttp.responseText;
if (getElementById("StateIDdd").value == "StateID") {
document.getElementById("CityID").innerHTML = "<select><option>City</option></select>";
}
}
<!DOCTYPE html>
<html>
<head>
<!-- index.php -->
<!-- THIS CODE PROVIDES A DROP DOWN FORM
FOR USER TO SELECT COUNTRY THEN STATE THEN CITY
A JQUERY SCRIPT PROCESSES THE COUNTRY VALUE
TO PRODUCE THE APPROPRIATE STATES AND
PROCESSES THE STATE VALUE TO PRODUCE
THE APPROPRIATE CITIES -->
<title>Country, State, City Selection</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<!-- THESE FILES ARE DATABASE CONNECTION AND FUNCTIONS
FOR VARIOUS LOGIN, USER SESSION VARIABLES TO IDENTIFY
THE CONTACT NO OF USER UPDATING THEIR LOCATION -->
<?php include("includes/header.php") ?>
<?php include("includes/nav.php") ?>
<?php //Check user's login status
if (logged_in() === false) {
echo "Redirecting...";
redirect("../index.html");
}
?>
<!-- responsive setup for form -->
<div class="row">
<div class="col-lg-6 col-lg-offset-3">
</div>
</div>
<!-- end of class row div -->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-login">
<div class="panel-heading">
<div class="row">
<div class="col-xs-12">
<div class="col-xs-6">
</div>
<div class="col-xs-6">
Country-State-City Selection
</div>
</div>
<hr>
</div>
<!-- end of class row div -->
<div class="panel-body">
<div class="row col-md-12" style="text-align: center">
<form method="POST" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>" autocomplete="off">
<div id="CountryNo" class="col-xs-3 form-group" style="font-size: 75%">
<select id="CountryNodd" name="CountryNodd" onChange="change_CountryNo()" class="form-control selectpicker" style="width:100%;">
<option>Country</option>
<?php
$res=mysqli_query($con, "SELECT * FROM countries ORDER BY Country_Descrip");
while($row=mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["CountryNo"]; ?>"><?php echo $row["Country_Descrip"]; ?></option>
<?php $CountryNodd = $_POST["CountryNo"]; ?>
<?php }
?>
</select>
</div>
<div id="StateID" class="col-xs-3 form-group" style="font-size: 75%">
<select id="StateIDdd" name="StateID" class="form-control selectpicker" style="width:100%;">
<option>Product</option>
</select>
</div>
<div id="CityID" class="col-xs-3 form-group" style="font-size: 75%">
<select id="CityIDdd" name="CityIDdd" class="form-control selectpicker" style="width:100%;">
<option>Brand</option>
</select>
</div>
<div class="form-group">
<img src="img\..." class="img-responsive" alt="Country-State-City Image" width="100%" height="auto">
<div class="col-lg-12 text-center">
<br>
<input type="submit" name="reset" id="reset" tabindex="3" class="form-control btn btn-register" value="Reset Country-State-City Selections" required>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 text-center">
<br>
<input type="submit" name="Update My Country-State-City" id="update" tabindex="4" class="form-control btn btn-register" value="Update My Country-State-City" required>
</div>
</div>
</form>
<!-- end of form -->
</div>
<!-- end of row col-md-12 div -->
</div>
<!-- end of panel-body div -->
</div>
<!-- end of panel-heading div -->
</div>
<!-- end of panel-login div -->
</div>
<!-- end of col-md-6 col-md-offset-3 div -->
</div>
<!-- end of class row div -->
<!-- ajax.php -->
<!DOCTYPE HTML>
<html>
<head>
<title>ajax.php</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<?php
//THIS FILE PROCESSES THE JQUERY SELECT BASED ON COUNTRY INPUT AND
//THE STATE INPUT
// Turn off error reporting
error_reporting(0);
$con=mysqli_connect('localhost', 'root', '', 'contact_info');
mysqli_set_charset($con,"utf8");
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
// Get the Country and State Values User Selects
$CountryNo=$_GET["CountryNo"];
$StateID=$_GET["StateID"];
//Check user selection for country and list states
if($CountryNo!="Country")
{
$query="SELECT State_ID, StateCountry_ID, State_Description FROM states WHERE StateCountry_ID=$CountryNo ORDER BY State_Description";
$result=mysqli_query($con, $query);
echo "<select id='StateIDdd' onchange='change_StateID()' selected>";
echo "<option>"; echo "State"; echo "</option>";
while($row=mysqli_fetch_array($result))
{
echo "<option value='$row[State_ID]'>"; echo $row["State_Description"]; echo "</option>";
}
echo "</select>";
}
//Check user selection for state and list cities
if($StateID!="State")
{
$query="SELECT CityID, City_Name, CountryNo, CityState_ID FROM cities WHERE CityState_ID=$StateID ORDER BY City_Name";
$result=mysqli_query($con, $query);
echo "<select>";
while($row=mysqli_fetch_array($result))
{
echo "<option value='$row[CityID]' selected>"; echo $row["City_Name"]; echo "</option>";
}
echo "</select>";
}
?>
<?php include("ajax2.php") //Go to post to MySQL processing
?>
</head>
</html>
<!-- ajax2.php -->
<!-- THIS FILE POSTS THE COUNTRY, STATE, CITY VALUES TO
MYSQLI AND UPDATES THE USER'S CONTACT LOCATION -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<?php include("includes/header.php") ?>
<?php include("includes/nav.php") ?>
<?
// Turn off error reporting
error_reporting(0);
$con=mysqli_connect('localhost', 'root', '', 'contact_info');
mysqli_set_charset($con,"utf8");
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
?>
<?
// Ensure user is logged in to get values
// for ContactNo
php if (logged_in() === false) {
echo "Redirecting...";
redirect("../index.html");
}
//store country, state, city selection and update contact's location
$CountryNo = $_POST['CountryNodd'];
$StateID = $_POST['StateIDdd'];
$CityID = $_POST['CityIDdd'];
//Update MySQL
$sql = "UPDATE contact_location SET CountryNodd=$CountryNo, StateID=$StateID, CityID=$CityID";
$sql.= "WHERE ContactNo=$ContactNo"; //Contact info is from contact table accessed via function include in header.php
$res_update = mysqli_query($con,$sql);
if($res_update) {
echo "Location updated successfully";
}
else {
echo "Not working...";
}
?>
I've read related questions/responses, but none resolve my problem.
I am very new to jQuery & PHP programming with a MySQL backend.
Created a 3-level drop down (Country-State-City) form where users
can select country-state-city values, which will update
MySQL.
While I can GET and POST the Country variable, I have been
unsuccessful for State and City. I can see the correct value of
the State variable, but I do not see a value for the City variable.
Furthermore, I cannot POST either the State or City variables: I get an
"Index Undefined" error for the variables associated with each.

SOLVED: The POST execution was occurring before the JavaScript actions, and this is because PHP, server side, is executed before Java, client-side. I moved the MySQL update code into the PHP script at the point the City selection has occurred.
I will not provide the code because comments I received thus far suggest my documentation needs work. Certainly appreciate that feedback and will take steps to improve future posts. Thank you!

Related

How to populate table row data in collapsible sidebar form on button click?

I am trying to populate a collapsible sidebar form, with table row data on button click of specific record from the table (Similar to action button EDIT). The HTML of the collapsible sidebar is on the same php page. Can any one help me with code to populate the collapsible sidebar form with the selected rows data.
Requirement: While clicking on edit button of particular row, the collapsible sidebar has to toggle and the row data has to be displayed in the form of sidebar.
Bellow is my php code with collapsible sidebar
<?php
require_once 'authentication/auth.php';
// HTML authentication
authHTML();
require_once "configs/config.php";
$session_username = $_SESSION["username"];
$query = "SELECT username, ticket_title, ticket_category, ticket_status FROM tickets_file ";
$result1 = mysqli_query($link, $query);
?>
<!-- Data list view starts -->
<section id="data-list-view" class="data-list-view-header">
<!-- DataTable starts -->
<div class="table-responsive">
<table class="table data-list-view">
<thead>
<tr>
<th></th>
<th>USER NAME</th>
<th>TITLE</th>
<th>CATEGORY</th>
<th>STATUS</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
<?php while($row1 = mysqli_fetch_array($result1)):;?>
<tr>
<td></td>
<td class="product-name"><?php echo $row1[0];?></td>
<td class="product-category"> <div class="chip chip-warning">
<div class="chip-body">
<div class="chip-text"><?php echo $row1[1];?></div>
</div>
</div></td>
<td class="product-category"><?php echo $row1[2];?></td>
<td class="product-name"><?php echo $row1[3];?></td>
<td class="product-action">
<span class="action-edit"><i class="feather icon-eye"></i></span>
</td>
</tr>
<?php endwhile;?>
</tbody>
</table>
</div>
<!-- DataTable ends -->
<!-- add new sidebar starts -->
<div class="add-new-data-sidebar">
<div class="overlay-bg"></div>
<div class="add-new-data">
<div class="div mt-2 px-2 d-flex new-data-title justify-content-between">
<div>
<h4 class="text-uppercase">List View Data</h4>
</div>
<div class="hide-data-sidebar">
<i class="feather icon-x"></i>
</div>
</div>
<div class="data-items pb-3">
<div class="data-fields px-2 mt-3">
<div class="row">
<div class="col-sm-12 data-field-col">
<label for="data-name">Name</label>
<input type="text" class="form-control" id="data-name">
</div>
<div class="col-sm-12 data-field-col">
<label for="data-category"> Category </label>
<select class="form-control" id="data-category">
<option>Audio</option>
<option>Computers</option>
<option>Fitness</option>
<option>Appliance</option>
</select>
</div>
<div class="col-sm-12 data-field-col">
<label for="data-status">Order Status</label>
<select class="form-control" id="data-status">
<option>Pending</option>
<option>Canceled</option>
<option>Delivered</option>
<option>On Hold</option>
</select>
</div>
<div class="col-sm-12 data-field-col">
<label for="data-price">Price</label>
<input type="text" class="form-control" id="data-price">
</div>
<div class="col-sm-12 data-field-col data-list-upload">
<form action="#" class="dropzone dropzone-area" id="dataListUpload">
<div class="dz-message">Upload Image</div>
</form>
</div>
</div>
</div>
</div>
<div class="add-data-footer d-flex justify-content-around px-3 mt-2">
<div class="add-data-btn">
<button class="btn btn-primary">Add Data</button>
</div>
<div class="cancel-data-btn">
<button class="btn btn-outline-danger">Cancel</button>
</div>
</div>
</div>
</div>
<!-- add new sidebar ends -->
</section>
<!-- Data list view end -->
</div>
</div>
</div>
<!-- END: Content-->
<div class="sidenav-overlay"></div>
<div class="drag-target"></div>
I will be using MySQLi for my answer specifically. Another method would be using PDO.
My first example will fetch one row through a WHERE clause (under the assumption that username is unique). If you need to pull all the data and use loops to construct HTML, as well as display a lot of row data, see second example instead.
First Example:
<?php
// DB variables
$servername = "DBSERVER";
$username = "DBUSER";
$password = "DBPASS";
$dbname = "DBNAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
// Your session variable
$session_username = $_SESSION["username"];
/*
Since you have the username in a session variable,
you don't really need to pull the username from the database (again).
Simply use the session variable. However, I pull the username
either way since that's what you did initially.
*/
// Declare SQL query
$sql = "SELECT
username,
ticket_title,
ticket_category,
ticket_status
FROM
tickets_file
WHERE
username = ?";
// Prepare and bind
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $session_username);
// Execture query
$stmt->execute();
// Bind result(s) to variable(s)
$stmt->bind_result($username, $ticket_title, $ticket_category, $ticket_status);
// Fetch result(s)
$stmt->fetch();
// Close connection
$stmt->close();
$conn->close();
?>
Since we have bound our data to the different variables: $username, $ticket_title ... etc. we can now use them anywhere we see fit by simply echoing the variable, example:
<?php echo $ticket_title; ?>
Second Example:
<?php
// DB variables
$servername = "DBSERVER";
$username = "DBUSER";
$password = "DBPASS";
$dbname = "DBNAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
// Declare the query
$sql = "SELECT
username,
ticket_title,
ticket_category,
ticket_status
FROM
tickets_file";
// Prepare
$stmt = $conn->prepare($sql);
// Execute the query
$stmt->execute();
// Get result of query
$result = $stmt->get_result();
// Close connection
$stmt->close();
$conn->close();
// Loop through the result(s)
while ($data = $result->fetch_assoc()) {
/*
Then to display the results you simply echo $data['row_name_here'];
Example: echo $data['ticket_title'];
Pair that with your HTML structure and you're good to go.
*/
}
?>
I would recommend that you look up MySQLi and/or PDO. I would also recommend that you look up prepared statements and parametized queries. The MySQLi and PDO links also cover the topic within a PHP environment. This will be very important moving forward, because it will make your applications secure against SQL Injection Attacks.

How to delete a complete row on button click in javascript?

I have a html/php code as shown below. The below html/php code is working in a way that on adding rows, we can select date from every row and can save it as well.
Two things need to be done.
On clicking Delete button, it should remove the value from the JSON array because everything is pulled from the JSON after saving the form.
Also, on clicking Delete button it should delete the complete row from the DOM.
you should give each added row an id corresponding to its rank:
row.id=i.toString();
then use the following code to remove the row:
var row = document.getElementById(rowrankid);
row.parentNode.removeChild(row);
I have prepared a code sample for you using your example that does exactly what you say.
It is using a javascript fetch post request to post to the script you have provided to remove the dom elements and update the json file.
I have changed some of your paths slightly so you will need to change those back (add in the ../feeds/ parent directory)
Once the user has pressed the button the page will reload, showing the updated interface that is loaded from the json file.
There are some improvements that could be made, for example the javascript is not checking to make sure the request was successful before reloading, but as the input is date select it should be ok.
<?php
if(file_exists('./ptp-ess_landing_house.json')){
$data = json_decode(file_get_contents('./ptp-ess_landing_house.json'));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_POST = json_decode(file_get_contents('php://input'), true);
if(isset($_POST['requestType']) && in_array($_POST['requestType'], ['remove'])) {
switch ($_POST['requestType']) {
case 'remove' :
//Unset the values
unset($data->row_delete[$_POST['data'] -1]);
unset($data->house_sitting_date[$_POST['data'] -1]);
//We are reindexing the arrays as we have deleted some rows, note that we are using +1 array indexes
$data->row_delete = array_values($data->row_delete);
$data->house_sitting_date = array_values($data->house_sitting_date);
foreach($data->row_delete as $key=>$value) {
$data->row_delete[$key] = strval($key+1);
}
//Write the file back
$fp = fopen('./ptp-ess_landing_house.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
header("HTTP/1.1 200 OK");
echo 'ok';
die;
break;
default:
}
}
}
?>
<script>
function rowDelete(row) {
//Make a request to your entry file (index.php here) to do the removal
fetch('/index.php', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({requestType: 'remove', data: row})
}).then(function(response) {
location.reload();
return response;
});
}
</script>
<?php if($data) { ?>
<form method="post">
<div id="rows" style="display:flex; justify-content: center;"><!-- Big div START -->
<!-- Remove Button START -->
<div class="rows-delete">
<h4 style="text-align:center;">Delete Rows</h4>
<?php if (empty($data->row_delete)) { ?>
<div class="row-delete" style="margin-right:30px; margin-top:22.5px;">
<button type="button" id="delete" onclick="rowDelete()">Remove</button>
<input type="hidden" name="row_delete[]" value="1" />
</div>
<?php } else { ?>
<?php foreach ($data->row_delete as $row_delete){ ?>
<div class="row-delete" style="margin-right:30px; margin-top:22.5px;">
<button id="delete" type="button" onclick="rowDelete(<?php echo $row_delete;?>)">Remove</button>
<input type="hidden" name="row_delete[]" value="<?php echo $row_delete;?>" />
</div>
<?php }} ?>
</div>
<!-- Remove Button END -->
<!-- Sitting Date START -->
<div class="sitting-days">
<h4 style="text-align:center;">Select Date</h4>
<?php if (empty($data->house_sitting_date)) { ?>
<!-- Select Date START -->
<div class="select-date" style="margin-right:30px; margin-top:20px;">
<input type="date" class="house-sitting-date" name="house_sitting_date[]" value="">
</div>
<?php } else { ?>
<?php foreach ($data->house_sitting_date as $date){ ?>
<!-- Select Date START -->
<div class="select-date" style="margin-right:30px; margin-top:20px;">
<input type="date" class="house-sitting-date" name="house_sitting_date[]" value="<?php if($date) {echo $date;}?>">
</div>
<!-- Select Date END -->
<?php }} ?>
</div>
<!-- Sitting Date END -->
</div><!-- Big div END -->
</form>
<?php } else {
echo 'Cannot read JSON settings file';
}
?>
If your json is known at the front-end (which I think you are implying, since your rowDelete is a JS-function), you can pass this with the call to rowDelete. Then you can traverse the DOM to get to value the corresponding sibling input-field (perhaps something like this.parentNode.childNodes[1]).
Once you have that value, you can easily remove it from the corrsponding array in your json:
let d = '2020-01-30'
let idx = arr.indexOf(d)
let newdates = ([...arr.slice(0,idx), ...arr.slice(idx+1)])
data.house_sitting_date = newdates
(with some additional index bounds checking, of course).
After that, you can perform a similar DOM traversal to remove the corresponding element from the DOM.
Flash, unfortunately, the desing of the code itself is not much professional... there are separate loops for rows (in php), which instead should be only 1 loop, like (with example simple Javascript binding on click):
<?php
for ($i=0; $i<count($data["house_sitting_date"]); $i++)
{
echo '<div class="remove"><a id="'.$data["row_delete"][$i].'" onclick="deleteRow(this);">Remove</a></div>';
echo '<div class="date">....</div>';
...
}
?>
<script> function deleteRow(el) { el.remove(); } </script>
also, lots of embedded style="".. codes, instead you might use 1 style file.
This is how I did in past, and it works perfectly
Prerequisite for this answer to work is each button and input field should be in DIV with unique id and there should be container for all these div in my case its .
On Add button(if you have one) you need clone node, and paste it under or above the element where it was clicked,
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#row'+rownumber).cloneNode( true );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
Then every time you add a new row or delete a row you need to append ids on these row, to do this you would a common class for all these rows in my case I used, rows
function changeids()
{
let rows =document.getElementsByClassName('rows');
for(let i=0; i<rows.length; i++)
{
let thisid="row"+i;
rows[i].setAttribute("id", thisid);
let thisAddButton = rows[i].getElementsByClassName("add")[0];
let thisDeleteButton = rows[i].getElementsByClassName("delete")[0];
let onclickaddfunction = "addrow("+i+")";
thisAddButton.setAttribute("onclick", onclickaddfunction);
let onclickDeletefunction = "removerow("+i+")";
thisDeleteButton.setAttribute("onclick", onclickDeletefunction);
}
}
Then when you remove you need to remove node and call changeids again
function removerow(rownumber){
document.getElementById('row'+rownumber).remove();
changeids();
}
This would give you whole working idea of add and delete rows, whole code below please ignore my messy code, just did it to give you and idea
<p>
<div id="row1" class="rows">
<button class="add" onclick="addrow(1)">add</button>
<button class="delete" onclick="removerow(1)"> remove </button>
<input type="text">
</div>
</p>
<script>
function addrow(rownumber)
{
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#row'+rownumber).cloneNode( true );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
changeids();
}
function removerow(rownumber)
{
document.getElementById('row'+rownumber).remove();
changeids();
}
function changeids()
{
let rows =document.getElementsByClassName('rows')
for(let i=0; i<rows.length; i++)
{
let thisid="row"+i;
rows[i].setAttribute("id", thisid);
let thisAddButton = rows[i].getElementsByClassName("add")[0];
let thisDeleteButton = rows[i].getElementsByClassName("delete")[0];
let onclickaddfunction = "addrow("+i+")";
thisAddButton.setAttribute("onclick", onclickaddfunction);
let onclickDeletefunction = "removerow("+i+")";
thisDeleteButton.setAttribute("onclick", onclickDeletefunction);
}
}
</script>
To delete row from dom, you have to specify unique id for main element of row and you can use [ElementObject].remove() method to delete, So everything inside that will be removed.
Also You should simplify and change JSON data, so that it will delete from json also using ajax with using single id(key) as parameter.
Here is the working code:
<?php
if (!empty($_GET)) {
if (!empty($_GET['action']) && $_GET['action'] == 'delete') {
if(file_exists('ptp-ess_landing_house.json')) {
$data = json_decode(file_get_contents('ptp-ess_landing_house.json'), true);
if (!empty($_GET['row_number'])) {
unset($data[$_GET['row_number']]);
$fp = fopen('ptp-ess_landing_house.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
echo 1;
exit;
}
}
echo 0;
exit;
}
}
if (!empty($_POST)) {
$output = array();
if (!empty($_POST['row_item'])) {
$output = $_POST['row_item'];
}
$fp = fopen('ptp-ess_landing_house.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
$data = array();
if(file_exists('ptp-ess_landing_house.json')) {
$data = json_decode(file_get_contents('ptp-ess_landing_house.json'), true);
}
?><form method="post">
<!-- Add New Row Button START -->
<div class="plus-minus-button" style="text-align:center;">
<button type="button" id="addRow" onclick="rowAdd()">+</button>
</div>
<!-- Add New Row Button END -->
<div id="maindiv">
<div style="display:flex; justify-content: center;">
<div class="rows-delete" style="text-align:center;">
<div class="row-delete" style="margin-right:30px;">
<h4 style="text-align:center;">Delete Rows</h4>
</div>
</div>
<div class="sitting-days" style="text-align:center;">
<div class="select-date" style="margin-right:30px;">
<h4 style="text-align:center;">Select Date</h4>
</div>
</div>
<div class="choose-options" style="text-align:center;">
<div class="yes-no-option" style="display:inline-grid;">
<h4 style="text-align:center;">Yes/No</h4>
</div>
</div>
</div>
<!-- Big div START --><?php
$totalrow = 0;
foreach ($data AS $key => $row) {
?><div id="row-<?php echo $key; ?>" style="display:flex; justify-content: center; margin-top:20px;"><?php
?><div class="rows-delete" style="text-align:center;">
<div class="row-delete" style="margin-right:30px;">
<button type="button" class="delete" onClick="delete_row(this.value)" value="<?php echo $key; ?>">Remove</button>
<input type="hidden" name="row_item[<?php echo $key; ?>][row_delete]" value="<?php echo $row['row_delete'];?>" />
</div>
</div>
<!-- Remove Button END -->
<!-- This is what I have tried to add a button (END) -->
<!-- Sitting Date START -->
<div class="sitting-days" style="text-align:center;">
<div class="select-date" style="margin-right:30px;">
<input type="date" class="house-sitting-date" name="row_item[<?php echo $key; ?>][house_sitting_date]" value="<?php echo $row['house_sitting_date']; ?>">
</div>
</div>
<!-- Sitting Date END -->
<!-- YES/NO START --><?php
?><div class="choose-options">
<div class="yes-no-option" style="display:inline-grid;">
<select name="row_item[<?php echo $key; ?>][house_sitting_date_yes_no]" class="house-yes-no" style="height:24px; ">
<option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "nada" ) echo "selected";?>>Please choose an option</option>
<option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "yes" ) echo "selected";?>>Yes</option>
<option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "no" ) echo "selected";?>>No</option>
</select>
</div>
</div>
<!-- YES/NO END -->
</div><?php
if ($key > $totalrow) $totalrow = $key;
else $totalrow++;
}
?>
<input type="hidden" name="totalrow" id="totalrow" value="<?php echo $totalrow; ?>">
</div>
<!-- Big div END -->
<hr />
<div style="text-align:center;">
<input type="submit" value="submit" />
</div>
</form>
<script>
function delete_row(row_number) {
var data = '<?php echo json_encode($data) ?>';
data = JSON.parse(data);
if (typeof(data[row_number]) != undefined) {
var request = new XMLHttpRequest();
request.open("GET", "index.php?action=delete&row_number=" + row_number);
request.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var row = document.getElementById('row-'+row_number);
row.remove();
}
}
request.send();
}
else {
var row = document.getElementById('row-'+row_number);
row.remove();
}
}
function rowAdd(event) {
var totalrow = document.getElementById("totalrow").value;
totalrow = parseInt(totalrow) + 1;
document.getElementById("maindiv").insertAdjacentHTML('beforeend', newRow(totalrow));
document.getElementById("totalrow").value = totalrow;
}
function newRow(row_number) {
return `<div id="row-` + row_number + `" class="sitting-days" style="display:flex; justify-content:center; margin-top:20px;">
<div class="rows-delete" style="text-align:center;">
<div class="row-delete" style="margin-right:30px;">
<button type="button" class="delete" onClick="delete_row(this.value)" value="` + row_number + `">Remove</button>
<input type="hidden" name="row_item[` + row_number + `][row_delete]" value="` + row_number + `" />
</div>
</div>
<div class="sitting-days" style="text-align:center;">
<div class="select-date" style="margin-right:30px;">
<input type="date" class="house-sitting-date" name="row_item[` + row_number + `][house_sitting_date]" value="">
</div>
</div>
<div class="choose-options">
<div class="yes-no-option" style="display:inline-grid;">
<select name="row_item[` + row_number + `][house_sitting_date_yes_no]" class="house-yes-no" style="height:24px; ">
<option value="nada">Please choose an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</div>
</div>`;
}
</script>

Drop-down menu that when you click on an option a file will be downloaded

I'm creating a website as a learning tool, this website has PHP code which consists of 3 drop-down menus, each of them is filled with 3 databases. And the previous one is filled dynamically depending on the previous choice.
What I want to do is when the user selects the last menu, download a file attached to that option. I don't know very well how to do this, I've been doing some research and it seems that my best asset is using javascript but I can't get it to work with my PHP code.
I think my best bet is to add another row in the database that contains the links and when the user clicks on an option it downloads according to that row.
<?php
//fetch_third_level_category.php
include('database_connection.php');
if(isset($_POST["selected"]))
{
$id = join("','", $_POST["selected"]);
$query = "
SELECT * FROM third_level_category
WHERE second_level_category_id IN ('".$id."')
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '<option value="'.$row["third_level_category_id"].'">'.$row["third_level_category_name"].'</option>';
}
echo $output;
}
?>
//index.php
//index.php
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" />
</head>
<body>
<br />
<div class="container">
<br /><br />
<div style="width: 500px; margin:0 auto">
<div class="form-group">
<select id="first_level" name="first_level[]" multiple class="form-control">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["first_level_category_id"].'">'.$row["first_level_category_name"].'</option>';
}
?>
</select>
</div>
<div class="form-group">
<select id="second_level" name="second_level[]" multiple class="form-control">
</select>
</div>
<div class="form-group">
<select id="third_level" name="third_level[]" multiple class="form-control">
</select>
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#first_level').multiselect({
nonSelectedText:'Selecciona el driver',
buttonWidth:'400px',
onChange:function(option, checked){
$('#second_level').html('');
$('#second_level').multiselect('rebuild');
$('#third_level').html('');
$('#third_level').multiselect('rebuild');
var selected = this.$select.val();
if(selected.length > 0)
{
$.ajax({
url:"fetch_second_level_category.php",
method:"POST",
data:{selected:selected},
success:function(data)
{
$('#second_level').html(data);
$('#second_level').multiselect('rebuild');
}
})
}
}
});
$('#second_level').multiselect({
nonSelectedText: 'Selecciona el modelo',
buttonWidth:'400px',
onChange:function(option, checked)
{
$('#third_level').html('');
$('#third_level').multiselect('rebuild');
var selected = this.$select.val();
if(selected.length > 0)
{
$.ajax({
url:"fetch_third_level_category.php",
method:"POST",//index.php
data:{selected:selected},
success:function(data)
{
$('#third_level').html(data);
$('#third_level').multiselect('rebuild');
}
});
}
}
});
$('#third_level').multiselect({
nonSelectedText: 'Seleccona la serie del modelo',
buttonWidth:'400px'
});
});
</script>
You have 2 ways, depending on do you want download to start as soon as user selects that option or when webform is submitted.
If you want to start download as soon as option is selected then you have to go with JavaScrip. You have to add event listener to those drop-downs (probably easier would be with jQuery) and when even happens somehow trigger file download.
Other opiton is to do nothing when option is selected, but to check selected option from form submissions handler (php scrip which is called when form is submitted) and from there to start download.
Or even some hybrid options are i.e. to submit form with JS when drop value changes...

JQUERY change div contents based on select options -- I'm lost

In the following code, I have two dropdowns, unit-type and unit-size. I have two , unit-price and row-total, that need to be updated, first on page load, then whenever one or both dropdowns are changed.
The problem is that I'm new to Javascript and Jquery and really don't know what I'm doing, and none of the examples I've tried following seems to work for me. I'm hoping someone here can point me to where my problem is and how to make it work?
<?php
session_start();
include '../include/search.php';
$dbserver = '#########';
$dbname = '########';
$dbuser = '########';
$dbpassword = '#########';
$category = $_GET['category'];
$db = mysqli_connect($dbserver, $dbuser, $dbpassword, $dbname);
if (mysqli_connect_errno()) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_select_db($db, $dbname);
$sql = "SELECT * FROM products WHERE category = '".$category."'";
$result = mysqli_query($db, $sql);
if (!$result) {
die ('Error: Could not select products'.mysqli_error($db));
}
function make_size_select($product) {
echo '<select name="unit_menu">';
$price_set = array(
'halfpint'=>$product['halfpint'],
'pint'=>$product['pint'],
'dk'=>$product['dk'],
'quart'=>$product['quart']);
$handles = array(
'halfpint'=>'Half Pint (8 oz)',
'pint'=>'Pint (16 oz)',
'dk'=>'Dutch Kettle (16 oz)',
'quart'=>'Quart (32 oz)');
$i = 0;
foreach ($price_set as $key=>$value) {
if ( $value > 0.00) {
$i++;
if ($i == 1) {
echo '<option value="'.$value.'" selected="selected">'.$handles[$key].'</option>';
} else {
echo '<option value="'.$value.'">'.$handles[$key].'</option>';
}
}
}
echo '</select>';
}
function category_select($product) {
$categories = array();
foreach ($product as $row) {
if (!in_array($row['category'], $categories)) {
array_push($row['category']);
}
}
echo '<select name="categories" onChange="loadNewCategory();">';
foreach ($categories as $category) {
echo '<option '.$category.'>'.ucfirst($category);
}
echo '</select>';
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Smoky Mountain Honey House</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="../css/style.css" rel="stylesheet" type="text/css" media="all" />
<link href="../css/custom.css" rel="stylesheet" type="text/css" media="all" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="../js/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="../js/menu.js"></script>
</head>
<body>
<!----start-header----->
<div class="header_img">
<img src="../images/header_img.jpg" alt="" />
<div class="wrap">
<div class="header">
<div class="logo">
<img src="../images/logo.png" alt="">
</div>
<div class="menu">
<nav class="clearfix">
<ul class="clearfix">
<li class="active">HOME</li>
<li>ABOUT</li>
<li>LOCATIONS</li>
<li>SHOP</li>
<li>CONTACT</li>
</ul>
Menu
</nav>
</div>
</div>
</div>
</div>
<!----End-header----->
<div class="wrap">
<div class="content">
<div class="category-header">
<h2><?php echo ucfirst($category); ?></h2>
<!-- <div class="product-search">
<p>
Search our inventory: <form name="search" action="../include/functions.php?method=search" method="post">
<input type="text" name="search_terms" />
<input type="submit" value="submit" />
</form>
</p>
</div> -->
</div>
<?php
while ( $product = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) {
// display product ?>
<div class="product_row">
<script>
var product = <?php echo json_encode($product); ?>
</script>
<form name="order_row_<?php echo $product['product_id']; ?>" action="#" method="post">
<div class="product_id">
<input type="hidden" name="product_id" value="<?php echo $product['product_id']; ?>">
<?php echo ucfirst($product['name']); ?>
</div>
<div class="type">
<select name="unit_type">
<option value="ind" selected>By the Jar</option>
<option value="case">By the Case</option>
</select>
</div>
<div class="unit">
<?php echo make_size_select($product); ?>
</div>
<div class="unit-price">
</div>
<div class="qty">
<input type="number" name="qty" min="0" maxlength="5" max="11" label="How many?" />
</div>
<div class="row-price"></div>
<div class="add_cell">
<button class="add-to-cart" onclick="addToCart();">Add To Cart</button>
</div>
</form>
</div>
<?php }; ?>
</div>
</div>
<div class="copy-right">
<p>© 2016 Smoky Mountain Honey House</p>
</div>
</div>
<!---End-footer---->
<script>
$( ".unit_type" ).change(function () {
var unitPrice = $(this).val();
if ( $(this).closest.(".unit_type") == "ind") {
unitPrice = unitPrice / 12.00;
}
$( this ).closest.( ".unit-price" ).text( unitPrice );
})
.change();
</script>
</body>
</html>
jQuery's closest is not finding things located in siblings (or parents' siblings). I would get the closest product row and find children elements from there.
There's also a dot after each closest. For example:
closest.(".unit-price");
should actually be:
closest(".unit-price");
The element you're trying to select (.unit-type) doesn't contain a class which you're trying to find, it contains a name instead. A dot (.) in jQuery represents a class, a hash symbol (#) represents an id.
<select name="unit_type">
should be:
<select name="unit_type" class="unit_type">
if you wanna be able so select it with:
$(".unit_type");
$(".unit-type").change(function() {
var productRow = $(this).closest(".product_row");
var price = 5; // get your price here
var unitPrice;
if ($(this).val() == "ind") { // $(this).val() contains the value of the selected option
unitPrice = price / 12.00;
} else {
unitPrice = price / 24.00;
}
productRow.find(".unit-price").text(unitPrice);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product_row">
<div class="type">
<select name="unit_type" class="unit-type">
<option value="ind" selected>By the Jar</option>
<option value="case">By the Case</option>
</select>
</div>
<div class="unit-price">
</div>
</div>

Dropdown that based on another dropdown, select option are from database

Sorry if it was discussed before, but all of them doesn't really work for me. I have 5 dropdowns they are Brand, Model, Color, Engine No. and Chassis No., My question is what should I do to make the dropdown of the model is based on the selected dropdown of Brand, for example If a user selects Honda well based on my posted image in my database, the BrandID of Honda is 1 so all of the model that has the BrandID = 1. The dropdown of the model shown are only that has a brandID =1. Then the dropdown of color is based on the dropdown of the model, so the same logic like I discussed earlier. Finally the Dropdown of Engine No. and Chasis No. is based on the dropdown of the color, also the same as the logic that I discussed.
Here's my code for the brand dropdown
<label for="bName" class="control-label col-xs-4"><p class="left">Brand</p></label>
<div class="col-xs-7">
<div class="req">
<?php
include_once "config.php";
$bsql="SELECT bName, brandID FROM brand order by bName";
$bstmt=$con->prepare($bsql);
$bstmt->execute();
$bstmt->bind_result($bName, $bid);
$bstmt->store_result();
echo "<select name='brandID' class='form-control'>
<option value=''></option>";
while ($bstmt->fetch()){
echo '<option value="'.$bid.'">'.$bName.'</option>';
}
echo '</select>';
?>
</div>
</div>
Heres the code for the dropdown of the model
<label for="model" class="control-label col-xs-4">
<p class="left">Model</p></label>
<div class="col-xs-7">
<div class="req">
<?php
include_once "config.php";
$msql="SELECT model, modID FROM model order by model";
$mstmt=$con->prepare($msql);
//$mstmt->bind_param('i', $bid);
$mstmt->execute();
$mstmt->bind_result($model, $mid);
$mstmt->store_result();
echo "<select name='mID' class='form-control'>
<option value=''></option>";
while ($mstmt->fetch()){
echo '<option value="'.$mid.'">'.$model.'</option>';
}
echo '</select>';
?>
</div>
</div>
Heres the code for color dropdown
<label for="model" class="control-label col-xs-4"><p class="left">Color</p></label>
<div class="col-xs-7">
<div class="req">
<?php
include_once "config.php";
$csql="SELECT distinct(color) FROM stock order by color";
$cstmt=$con->prepare($csql);
$cstmt->execute();
$cstmt->bind_result($color);
$cstmt->store_result();
echo "<select name='color' class='form-control'>
<option value=''></option>";
while ($cstmt->fetch()){
echo '<option value="'.$color.'">'.$color.'</option>';
}
echo '</select>';
?>
</div>
</div>
Heres the code for the dropdown Engine No.
<label for="engNum" class="control-label col-xs-4">
<p class="left">Engine No</p></label>
<div class="col-xs-7">
<div class="req">
<?php
include_once "config.php";
$esql="SELECT engNum FROM stock where status='Available' order by engNum";
$estmt=$con->prepare($esql);
$estmt->execute();
$estmt->bind_result($engNum);
$estmt->store_result();
echo "<select name='engNum' class='form-control'>
<option value=''></option>";
while ($estmt->fetch()){
echo '<option value="'.$engNum.'">'.$engNum.'</option>';
}
echo '</select>';
?>
</div>
</div>
Heres the code for the dropdown Chasis No.
<label for="chassisNum" class="control-label col-xs-4"><p class="left">Chassis No</p></label>
<div class="col-xs-7">
<div class="req">
<?php
include_once "config.php";
$nsql="SELECT chassisNum FROM stock where status='Available' order by chassisNum";
$nstmt=$con->prepare($nsql);
$nstmt->execute();
$nstmt->bind_result($chassisNum);
$nstmt->store_result();
echo "<select name='chassisNum' class='form-control'>
<option value=''></option>";
while ($nstmt->fetch()){
echo '<option value="'.$chassisNum.'">'.$chassisNum.'</option>';
}
echo '</select>';
?>
</div>
</div>
Heres the Image for my brand database
Heres the Image for my model database
Heres the Image for the color, chasis no. and engine no. database
Write an onchange event on select tag
for e.g. to change the Models based on brand selected you should write
<label for="bName" class="control-label col-xs-4"><p class="left">Brand</p></label>
<div class="col-xs-7">
<div class="req">
<?php
include_once "config.php";
$bsql="SELECT bName, brandID FROM brand order by bName";
$bstmt=$con->prepare($bsql);
$bstmt->execute();
$bstmt->bind_result($bName, $bid);
$bstmt->store_result();
echo "<select name='brandID' class='form-control' **onchange='getModels(this)'**>
<option value=''></option>";
while ($bstmt->fetch()){
echo '<option value="'.$bid.'">'.$bName.'</option>';
}
echo '</select>';
//The function getModels(this) will get called whenever user will change the value of the brand option.
Now define this method in your js file
function getModels(BrandObj)
{
brandValue=BrandObj.value; // Will give you the ID of brand which is selected.
// Make A ajax call to some php file which will return models based on brand ID & bind it to your Models Dropdown
$.ajax({
url: 'getModels.php',
type: 'GET', // Method Type
data: 'brandID=brandValue',// This parameter will be sent to getModels.php
success: function(**data**) {
//called when successful the data we have returned in getModels.php will be accessible in "data" variable
// Decode the response & bind it to your dropdownList
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
}
// IN your getModels.php file write following code
$BrandID=#$_GET['brandID'];
//Connect to database
// Write a sql to find models having brand_id=$BrandID
// Fetch rows & create array of Models & return it using
echo json_encode(*your_array_name*)
// END getModels.php
// You can find the detailed documentation of AJAX
http://api.jquery.com/jquery.ajax/

Categories

Resources