POST Json to PHP get VAR - javascript

i have a form like this:
<?php
include '../db/baza.php';
?>
<?php include 'vrh.php' ?>
<div id="stranica">
<div id="stranicaOkvir">
<form action="dodaj_sliku_obrada.php" method="POST" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Dodaj sliku</legend>
<?php $upit = "SELECT kategorija_ID, kategorija_naziv FROM kategorije ORDER BY kategorija_ID ASC";
$ispis = mysql_query($upit) or die(mysql_error());
$blok_ispis = mysql_fetch_assoc($ispis);
$ukupno = mysql_num_rows($ispis); ?>
<p><strong>Obavezno odaberite kategoriju kojoj slika pripada</strong></p>
<p> <select name="kategorija" id="kategorija">
<?php do { ?>
<option value="<?php echo $blok_ispis['kategorija_ID']; ?>"> <?php echo $blok_ispis['kategorija_naziv']; ?></option>
<?php } while ($blok_ispis = mysql_fetch_assoc($ispis)); ?>
<?php mysql_free_result($ispis);?>
</select>
</p>
<input type="file" id="file" name="file[]" required multiple>
<input type="submit" id="submit" name="submit" value="Dodaj sliku">
<div class="progresbar">
<span class="progresbar-puni" id="pb"><span class="progresbar-puni-tekst" id="pt"></span></span>
</div>
<div id="uploads" class="uploads">
Uploaded file links will apper here.
<script src="js/dodaj_Sliku.js"></script>
<script>
document.getElementById('submit').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'dodaj_sliku_obrada.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
uspjesno_Dodano = document.createElement('div'),
neuspjelo_Dodavanje = document.createElement('div'),
anchor,
span,
x;
if(data.neuspjelo_Dodavanje.length){
neuspjelo_Dodavanje.innerHTML = '<p>Nazalost, sljedece nije dodano: </p>';
}
uploads.innerText = '';
uploads.textContent = '';
for( x = 0; x < data.uspjesno_Dodano.length; x = x + 1){
anchor = document.createElement('a');
anchor.href = '../slike/galerija/' + data.uspjesno_Dodano[x].file;
anchor.innerText = data.uspjesno_Dodano[x].name;
anchor.textContent = data.uspjesno_Dodano[x].name;
anchor.target = '_blank';
uspjesno_Dodano.appendChild(anchor);
}
for( x = 0; x < data.neuspjelo_Dodavanje.length; x = x + 1){
span = document.createElement('span');
span.innerText = data.neuspjelo_Dodavanje[x].name;
span.textContent = data.neuspjelo_Dodavanje[x].name;
neuspjelo_Dodavanje.appendChild(span);
}
uploads.appendChild(uspjesno_Dodano);
uploads.appendChild(neuspjelo_Dodavanje);
},
error: function(){
console.log('Ne radi!');
}
});
});
</script>
<script>
</script>
</div>
</fieldset>
</form>
</div>
</div>
<?php include 'dno.php' ?>
The .js looks like this
var app = app || {};
(function(o){
"use strict";
//Privatne metode
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uspjesno_Dodano;
xmlhttp.addEventListener('readystatechange', function(){
if(this.readyState === 4){
if(this.status === 200){
uspjesno_Dodano = JSON.parse(this.response);
if(typeof o.options.finished === 'function'){
o.options.finished(uspjesno_Dodano);
}
} else {
if(typeof o.options.error === 'function'){
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(event){
var percent;
if(event.lengthComputable === true){
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i = 0; i < source.length; i = i + 1){
data.append('file[]', source[i]);
}
data.append('ajax', true);
data.append('kategorija', o.options.kategorija);
return data;
};
setProgress = function(value){
if(o.options.progressBar !== undefined){
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined){
o.options.progressText.innerText = value ? value + '%' : '';
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options){
o.options = options;
if(o.options.files !== undefined){
ajax(getFormData(o.options.files.files));
}
}
}(app));
On the process.php part i want to listen the option value from select
"<select name="kategorija" id="kategorija">"
on the process.php when i
<?php
$kategorija = $_POST['kategorija'];
echo echo $kategorija;
?>
i alwasy get a 0 value, so what i am doing wrong? The file[] processing is working fine, but can't get it to work with a addtional variable.

You don't need to echo echo $kategorija; It should be echo $kategorija; If this causes an issue, which it might, try var_dump($kategorija) to view the contents of the variable.
Also, you're including your js throughout the page, this should be refactored and included properly in the head. The php should not be in the form of the document, it should be contained outside and included like you are doing with '../db/baza.php'; Finally, look into using PDO to connect to your db.

Related

Refresh part of page when user navigated back to it

In my shop page, for each product I have cart quantities that the user can change without add to cart button (it's with display none and activated by js).
my problem is that if a user changed item quantity in single product page and navigated back into shop page it show the wrong quantity from cache.
Right now i'm reloadin the whole page using this code:
jQuery( document ).ready(function( $ ) {
$(document).ready(function () {
if(performance.navigation.type == 2 || performance.navigation.type == 0){
var isquanpage = document.getElementsByClassName('store-quantity');
if (isquanpage.length > 0) {
console.log(isquanpage);
$("#a2cloader").show();
location.reload(true);
document.addEventListener('DOMContentLoaded', function() {
$("#a2cloader").hide();
}, false);
}
}
});
});
I want to refresh just the quantities and not the whole page:
<div class="quantity-div" >
<i class="fas fa-plus sumsum-quantity-b" value="+" onclick="store_quantity_b('+', this.parentNode.querySelector('input[type=number]').id);"></i>
<input class="sumsum-quantity store-quantity" form="<?php echo $product->id; ?>" inputmode="decimal" style="padding:0;border-radius:5px;" type="number" min="0" value="<?php echo $cartquan ?>"
name="<?php echo $varid; ?>" onclick="this.select()" id="quantity-<?php echo $varid ?>" data-cartquan="<?php echo $cartquan ?>" data-varititle="<?php echo get_the_title( $attribute_value['variation_id']); ?>">
<i class="fas fa-minus sumsum-quantity-b" value="-" onclick="store_quantity_b('-', this.parentNode.querySelector('input[type=number]').id);"></i>
</div>
And what i tried to do is this:
quanfield = document.getElementsByClassName("store-quantity");
cartquantities =<?php echo json_encode(WC()->cart->get_cart_item_quantities();); ?>;
console.log(cartquantities);
But it gets the cached version of the cart and not the updated one.
OK, i found a solution, I'm using hook on woocommerce add to cart fragments like this:
// cart quantities
add_filter( 'woocommerce_add_to_cart_fragments', woocommerce_cartquant_fragment' );
function woocommerce_cartquant_fragment( $fragments ) {
global $woocommerce;
ob_start();
?>
<p id="cartquantities" style="display:none"><?php echo json_encode(WC()->cart->get_cart_item_quantities()); ?></p>
<?php
$fragments['p#cartquantities'] = ob_get_clean();
return $fragments;
}
and then using this script:
//refresh page from history
jQuery( document ).ready(function( $ ) {
$(document).ready(function () {
if(performance.navigation.type == 2 || performance.navigation.type == 0){
let quanfield, quanname,cartquantities,store,obj;
let findname =[];
$("#a2cloader").show();
timeout = setTimeout(function() {
cartquantities = document.getElementById("cartquantities").innerText;
cartquantities = cartquantities.replace("{","");
cartquantities = cartquantities.replace("}","");
cartquantities = cartquantities.replace(/['"]+/g, '');
cartquantities = cartquantities.split(",");
for (i = 0; i < cartquantities.length; i++) {
cartquantities[i] = cartquantities[i].split(":");
findname[i] = cartquantities[i][0];
}
//console.log(findname);
quanfield = document.getElementsByClassName("store-quantity");
//console.log(quanfield.length);
for (i = 0; i < quanfield.length; i++) {
quanname = quanfield[i].name;
obj = findname.findIndex(o => o==quanname);
//console.log(obj);
if (obj !=-1){
quanfield[i].value=cartquantities[obj][1];
quanfield[i].setAttribute("data-cartquan", cartquantities[obj][1]);
}else{
quanfield[i].value=0;
quanfield[i].setAttribute("data-cartquan", 0);
}
$("#a2cloader").hide();
}
}, 1500 );
}
});
});
Is there a possibility to make javascript wait for the fragments instead of setting timeout?
SOLVED! used interval to check when fragments are updated
<script>
//refresh page from history
jQuery( document ).ready(function( $ ) {
$(document).ready(function () {
if(performance.navigation.type == 2 || performance.navigation.type == 0){
let quanfield, quanname,cartquantities,store,obj,timer;
let findname =[];
$("#a2cloader").show();
//var t=0;
timer = setInterval(checkfrags, 5);
function checkfrags(){
//t+=5;
if(document.getElementById("cartquantities").innerText=="null") {
//console.log(t);
}else{
cartquantities = document.getElementById("cartquantities").innerText;
cartquantities = cartquantities.replace("{","");
cartquantities = cartquantities.replace("}","");
cartquantities = cartquantities.replace(/['"]+/g, '');
cartquantities = cartquantities.split(",");
for (i = 0; i < cartquantities.length; i++) {
cartquantities[i] = cartquantities[i].split(":");
findname[i] = cartquantities[i][0];
}
//console.log(findname);
quanfield = document.getElementsByClassName("store-quantity");
//console.log(quanfield.length);
for (i = 0; i < quanfield.length; i++) {
quanname = quanfield[i].name;
obj = findname.findIndex(o => o==quanname);
//console.log(obj);
if (obj !=-1){
quanfield[i].value=cartquantities[obj][1];
quanfield[i].setAttribute("data-cartquan", cartquantities[obj][1]);
}else{
quanfield[i].value=0;
quanfield[i].setAttribute("data-cartquan", 0);
}
$("#a2cloader").hide();
}
//console.log(document.getElementById("cartquantities").innerText+"done "+t);
document.getElementById("cartquantities").innerText="null";
clearInterval(timer);
}
}
}
});
});
</script>
<p id="cartquantities" style="display:none">null</p>

multiple textbox values storing in same column in php

I an using Javascript when click add button to show multiple text box. but i don't how to store these text box values in database table single column. here i attached my form input coding and javascript for add number of textbox. after submit my form it stores somthing like Array into my table.
<?php
if(isset($_POST['submit']))
{
Include 'db.php';
//$digits = 5;
//$staff_id=STAF.rand(pow(10, $digits-1), pow(10, $digits)-1);
$fromlocation = $_POST['fromlocation'];
$fromlatitude = $_POST['fromlatitude'];
$fromlongitude = $_POST['fromlongitude'];
$tolocation = $_POST['tolocation'];
$tolatitude = $_POST['tolatitude'];
$tolongitude = $_POST['tolongitude'];
// $routes = $_POST['routes'];
//$routesmore = $_POST['routes_more'];
$date=date('Y-m-d H:i:s');
$status=1;
//$usertype=1;
$count = $_POST['count'];
for($i = 0 ; $i < $count ; $i++)
{
//$count++;
$routesmore = $_POST['routes_more'];
$routesmore2 = explode('.', $routesmore[0]);
}
$query = mysqli_query($connect,"INSERT INTO `motorpark-db`.`tbl_route` (`from_location`, `from_latitude`, `from_longitude`, `to_location`, `to_latitude`, `to_longitude`, `route1`, `status`, `created_date`) VALUES ('$fromlocation', '$fromlatitude', '$fromlongitude', '$tolocation', '$tolatitude', '$tolongitude', '$routesmore2', '$status', '$date');");
if($query)
{
header('location:create_route.php#managepart');
}
else
{
header('location:create_staff.php');
}
}
?>
my input box:
<div class="col-lg-8" id="img_upload">
<!-- <input type="text" id="file0" name="routes" style="background:none;width:185px;"> -->
<div id="divTxt"></div>
<p><a onClick="addproductimageFormField(); return false;" style="cursor:pointer;width:100px;" id="add_img_btn" class="btn btn-primary">Add Route</a></p>
<input type="hidden" id="aid" value="1">
<input type="hidden" id="count" name="count" value="0">
My Javascript:
<script type="text/javascript">
function addproductimageFormField()
{
var id = document.getElementById("aid").value;
var count_id = document.getElementById("count").value;
if(count_id < 2)
{
document.getElementById('count').value = parseInt(count_id)+1;
var count_id_new = document.getElementById("count").value;
jQuery.noConflict()
jQuery("#divTxt").append("<div id='row" + count_id + "' style='width:100%'><fieldset class='gllpLatlonPicker'><label for='text- input'>Stop</label><span style='color:red;'> *</span><input type='text' class='gllpSearchField' name='routes_more"+count_id+"' id='file"+count_id_new+"' /></fieldset> &nbsp<a href='#' onClick='removeFormField(\"#row" + count_id + "\"); return false;' style='color:#F60;' >Remove</a></div>");
jQuery('#row' + id).highlightFade({speed:1000 });
id = (id - 1) + 2;
document.getElementById("aid").value = id;
}
}
function removeFormField(id)
{
//alert(id);
var count_id = document.getElementById("count").value;
document.getElementById('count').value = parseInt(count_id)-1;
jQuery(id).remove();
}
</script>
Change In JS - Append routes_more[] in jQuery("#divTxt").append in place of routes_more'+count+'.
<script type="text/javascript">
function addproductimageFormField()
{
var id = document.getElementById("aid").value;
var count_id = document.getElementById("count").value;
if(count_id < 2)
{
document.getElementById('count').value = parseInt(count_id)+1;
var count_id_new = document.getElementById("count").value;
jQuery.noConflict()
jQuery("#divTxt").append("<div id='row" + count_id + "' style='width:100%'><fieldset class='gllpLatlonPicker'><label for='text- input'>Stop</label><span style='color:red;'> *</span><input type='text' class='gllpSearchField' name='routes_more[]' id='file"+count_id_new+"' /></fieldset> &nbsp<a href='#' onClick='removeFormField(\"#row" + count_id + "\"); return false;' style='color:#F60;' >Remove</a></div>");
jQuery('#row' + id).highlightFade({speed:1000 });
id = (id - 1) + 2;
document.getElementById("aid").value = id;
}
}
function removeFormField(id)
{
//alert(id);
var count_id = document.getElementById("count").value;
document.getElementById('count').value = parseInt(count_id)-1;
jQuery(id).remove();
}
</script>
Change in PHP Code - Find total count of routes_more textbox. And do accordingly. (No Need of checking how much count was there in your html code.)
<?php
if(isset($_POST['submit']))
{
include 'db.php';
//$digits = 5;
//$staff_id=STAF.rand(pow(10, $digits-1), pow(10, $digits)-1);
$fromlocation = $_POST['fromlocation'];
$fromlatitude = $_POST['fromlatitude'];
$fromlongitude = $_POST['fromlongitude'];
$tolocation = $_POST['tolocation'];
$tolatitude = $_POST['tolatitude'];
$tolongitude = $_POST['tolongitude'];
// $routes = $_POST['routes'];
//$routesmore = $_POST['routes_more'];
$date=date('Y-m-d H:i:s');
$status=1;
//$usertype=1;
//For Routes More
$totalRoutesCount = sizeof($_POST['routes_more']);
$totalRoutes="";
for($i=0;$i<$totalRoutesCount;$i++)
{
$totalRoutes = $totalRoutes.$routesmore[$i].",";
}
$totalRoutes = rtrim($totalRoutes, ',');
$query = mysqli_query($connect,"INSERT INTO `motorpark-db`.`tbl_route` (`from_location`, `from_latitude`, `from_longitude`, `to_location`, `to_latitude`, `to_longitude`, `route1`, `status`, `created_date`) VALUES ('$fromlocation', '$fromlatitude', '$fromlongitude', '$tolocation', '$tolatitude', '$tolongitude', '$totalRoutes', '$status', '$date');");
if($query)
{
header('location:create_route.php#managepart');
}
else
{
header('location:create_staff.php');
}
}
?>
HTML :
<input type="text"
id="file0" name="routes[]"
style="background:none;width:185px;">
PHP:
INSERT Query:
'routes'(BD column) = serialize( $post['routes'] );
Display Time:
unserialize the column routes and print with foreach loop

How to push data from database and see vote count after each data?

What I'm trying to do is to allow students answer questions and see each vote after each question and then the teacher can push the next question. The votes will then be entered into the database which I can use to produce a chart. I currently have the student answering questions but I'm having problem on stopping the next question from coming so the poll vote can show and how to show the vote before the next question comes.
This gets the questions from the database:
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&radio="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Your answer was submitted"+ p.responseText);
var url = 'quiz.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
On a different php file:
require_once 'core/init.php';
$arrCount = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$output = "";
$answers = "";
$q = "";
$connection = mysqli_connect('localhost', 'root', '', 'alsp');
$sql = mysqli_query($connection,"SELECT id FROM questions");
$numQuestions = mysqli_num_rows($sql);
if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
$currQuestion = "1";
}else{
$arrCount = count($_SESSION['answer_array']);
}
if($arrCount > $numQuestions){
unset($_SESSION['answer_array']);
header("location: start-quiz.php");
exit();
}
if($arrCount >= $numQuestions){
echo 'finished|<p>There are no more questions. Please enter your username and submit</p>
<form action="userAnswers.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<button class="btn btn-action" type="submit" value="finish">Submit</button>
</form>';
exit();
}
$singleSQL = mysqli_query($connection,"SELECT * FROM questions WHERE id='$question' LIMIT 1");
while($row = mysqli_fetch_array($singleSQL)){
$id = $row['id'];
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysqli_query($connection,"SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysqli_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()"class="btn btn-action">Submit</button></span>';
echo $output;
}
}
I'm guessing rather than have a submit button that takes you to the next page, after clicking on a radio button, the vote should show and then the teacher can push the next question. That's were the main issue is.

Is it possible to passing data in same PHP file?

I have a button (someone created it and I need to edit) which is saved to $elisting in employee.php. The button will go to javascript function named edit(). $elisting code are below:
$elisting ="";
$queryf = "select employee.id as myid,jobtitle,info,locid,deptid,gender,dob,emid,employee$cid.name,username,dept,datejoin,location.name as loc from employee
left join location on location$cid.id = employee.locid
inner join department on department.id = employee.deptid order by username
";
$resultf = pg_query($queryf);
$numrows = pg_numrows($resultf);
while ($rowf = pg_fetch_array($resultf)) {
$ct=$ct+1;
$myid = $rowf[myid];
$uname = $rowf[username];
$loc1 = $rowf[loc];
$dept = $rowf[dept];
$date = $rowf[datejoin];
$name = $rowf[name];
$emid = $rowf[emid];
$dob = $rowf[dob];
$gender = $rowf[gender];
$job = $rowf[jobtitle];
$info = $rowf[info];
$datejoin = $rowf[datejoin];
$locid = $rowf[locid];
$deptid = $rowf[deptid];
$newbal = $rowf[newbal];
$templatelist = "";
$tempcn = 0;
$querytemp = "select tid,ltype from leaveatemplate$cid where username='$uname' order by tid desc";
$resulttemp = pg_query($querytemp);
while ($rowtemp = pg_fetch_array($resulttemp)) {
$tempcn = $tempcn +1;
$tid = $rowtemp[tid];
$ltype = $rowtemp[ltype];
if($tempcn=="1")
$templatelist = "$ltype|$tid";
else
$templatelist = $templatelist.","."$ltype|$tid";
}
$elisting=$elisting."<tr><td align=\"center\">$uname</td><td align=\"center\">$loc1</td><td align=\"center\">$dept</td>
<td align=\"center\">$date</td>
<td align=\"center\"><a><button class=\"btn btn-mini\"data-toggle=\"modal\"href=\"#long\"
onClick=\"javascript:edit('$name','$uname','$emid','$dob','$gender','$job','$info','$datejoin','$locid','$deptid','$myid','$templatelist');\"><i class=\"icon-pencil\"></i></a>
Here are javascript edit() code:
function edit(a,b,c,d,e,f,g,h,i,j,k,l){
document.getElementById("frm").id.value=k;
document.getElementById("frm").name.value=a;
document.getElementById("frm").username.value=b;
document.getElementById("frm").emid.value=c;
document.getElementById("frm").dob.value=d;
setCheckedValue(document.forms['frm'].elements['gender'],e);
document.getElementById("frm").job.value=f;
document.getElementById("frm").info.value=g;
document.getElementById("frm").datejoin.value=h;
document.getElementById('locid').value=i;
document.getElementById('deptid').value=m;
var params = b;
window.location.href="http://192.168.1.5/eleave/employee.php?lapplicant=" + params;
var myTemp = l;
var mySplitResult = myTemp.split(",");
for(i = 0; i < mySplitResult.length; i++){
cval = mySplitResult[i];
myval = cval.split("|");
val1 = myval[0];
val2 = myval[1];
document.getElementById('temp'+val1).value= val2;
}
Since I failed to try many ways to get b in edit(), so I need to find the way to get $uname in $elisting and send it to $llisting in the same PHP file (employee.php) which the code are below:
$llisting ="";
$ct=0;
//leave code
$ccompassionate = "3";
$cemergency = "4";
$cmaternity = "5";
$cmedical = "6";
$cannual = "2";
//leave value
$compassionate = 2;
$emergency = 5;
$maternity = 60;
$medical = 20;
$lapplicant = $_POST['lapplicant'];
$querye = "select leavetype.id, leavetype.ltype, leaves.leave from leavetype,leaves where username='".$_SESSION["username"]."'";
$resulte = pg_query($querye);
while ($rowe = pg_fetch_array($resulte)) {
$ct=$ct+1;
$lid = $rowe[id];
$ltype = $rowe[ltype];
$leave = $rowe[leave];
if ($lid == $ccompassionate) {
$compassionate_query = pg_query("select ltotal from leave where lapplicant='".$lapplicant."' and ltype='".$ccompassionate."'");
if (count($compassionate_query) > 0) {
foreach ($compassionate_query as $data) {
$total_compassionate = $total_compassionate + $data['total'];
$value = $compassionate - $total_compassionate;
}
} else {
$value = $compassionate;
}
$llisting=$llisting."<tr><td align=\"center\">$ct</td><td>$ltype</td><td><input type='text' value='$lapplicant'></td><td align=\"center\">";
$llisting=$llisting."<select name=\"temp$lid\" id=\"temp$lid\" class=\"span12\"><option value=\"0\"> - </option> $tlisting</select>";
$llisting=$llisting."</td></tr>\n";
Anyone have an idea to get $uname in $elisting and send to $llisting?
And also, how can '$name','$uname','$emid','$dob','$gender','$job','$info','$datejoin','$locid','$deptid','$myid','$templatelist' in $elisting change to a,b,c,d,e,f,g,h,i,j,k,l in edit(), I'm new in Javascript so I don't understand how can it change?
Thank you for help..
this is the code where href="#long" called:
<div id="long" class="modal hide fade" tabindex="-1" data-replace="true" data-width="760">
<div class="modal-header"><h3>Employee Profile</h3></div>
<div class="modal-body">
<form class="form-horizontal" method="Post" name="frm" id="frm">
Code to call html page:
if($msg!="") $alert= "<div class=\"alert\"><i class=\"icon-info-sign\"></i> $msg</div><p> </p>";
$source2 = file_get_contents('http://'.$_SESSION["url"].'/cgi-bin/vo/'.$_SESSION["sessid"].'.interface.designer.vo?file=eleave/employee.htm');
$html2 = str_replace("[templateurl]",$templateurl,$source2);
$html2 = str_replace("[alert]",$alert ,$html2);
$html2 = str_replace("[elisting]",$elisting ,$html2);
$html2 = str_replace("[ulisting]",$ulisting ,$html2);
$html2 = str_replace("[locationlisting]",$locationlisting ,$html2);
$html2 = str_replace("[deptlisting]",$deptlisting ,$html2);
$html2 = str_replace("[llisting]",$llisting ,$html2);
$html2 = str_replace("[wfid]","sid=$sid" ,$html2);
echo $html2;
Please try the basic first, I have no problem with this one.
In JS:
<script>
function TestTriggered(name){
alert("the function triggered!");
alert("My name is: " + name);
}
</script>
On the HTML part
<input type="button" name="myButton" onClick="javascript:TestTriggered('John');" value="Please click"/>
Please try this first and see how thing works.

Toggle to open/close tabbed navigation

I am very new to jQuery/Javascript and have been trying to have a tabbed navigation menu closed on page load then open if clicked by the user. So far I haven't had any joy with editing the following file
function amshopby_start(){
$$('.block-layered-nav .form-button').each(function (e){
e.observe('click', amshopby_price_click_callback);
});
$$('.block-layered-nav .input-text').each(function (e){
e.observe('focus', amshopby_price_focus_callback);
e.observe('keypress', amshopby_price_click_callback);
});
$$('a.amshopby-more', 'a.amshopby-less').each(function (a){
a.observe('click', amshopby_toggle);
});
$$('span.amshopby-plusminus').each(function (span){
span.observe('click', amshopby_category_show);
});
$$('.block-layered-nav dt').each(function (dt){
dt.observe('click', amshopby_filter_show);
});
$$('.block-layered-nav dt img').each(function (img){
img.observe('mouseover', amshopby_tooltip_show);
img.observe('mouseout', amshopby_tooltip_hide);
});
$$('.amshopby-slider-param').each(function (item) {
param = item.value.split(',');
amshopby_slider(param[0], param[1], param[2], param[3], param[4], param[5], param[6]);
});
}
function amshopby_price_click_callback(evt) {
if (evt && evt.type == 'keypress' && 13 != evt.keyCode)
return;
var prefix = 'amshopby-price';
// from slider
if (typeof(evt) == 'string'){
prefix = evt;
}
else {
var el = Event.findElement(evt, 'input');
if (!Object.isElement(el)){
el = Event.findElement(evt, 'button');
}
prefix = el.name;
}
var a = prefix + '-from';
var b = prefix + '-to';
var numFrom = amshopby_price_format($(a).value);
var numTo = amshopby_price_format($(b).value);
if ((numFrom < 0.01 && numTo < 0.01) || numFrom < 0 || numTo < 0) {
return;
}
var url = $(prefix +'-url').value.gsub(a, numFrom).gsub(b, numTo);
amshopby_set_location(url);
}
function amshopby_price_focus_callback(evt){
var el = Event.findElement(evt, 'input');
if (isNaN(parseFloat(el.value))){
el.value = '';
}
}
function amshopby_price_format(num){
num = parseFloat(num);
if (isNaN(num))
num = 0;
return Math.round(num);
}
function amshopby_slider(width, from, to, max_value, prefix, min_value, ratePP) {
width = parseFloat(width);
from = parseFloat(from);
to = parseFloat(to);
max_value = parseFloat(max_value);
min_value = parseFloat(min_value);
var slider = $(prefix);
// var allowedVals = new Array(11);
// for (var i=0; i<allowedVals.length; ++i){
// allowedVals[i] = Math.round(i * to /10);
// }
return new Control.Slider(slider.select('.handle'), slider, {
range: $R(0, width),
sliderValue: [from, to],
restricted: true,
//values: allowedVals,
onChange: function (values){
this.onSlide(values);
amshopby_price_click_callback(prefix);
},
onSlide: function(values) {
var fromValue = Math.round(min_value + ratePP * values[0]);
var toValue = Math.round(min_value + ratePP * values[1]);
/*
* Change current selection style
*/
if ($(prefix + '-slider-bar')) {
var barWidth = values[1] - values[0] - 1;
if (values[1] == values[0]) {
barWidth = 0;
}
$(prefix + '-slider-bar').setStyle({
width : barWidth + 'px',
left : values[0] + 'px'
});
}
if ($(prefix+'-from')) {
$(prefix+'-from').value = fromValue;
$(prefix+'-to').value = toValue;
}
if ($(prefix + '-from-slider')) {
$(prefix + '-from-slider').update(fromValue);
$(prefix + '-to-slider').update(toValue);
}
}
});
}
function amshopby_toggle(evt){
var attr = Event.findElement(evt, 'a').id.substr(14);
$$('.amshopby-attr-' + attr).invoke('toggle');
$('amshopby-more-' + attr, 'amshopby-less-' + attr).invoke('toggle');
Event.stop(evt);
return false;
}
function amshopby_category_show(evt){
var span = Event.findElement(evt, 'span');
var id = span.id.substr(16);
$$('.amshopby-cat-parentid-' + id).invoke('toggle');
span.toggleClassName('minus');
Event.stop(evt);
return false;
}
function amshopby_filter_show(evt){
var dt = Event.findElement(evt, 'dt');
dt.next('dd').down('ol').toggle();
dt.toggleClassName('amshopby-collapsed');
Event.stop(evt);
return true;
}
function amshopby_tooltip_show(evt){
var img = Event.findElement(evt, 'img');
var txt = img.alt;
var tooltip = $(img.id + '-tooltip');
if (!tooltip) {
tooltip = document.createElement('div');
tooltip.className = 'amshopby-tooltip';
tooltip.id = img.id + '-tooltip';
tooltip.innerHTML = img.alt;
document.body.appendChild(tooltip);
}
var offset = Element.cumulativeOffset(img);
tooltip.style.top = offset[1] + 'px';
tooltip.style.left = (offset[0] + 30) + 'px';
tooltip.show();
}
function amshopby_tooltip_hide(evt){
var img = Event.findElement(evt, 'img');
var tooltip = $(img.id + '-tooltip');
if (tooltip) {
tooltip.hide();
}
}
function amshopby_set_location(url){
if (typeof amshopby_working != 'undefined'){
return amshopby_ajax_request(url);
}
else {
return setLocation(url);
}
}
document.observe("dom:loaded", function() { amshopby_start(); });
The element that I am trying to manipulate is contained in this file
<?php if($this->canShowBlock()): ?>
<div class="block block-layered-nav">
<div class="block-title">
<strong><span><?php echo $this->__('Shop By') ?></span></strong>
</div>
<?php echo $this->getStateHtml() ?>
<div class="block-content">
<?php if($this->canShowOptions()): ?>
<!-- <p class="block-subtitle">--><?php //echo $this->__('Shopping Options') ?><!--</p>-->
<ul id="narrow-by-list">
<li>
<?php $_filters = $this->getFilters() ?>
<?php foreach ($_filters as $_filter): ?>
<?php if($_filter->getItemsCount()): ?>
<div class="opt-row">
<dl class="opt-row">
<dt><?php echo $this->__($_filter->getName()) ?></dt>
<dd><?php echo $_filter->getHtml() ?></dd>
</dl>
</div>
<?php endif; ?>
<?php endforeach; ?>
</li>
</ul>
<script type="text/javascript">decorateDataList('narrow-by-list')</script>
<?php endif; ?>
<?php if ($this->getLayer()->getState()->getFilters()): ?>
<div class="actions"><?php echo $this->__('Clear All') ?></div>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
When the page loads I woul like to have the tabbed navigation menus closed but toggable to open by the user... Can anyone assist please?
From the admin panel, you can make any of your filters closed by default:-
Catalog > Improved Navigation > Filters
Select the relevant filter and set 'Collapsed' to 'Yes'.

Categories