Move existing div into another div with Javascript - javascript

After selecting an option from first dropdown list then another dropdown list appear according to selected option. When an option is selected from the second one then the selected one's value is sent to input element that is at the top of the page as hidden. It also calls function "bolumGonder" which submits form that includes input element to same page with GET method. Then according to GET variable retrieve some data from database.
PHP
<?php
session_start();
if (isset($_GET['bolumtani']) && !empty($_GET['bolumtani'])) {
include_once 'alinabilendersler.php';
}
?>
HTML
<script>
function bolumGonder() {
var seciliBolum = $(".insaat").val();
if ( seciliBolum.length > 0 ) {
$("#bolumtani").val(seciliBolum);
document.bolumtaniform.submit();
}
}
</script>
<form name="bolumtaniform" action="program.php" method="GET">
<input name="bolumtani" id="bolumtani" type="text" style="display:none" />
</form>
<div id="orta_div">
<select class="fakulte_sec" onclick = "bolumAc()">
<option selected>Fakülte</option>
<option value="insaat">İnşaat Fakültesi</option>
<option value="mimarlik">Mimarlık Fakültesi</option>
<option>Makina Fakültesi</option>
<option>Uçak ve Uzay Bilimleri Fakültesi</option>
</select>
<select class="insaat" style="display:none" onchange="bolumGonder()">
<option value="" selected>Bölüm</option>
<option value="ins">İnşaat Mühendisliği %30</option>
<option value="inse">İnşaat Mühendisliği %100</option>
<option>Çevre Mühendisliği %30</option>
<option>Çevre Mühendisliği %100</option>
</select>
<select class="mimarlik" style="display:none">
<option>Mimarlık %30</option>
<option>İnşaat Mühendisliği %100</option>
<option>Çevre Mühendisliği %30</option>
<option>Çevre Mühendisliği %100</option>
</select>
<div class="uygun_dersler_ana_div" style="width:100%; color: white; height: 1500px;position: absolute ;overflow: hidden"><?php if (isset($_GET['bolumtani']) && !empty($_GET['bolumtani'])) {$sonuc = bolum($_GET['bolumtani']);} else {}?></div>
</div>
Gettin data from MySQL
<?php
##Database Bağlantısı##
$host = 'host';
$user = 'username';
$pass = 'password';
$db = 'databasename';
$baglan = mysql_connect($host, $user, $pass);
mysql_select_db($db);
mysql_query("SET NAMES 'utf8' ");
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET COLLATION_CONNECTION = 'utf8_turkish_ci' ");
## Her Ders İçin Ayrı Tablo Oluştur ##
function bolum($degisken) {
# Ders Kodlarını Al # # Gets Class Name From Another Website, Asign them into an array ##
$ch = curl_init("someURL");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$cl = curl_exec($ch);
$dom = new DOMDocument();
#$dom->loadHTML($cl);
$xpath = new DOMXpath($dom);
$derskodlari = $xpath->query("//option[position() >1]");
$todbderskodlariarr = array();
foreach ($derskodlari as $derskodu) {
$todbderskodlariarr[] = $derskodu;
}
$todbderskodu = array();
foreach ($todbderskodlariarr as $todbderskoduarr) {
$todbderskodu[] = $todbderskoduarr->nodeValue;
}
## This is just an exception. ##
$todbderskodu[81] = "MODD";
for ($a = 0; $a < count($todbderskodu); $a++) {
#$todbderskodu[$a] = mysql_query("SELECt crnler, derskodu, gun, bina, dersadi FROM $todbderskodu[$a] WHERE dersialabilen LIKE '%" . $bolum . "%'");
}
$a = 0;
while ($a < count($todbderskodu)) {
while ($row = mysql_fetch_array($todbderskodu[$a], MYSQL_NUM)) {
$class = substr($row[1], 0, 3);
echo '<div class="' . $class . '" id="' . $row[0] . '">' . $row[4] . $row[0] . ' |' . $row[2] . '</div>';
}
echo '<br>';
$a = $a + 1;
}
}
?>
Upto now everything works perfect. Script creates divs that have class AKM,ALM,ATA,UCK.. etc. I want to put all divs that have same class into classname_main_div. How can i do that?

use the class of the looped divs and append to the other div like:
$(".looped-divs").appendTo(".container-div");
Hope that helps
cheers!
PD: remember to scape the GET variables to avoid SQL injection

Related

