make a chain combobox using JCombo - javascript

i would like to seek some help with my code because my current code wont work...i found this plugin code from this site click here...as of now all are not working even the first combobox filtration...can anyone help me get this code work please.
index.php:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.js"></script>
</head>
<body>
<form>
<select name="position" id="position"></select>
<select name="salary_grade" id="salary_grade"></select>
<select name="salary" id="salary"></select>
</form>
<script type="text/javascript">
$( document ).ready(function() {
$("#position").jCombo({ url: "getPosition.php", selected_value : '150' } );
$("#salary_grade").jCombo({ url: "getSalary_Grade.php?sgid=",
parent: "#position",
selected_value: '178'
});
$("#salary").jCombo({ url: "getSalary.php?salaryid=",
parent: "#salary_grade",
selected_value: '630'
});
});
</script>
</body>
</html>
getPosition.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("test");
// Execute Query in the right order
//(value,text)
$query = "SELECT tcode, position FROM positions";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
// convert into JSON format and print
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
echo $data;
?>
getSalary_Grade.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("test");
// Get parameters from Array
$sgid = !empty($_GET['tcode'])
?intval($_GET['tcode']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT id,salary FROM salary_grades WHERE salary_grades.id = '$sgid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
$cache->finish($response);
?>
getSalary.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("test");
// Get parameters from Array
$salaryid = !empty($_GET['id'])
?intval($_GET['id']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT id,salary FROM salarys WHERE salarys.id = '$salaryid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
$cache->finish($response);
?>

This should work:
getSalary.php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$salaryid = !empty($_GET['salaryid'])
?intval($_GET['salaryid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT id,salary FROM salarys WHERE id = $salaryid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['id'], "value" => htmlentities($row['salary']));
$items[] = $option;
}
}
getSalary_Grades.php
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$sgid = !empty($_GET['sgid'])
?intval($_GET['sgid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT id, salary FROM salary_grades WHERE id = $sgid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['id'], "value" => htmlentities($row['salary']));
$items[] = $option;
}
}

Related

how to insert both value and content of dropdown select into database?

i want to insert both value and content of dropdown select into a database table. i can insert the value with no problem but i have no idea how to insert the content. i've been searching similar questions and probably it can be done by adding javascript. but i haven't learned about that yet so i have no clue how to use it.
<form action="hitung.php" method="POST" id="formid">
<?php
$query = "SELECT nama FROM alternatif";
$result = mysqli_query($conn, $query);
for ($i=0; $i < $row = mysqli_fetch_array($result) ; $i++) {
?>
<tr>
<th><?php echo $row['nama'] ?></th>
<?php
$select = mysqli_query($conn, "SELECT * FROM kriteria");
$count = mysqli_num_rows($select);
for ($j=0; $j < $count ; $j++) {
?>
<td>
<select class="btn-secondary" name="subkrt[<?php echo $i ?>][<?php echo $j ?>]" required>
<option value="" style="display:none;" required>-Pilih-</option>
<?php
$query = mysqli_query($conn, "SELECT pv_alternatif.pv_subkriteria, subkriteria.nama FROM pv_alternatif INNER JOIN subkriteria ON pv_alternatif.id_alternatif = subkriteria.id WHERE id_kriteria=$j+1");
while ($a = mysqli_fetch_array($query)) {
?>
<option value="<?php echo $a['pv_subkriteria']; ?>"><?php echo $a['nama']; ?></option>
<?php
}
?>
</select>
</td>
<?php
}
}
?>
</tr>
</form>
so both value and content are fetched from two different tables of my database. and hitung.php is code to insert into database.
include 'koneksi.php';
include 'fungsi.php';
$jmlsub = array();
$qwery = mysqli_query($conn, "SELECT nilai FROM pv_kriteria");
while ($row = mysqli_fetch_array($qwery)){
$rows[] = $row['nilai'];
$jmlsub[] = 0;
}
$query = "SELECT nama FROM alternatif";
$result = mysqli_query($conn, $query);
$a = mysqli_query($conn, "SELECT * FROM nilai_alt");
for ($i=0; $i < $row = mysqli_fetch_array($result) ; $i++) {?>
<?php
$select = mysqli_query($conn, "SELECT * FROM kriteria");
$count = mysqli_num_rows($select);
for ($j=0; $j < $count ; $j++) {
if(isset($_POST['subkrt'][$i][$j])){
$matriks[$i][$j] = $_POST['subkrt'][$i][$j] * $rows[$j];
$value = $matriks[$i][$j];
$jmlsub[$i] += $value;
$id_alternatif = getIDAlternatif($i);
$id_kriteria = getKriteriaID($j);
if (mysqli_num_rows($a)==0) {
$b = "INSERT INTO nilai_alt VALUES('',$id_alternatif,$id_kriteria,$value)";
} else {
$b = "UPDATE nilai_alt SET nilai_alternatif=$value WHERE id_alternatif = $id_alternatif AND id_kriteria = $id_kriteria";
}
$rsult = mysqli_query($conn,$b);
if (!$rsult) {
echo "Gagal memasukkan / mengupdate nilai alternatif";
exit();
}
}
}
}
$jmlAlternatif = getJumlahSubKriteria();
for ($i=0; $i < ($jmlAlternatif); $i++) {
$id_alternatif = getIDAlternatif($i);
$query = "INSERT INTO ranking VALUES ($id_alternatif,$jmlsub[$i]) ON DUPLICATE KEY UPDATE nilai=$jmlsub[$i]";
$result = mysqli_query($conn,$query);
if (!$result) {
echo "Gagal mengupdate ranking";
exit();
}
}
header('Location: hasil_subkrt.php');
?>
tables:
Any help will be greatly appreciated. Thanks.
As you said you "can insert the value with no problem", so it is simple to pass all the value and content to the selected option value as a string
using json_encode(...), then in hitung.php you just convert it back to array or object using json_decode(...)
If you have a array, example:
$a = array('pv_subkriteria' => 'the value', 'nama' => 'the name');
Then just
<option value='<?php echo htmlentities(json_encode($a)); ?>'><?php echo $a['nama']; ?></option>
Then in your case in hitung.php,
...
$a = json_decode(html_entity_decode($_POST['subkrt'][$i][$j]), true);
...
More info, generally your code has nested loop and query database in loop, you need to think more about better query way to reduce number of loops to increase performance.
Edited and added an example using some php functions that might help you:
<?php
$a = array('pv_subkriteria' => 'the value', 'nama' => 'the name');
$str = htmlentities(json_encode($a));
$a2 = json_decode(html_entity_decode($str), true);
print_r($a2);
?>

bad request error in angularjs

var successCallback=function(response) {
if(response.success) {
$log.log(response.data);
alert('fetched courses and percentages successfully');
} else {
}
};
var errorCallback = function(response) {
console.log(response.success);
alert( "failure message: " + JSON.stringify(response));
};
var data = { "mis": 111608059};
// data = JSON.stringify(data),
$http.post('api/stu_course_%.php', data).then(successCallback, errorCallback);
The above code gives the following error:
failure message: {"data":"\n\n400 Bad Request\n\nBad RequestYour browser sent a request that this server could not understand.Apache/2.4.18 (Ubuntu) Server at localhost Port 80\n\n","status":400,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"api/stu_course_%.php","data":{"mis":111608059},"headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"}},"statusText":"Bad Request","xhrStatus":"complete"}
Server-side code in php:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'config.php';
function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
$json_request = file_get_contents('php://input');
$request = json_decode($json_request, true);
print_r( $request);
$MIS = $request["mis"];
//$MIS = 111608059;
$data = array();
$result1 = mysqli_query($conn, "select enrolled.course_id, course_code, course_name from enrolled LEFT OUTER JOIN courses ON enrolled.course_id=courses.course_id where MIS='$MIS'");
if (mysqli_num_rows($result1) > 0) {
while($row = mysqli_fetch_assoc($result1)){
$query2 = "select count(course_id) as count from attendance_item group by course_id, MIS having (MIS='$MIS' and course_id='$row[course_id]') ";
$query3 = "select count(course_id) as total_count from lecture group by course_id having course_id='$row[course_id]'";
$result2 = mysqli_query($conn, $query2);
$result3 = mysqli_query($conn, $query3);
$count = mysqli_fetch_assoc($result2);
// print_r ($count);
$total_count = mysqli_fetch_assoc($result3);
// print_r ($total_count);
$percent = $count["count"]/$total_count["total_count"] *100;
// echo $percent;
$data = array_push_assoc($data, $row["course_name"], $percent);
}
// print_r($data);
$success = 1;
json_encode($data);
}
else{
$success = 0;
}
$response = array();
$response["success"] = $success;
$response["data"] = $data;
echo json_encode($response);
?>