How to populate one drop-down based on the selection of another drop-down from database in php and javascript/jquery

I want to populate the drop-down based on the selection of other. Here's how the database looks like. Tried the following code but it isn't giving me any results.
make
id maker
2 Apple
3 Samsung
model
id make_id model
1 3 Galaxy S III
2 3 Galaxy S IV
3 2 iphone 5s
4 2 iphone 5
Queries.php
class Queries{
public static function getMaker() {
$conn = DB::databaseConnection();
$sql = "SELECT * from make" ;
$stmt = $conn->prepare($sql);
if ($stmt->execute()) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
} else {
return null;
}
}
public static function getModel($make_id) {
$conn = DB::databaseConnection();
$sql = "SELECT * from model WHERE make_id = :make_id" ;
$stmt = $conn->prepare($sql);
$stmt->bindParam(':make_id', $make_id);
if ($stmt->execute()) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
} else {
return null;
}
}
}
mobilereg.php
$make_id = filter_input(INPUT_GET, "make_id");
require_once './pages/header.php';
require_once './functions/queries.php';
$maker = Queries::getMaker();
$model = Queries::getModel($make_id);
<div class="control-group form-group">
<div class="controls">
<label>Make</label>
<select class="form-control"name="maker"id="maker"onchange="get_models();">
<option selected disabled></option>
<?php
for ($i = 0; $i < count($maker); $i++) {
echo '<option value="' . $maker[$i]['id'] . '">' . $maker[$i]['maker'] . '</option>';
}
?>
</select>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Model</label>
<select class="form-control" name="get_models" id="get_models">
<option selected disabled></option>
</select>
</div>
</div>
main.js
function get_models(){
var maker = $('#maker').val();
var dataString = "maker="+maker;
$.ajax({
type: "POST",
url: "functions.php",
data: dataString,
success: function(html)
{
$("#get_models").html(html);
}
});
}
functions.php
require_once './queries.php';
$make_id = filter_input(INPUT_POST, "make_id");
if($_POST){
$maker = $_POST['maker'];
if($maker!=''){
echo Queries::getModel($make_id);
echo "<select name='get_models'>";
echo "<option value='" . $row['make_id'] . "'>" . $row['model'] . "
</option>";
echo '</select>';
}
}
So maker and model are the two drop-downs. The options in the model should result on the basis of the selection we make in the maker drop-down.
I've referred the code from one the questions here but it doesn't work at all. The problem is in the functions.php I guess. I'm very new to php and js, any help would be appreciated. TIA

Logically select categories and subcategories (php,joomla,javascript,ajax)

Hello I have installed jbusinessdirectory component for joomla, and I have module named mod_jbusinessdirectory (this is a search module for business listing) in tmpl/default.php file I have select code: (see below)
<?php if($params->get('showCategories')){ ?>
<div class="select">
<div class="categoryic"></div>
<select name="categorySearch" class="select-styled" id="categories">
<option value="0">category</option>
<?php foreach($categories as $category){?>
<option value="<?php echo $category->id?>" <?php echo $session->get('categorySearch')==$category->id && $preserve?" selected ":"" ?> ><?php echo $category->name?></option>
<?php if(!empty($category->subcategories)){?>
<?php foreach($category->subcategories as $subCat){?>
<option value="<?php echo $subCat->id?>" <?php echo $session->get('categorySearch')==$subCat->id && $preserve?" selected ":"" ?> >-- <?php echo $subCat->name?></option>
<?php }?>
<?php }?>
<?php }?>
</select>
</div>
<?php }?>
From this code I get categories and subcategories like this:
Main category 1
subcategory 1 subcategory 2 subcategory 3
Main category 2
subcategory 1 subcategory 2 subcategory 3
screenshot here: categories and sub categories screenshot
In helper.php I have functions that get categories and subcategories from database
static function getMainCategories(){
$db = JFactory::getDBO();
$query = ' SELECT * FROM #__jbusinessdirectory_categories where parent_id=1 and published=1 order by name';
$db->setQuery($query);
return $db->loadObjectList();
}
static function getSubCategories(){
$db = JFactory::getDBO();
$query = ' SELECT c.* FROM #__jbusinessdirectory_categories c
inner join #__jbusinessdirectory_categories cc on c.parent_id = cc.id where c.parent_id!=1 and cc.parent_id = 1 and c.published=1
order by c.name';
$db->setQuery($query,0,1000);
$result = $db->loadObjectList();
return $result;
}
And lastly in modjbusinesdirectory.php file I have the PHP like this:
if($params->get('showCategories')){
$categories = modJBusinessDirectoryHelper::getMainCategories();
if($params->get('showSubCategories')){
$subCategories = modJBusinessDirectoryHelper::getSubCategories();
foreach($categories as $category){
foreach($subCategories as $subCat){
if($category->id == $subCat->parent_id){
if(!isset($category->subcategories)){
$category->subcategories = array();
}
$category->subcategories[] = $subCat;
}
}
}
}
}
categories and subcategories table structure screenshot
here
My question is: How do I make Two select queries instead of one. Where in the first query I get the main categories and in the second query I get the subcategories (eg: if I choose from the first query the main category books and in the second query I choose children it has to show only books with the subcategory children books).
You can use below query for get categories.
function all_cat($id='',$child_of_child='parent')
{
$CI =& get_instance();
if($id="")
{
$query = $CI->db->get_where("__jbusinessdirectory_categories",array('parent_id'=>1));
}
else
{
$query = $CI->db->get_where("__jbusinessdirectory_categories",array('parent_id'=>$id));
}
//echo $CI->db->last_query()."<br>";
$op = '';
if($query->num_rows() > 0)
{
$res = $query->result();
//pr($res);
if($child_of_child == 'child')
{
$op .= '<ul class="sub_cat mrg-top-5" style="display:none;" id="'.$id.'">';
}
else
{
$op .= '<ul class="sub_cat " id="'.$id.'">';
}
foreach($res as $r)
{
$op .= '<li>'.ucwords($r->name).'
</li>';
$op .= all_cat($r->id,$child_of_child='child');
}
return $op .= '</ul>';
}
else
{
return $op;
}
}
It appears that the code already does what you want. You want 2 queries and there are 2. But, I think the result of these 2 queries combines into 1 result and you want to keep it spit into 2 results.
You will have to add new category functions that accept category ID parameters.
<?php
static function getCategoryById($id){
$id = intval( $id );
$db = JFactory::getDBO();
$query = '
SELECT *
FROM #__jbusinessdirectory_categories
WHERE
published=1
AND id= '.$id;
$db->setQuery($query);
return $db->loadObject();
}
static function getChildCategoryList($id){
$id = intval($id);
$db = JFactory::getDBO();
$query = '
SELECT c.*
FROM #__jbusinessdirectory_categories c
INNER JOIN #__jbusinessdirectory_categories cc
ON c.parent_id = cc.id
WHERE c.parent_id!=1
AND cc.id = '.$id.'
AND c.published=1
ORDER BY c.name';
$db->setQuery($query,0,1000);
$result = $db->loadObjectList();
return $result;
}
I am not familiar with Joomla code that retrieves parameters but you can find the ID if you POST it when someone selects a main category.
<?php
if($params->get('showCategories')){
$categoryId = (int) $params->get('mainCategory');
$category = modJBusinessDirectoryHelper::getCategoriesById($categoryId);
$subCategories = modJBusinessDirectoryHelper::getChildCategoryList($categoryId);
}
}

how to create a for loop with a drop down box