ajax error, the data is burried

this is my code
main.js
var save_method, table;
//Menerapkan plugin datatables
$(function(){
table = $('.table').DataTable({
"processing" : true,
"ajax" : {
"url" : "ajax/ajax_user.php?action=table_data",
"type" : "POST"
}
});
});
ajax_user.php
<?php
include "../config/database.php";
include "../library/view.php";
if ($_GET['action'] == "table_data") {
$query = mysqli_query($mysqli, "SELECT p.*, v.nama_provinsi, k.nama_kota, j.nama_tagihan FROM pelanggan P
INNER JOIN provinsi v ON p.id_provinsi = v.id_provinsi
INNER JOIN kota k ON p.id_kota = k.id_kota
INNER JOIN jenis_tagihan j ON p.id_jenis_tagihan = j.id_jenis_tagihan
ORDER BY p.id DESC");
$data = array();
$no = 1;
while($p = mysqli_fetch_assoc($query)) {
$row = array();
$row[] = $no;
$row = $p['nama_masjid'];
$row = $p['nama_pengurus'];
$row = $p['id_pelanggan'];
$row = $p['tagihan'];
$row = $p['nama_provinsi'];
$row = $p['nama_kota'];
$row = $p['nama_tagihan'];
$data[] = $row;
$no++;
}
$output = array("data" => $data);
echo json_encode($output);
}
?>
and this is my error
The last data in the array appears but the previous data disappears what's wrong ?
try this :
$data = [];
$i=0;
while($p = mysqli_fetch_assoc($query)) {
$data[$i]['nama_masjid'] = $p['nama_masjid'];
$data[$i]['nama_pengurus']= $p['nama_pengurus'];
$i++;
}
echo json_encode($data);

How to get a php array index and use it in javascript

I have a PHP script that returns a latitude and longitude from the database.
Then I have a Javascript loop that loops according to the number of rows the PHP query returns and populate my data object with the logitude and latitude at a given index. The challenge now is - how do I get the index without hard coding it?
PHP
$DBhost = 'localhost';
$DBuser = 'root';
$DBpass = '';
$DBname = 'symptoms';
$con = mysqli_connect($DBhost, $DBuser, $DBpass) or die(mysql_error());
mysqli_select_db($con, $DBname);
$query = mysqli_query($con, 'SELECT latitude,longitude FROM markers') or die(mysql_error());
$longArr = array();
$latArr = array();
$count = 0;
while ($row = mysqli_fetch_array($query)) {
$lat = $row['latitude'];
$lon = $row['longitude'];
$latArr[$count] = $lat;
$longArr[$count] = $lon;
++$count;
}
JavaScript
var latArr = [];
var longArr = [];
var markersD = [];
var num = <?php echo $count ?>;
for (var i = 0; i < num; i++) {
var data = {
lat: '<?php echo $latArr[1]?>',
lon: '<?php echo $longArr[1]?>'
}
console.log(data);
}
You have to create json object via php
while($row = mysqli_fetch_array($query))
{
$json[] = array('lat' => $row['latitude'], 'lon' => $row['longitude']);
}
$json_string = json_encode($json);
=== JS ===
var data = <?php echo json_string; ?>;
console.log(data);
You can put all your coords in one array
$coords = array();
while($row = mysqli_fetch_array($query))
{
$coords[] = array(
'latitude' => $row['latitude'],
'longitude' => $row['longitude'],
)
}
and pass it to the js as a JSON object
var data = <?php echo json_encode($coords) ?>;
console.log(data);
All data you need should be available in the javascript

XML not parsing in jQuery

When I try to parse my PHP-generated XML file using the jQuery Feeds plugin, it doesn't do what it's supposed to - loop through the template below and output the XML <title> tag in the place of <!=title!>. Instead, it returns just one instance of the template with nothing in place of <!=title!>.
Nothing is returned in the Chrome JavaScript console.
Strangely, I have a similar PHP-generated XML file that works just fine.
Here's the jQuery I'm using:
$('.feed').feeds({
feeds: {
feed1: 'http://www.comfyshoulderrest.com/scrape.php?id=1' // this one doesn't work
},
//max: 3,
loadingTemplate: '<h1 class="feeds-loader">Loading items...</h1>',
entryTemplate: '<div class="item"><div class="image"><img src="images/tie.jpg" style="width: 100%;"></div>' +
'<div class="text"><ul class="list-inline">' +
'<li><span class="price text-warning"><strong>£7.00</strong></span> <span class="text-muted"><strike>£14.00</strike></span></li>' +
'<li class="text-muted"><strong>Topman</strong></li></ul>' +
'<!=title!>' +
'</div></div>'
});
Here's the code that generates the XML file:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country) {
header("Content-Type: application/xml; charset=UTF-8");
$xml = new SimpleXMLElement('<rss/>');
$xml->addAttribute("version", "2.0");
$channel = $xml->addChild("channel");
$channel->addChild("product_url", $product_url);
$channel->addChild("shop_name", $shop_name);
$channel->addChild("photo_url", $photo_url);
$channel->addChild("was_price", $was_price);
$channel->addChild("now_price", $now_price);
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html)) {
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i]
);
$item = $channel->addChild("item");
$item->addChild("product_url", $result['product_url']);
$item->addChild("shop_name", $result['shop_name']);
$item->addChild("photo_url", $result['photo_url']);
}
//print_r($result);
}
else
{
echo "this is empty";
}
echo $xml->asXML();
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result)) {
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location - $row['was_price_location'];
$now_price_location - $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
}
mysqli_close($con);
?>

Categories

Resources