Hi I am trying to create a set of drop down boxes that will use an array of data from the values that you pick and then runs through a loop to post them to the screen at the moment the data that i want to use will just be local but i want to edit this later so that it will loop through the data from my database and post that to the screen. i have looked at other questions on this subject and just wondering how i would change it for my code i have looked at this link questions on stack overflow that I have looked at i have just got a couple questions that im wondering if anybody has seen this before or if they have seen any examples i have also looked at for loops and i understand the concept
my questions to you are:
1) how would I post the values from my drop down boxes into a php array
2) how would I then check the values against and array of data and then choose which are correct and post them to the screen.
3)Would I need to use a second language like javascript or can it be done just in php
My drop down box code is
<div id="Content">
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="%">any...</option>
</select>
<br /><br />
Choose a principle:<br />
<select id="principle">
<option value="%">any...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
<!-- end of the Options -->
below is the select.class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowCategory()
{
$sql = "SELECT * FROM subject";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['subject_id'] . '">' . $row['description'] . '</option>';
}
return $category;
}
public function ShowType()
{
$sql = "SELECT * FROM section WHERE subject_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['section_id'] . '">' . $row['description'] . '</option>';
}
return $type;
}
public function ShowPrinciple()
{
$sql = "SELECT * FROM principle WHERE section_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$principle = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$principle .= '<option value="' . $row['principle_id'] . '">' . $row['description'] . '</option>';
}
return $principle;
}
}
$opt = new SelectList();
?>
1) how would I post the values from my drop down boxes into a php array
In the form tag add method="POST". Reference in PHP with $_POST array. Make sure to validate and escape the data before writing to your DB.
2) how would I then check the values against and array of data and then choose which are correct and post them to the screen.
If you don't have millions of categories, you are better off sending them all as a JSON array and using Javascript. Something like:
<script>
var categories = <?php echo json_encode($opt->ShowCategory()); ?>;
</script>
json_encode may require some options to be set, depening on your character set. More info here: http://php.net/manual/en/function.json-encode.php
Making a new request each time someone changes a dropdown box will drive them crazy, I know I hate that. If you have used jQuery before, this is very easy. This isn't that difficult without it.
3)Would I need to use a second language like javascript or can it be done just in php
For the sake of your users, use Javascript.
code for showCategory()
...
$categories = new array();
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$categories[$row['subject_id']] = $row['description'];
}
$validCategories = $this->getValidCategories() // get the valid categories
foreach($categories as $index=>$cat){
// only choose the categories that are valid
if(array_search($cat,$validCategories) !== FALSE)
$category.= '<option value="'.$index.'">'.$cat.'</option>';
}
return $category;

How to pass the value dropdownlist without using form

I have two sets of option value. I created another dropdown that if I choose r it echo <option value $row['nego'] > or n echo <option value $row['rfq'] >. What I want is to pass the value of dropdown without using form. If it possible to do that?
<script>
function showUser(str) {
var $txtHint = $('#txtHint');
if (str == "") {
$txtHint.html('');
return;
}
$txtHint.load('rfq_list.php?q=' + str) // or rfq_list.php?q
}
</script>
</head>
<body onload=showUser(str="ALL")>
<select>
<option value="r">rfq</option>
<option value="n">nego</option>
</select>
<?php
if (isset($_POST['n'])) {
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT nego FROM purchase_order GROUP BY shop ORDER BY nego");
$option = '';
while($row = $result->fetch_assoc()) {
$option .= '<option value = "'.$row['nego'].'">'.$row['nego'].'</option>';
}
}
?>
<?php
if (isset($_POST['r'])) {
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT rfq FROM purchase_order WHERE rfq LIKE '13-___' OR rfq LIKE '1_-___' OR rfq LIKE '2_-___' GROUP BY rfq ORDER BY rfq");
$option = '';
while($row = $result->fetch_assoc()) {
$option .= '<option value = "'.$row['rfq'].'">'.$row['rfq'].'</option>';
}
}
?>
<select name="users" onchange="showUser(this.value)" style="overflow:scroll;width:100px;">
<option value="ALL" selected='ALL'>ALL</option>
<?php echo $option; ?>
</select>
<div id="txtHint"></div>

How can I properly decode a javascript encoded URI in PHP?

I've created a dynamic dropdown using JS/PHP/MySQL but it seems I'm having some problems with UTF8 decoding in my PHP. The script is going to be used to make a small application that helps my customers find a product that meets their criteria. We sell panel meters that can accept different ranges of input and many are denoted with a +/- or a value (example: a meter can expect to process a voltage +/- 10V around a specified voltage.) Everything is starting to work great in my script except when some characters are parsed through (+, / , ±, ½, etc.) My database originally used ± to denote plus or minus but I then switched to +/- (three characters) in hopes that it would fix the special character problem but it didn't...
Using console.log I've figured out that my JS is encoding the special characters correctly but once it gets to my PHP it doesn't decode properly.
Everything along the way is set to UTF8
So now I still need to figure out why some things are not parsing right.
You can view a live version of the script at http://new.foxmeter.com/find.php.
This is the important part of my frontend
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
$("#type").change(function() {
var tval = document.getElementById('type').value;
$("#range").load(encodeURI("findbackend.php?type=" + tval));
});
$("#range").change(function() {
rval = document.getElementById('range').value;
$("#power").load(encodeURI("findbackend.php?range=" + rval));
console.log(encodeURIComponent(document.getElementById('range').value));
});
$("#power").change(function() {
//var rval = document.getElementById('range').value;
psval = document.getElementById('power').value;
$("#setpoint").load(encodeURI("findbackend.php?range=" + rval + "&power=" + psval));
});
$("#setpoint").change(function() {
//var rval = document.getElementById('range').value;
//var psval = document.getElementById('power').value;
stval = document.getElementById('setpoint').value;
$("#output").load(encodeURI("findbackend.php?range=" + rval + "&power=" + psval + "&setpoint=" + stval));
});
});
</script>
</head>
<body>
<!-- Google Analytics Script -->
<?php include_once("scripts/analyticstracking.php") ?>
<div class="wrapper"> <!-- Sticky Footer Wrapper -->
<div id="panorama"></div>
<div id="header">
<?php include("include/header/banner.php") ?>
<?php include("include/header/nav.php") ?>
<?php include("include/header/quicksearch.php") ?>
</div>
<div id="content">
<div id="findoptions">
<select id="type" class="finddrops">
<option selected value="base">Please Select</option>
<option value="DC Voltage">DC Voltage</option>
<option value="DC Current">DC Current</option>
<option value="AC Voltage">AC Voltage</option>
<option value="AC Current">AC Current</option>
<option value="Strainguage">Strainguage</option>
</select>
<br>
<select id="range" class="finddrops">
<option>Please choose from above</option>
</select>
<br>
<select id="power" class="finddrops">
<option>Please choose from above</option>
</select>
<br>
<select id="setpoint" class="finddrops">
<option>Please choose from above</option>
</select>
<br>
<select id="output" class="finddrops">
<option>Please choose from above</option>
</select>
<br>
<select id="blarg" class="finddrops">
<option>Please choose from above</option>
</select>
</div>
<div id="findresults" class="finddrops">
</div>
</div>
</div>
And this is my PHP running on the backend:
<?php
//\\ MODULAR DEPENDANT DROPDOWNS \\//
//creates DB connection
$dbHost = 'host';
$dbUser = 'user';
$dbPass = 'password';
$dbDatabase = 'database';
$con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error());
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
//prevents injections
//any order
$type = mysql_real_escape_string(urldecode($_GET['type']));
isset($_GET['range'])?$range = mysql_real_escape_string(urldecode($_GET['range'])):"";
isset($_GET['power'])?$power = mysql_real_escape_string(urldecode($_GET['power'])):"";
isset($_GET['setpoint'])?$setpoint = mysql_real_escape_string(urldecode($_GET['setpoint'])):"";
//forms the query depending on what data is recieved through GET
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' AND stp='$setpoint' ORDER BY model";
} elseif (isset($_GET['power'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' ORDER BY model";
} elseif (isset($_GET['range'])) {
$query = "SELECT DISTINCT pso FROM meters WHERE sio='$range' ORDER BY model";
} else {
$query = "SELECT DISTINCT sio FROM meters WHERE sit LIKE '%$type%' ORDER BY model";
}
//creates a result array from query results
$result = mysql_query($query);
//outputs dropdown options dependent on what GET variables are set
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'stp'} . "'>" . $row{'stp'} . "</option>";
}
} elseif (isset($_GET['power'])) {
echo "<option>Choose Setpoint Options</option>";
while ($row = mysql_fetch_array($result)) {
$row{'stp'} = ucfirst($row{'stp'}); //capitalizes the first letter; necessary?
echo "<option value='" . $row{'stp'} . "'>" . $row{'stp'} . "</option>";
}
} elseif (isset($_GET['range'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'pso'} . "'>" . $row{'pso'} . "</option>";
}
} else {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'sio'} . "'>" . $row{'sio'} . "</option>";
}
}
//Thanks to Chris Coyier for the wonderful examples on CSS-Tricks
//A Web Application by Zach Klemp
?>
Again, you can view the script here.
Choose DC Voltage in the first dropdown and then a +/- option in the second the see where the problem begins. When you choose Straingauge in the first dropdown and then click '30 mV with 10 V DC excitation' it parses through fine. (And as an aside another problem I have is that choosing the first result without clicking another first doesn't trigger the .change)
Thanks for any and all help getting this to work! I've been trying to figure this out for a bit now and haven't come up with a solution.
Try this in your PHP file :
Replace any echo XXXX; with utf8_decode(XXXX)
It should make it works
$string = ';http%3A%2F%2Fwww.google.com%2F%3Fq%3Dtesting%2Burldecode';
echo urldecode($string); // http://www.google.com/?q=testing+urldecode
For further reading, see the official PHP documentation on urldecode here.

Categories