Deleting and element by using a php id inside javascript - javascript

I'm trying to do it so when a user checks a checkbox it gets the Email to a text field and when the user unchecks it it deletes the text field, here's the code that I've tried to use that's not working.
The php code:
<?php
$execItems = $conn->query("SELECT Nome,EmailGeral,Enviado FROM escolas");
while($infoItems = $execItems->fetch_array()){
echo "
<tr>
<td>".$infoItems['Nome']."</td>
<td>".$infoItems['EmailGeral']."</td>
<td><input type=\"checkbox\" id=\"{$infoItems['EmailGeral']}\"".($infoItems['Enviado']?' checked':' ')." onclick=\"emailNextWithAddress(this, '".$infoItems['EmailGeral']."');\"/>
</tr>
";
}
?>
And the javascript:
<script>
function emailNextWithAddress(chk,address) {
if(chk.checked === true){
var nextEmail, inside_where;
nextEmail = document.createElement('input');
nextEmail.value = address;
nextEmail.type = 'text';
nextEmail.name = 'email[]';
nextEmail.className = 'insemail';
nextEmail.style.display = 'inline-block';
inside_where = document.getElementById('addEmail');
inside_where.appendChild(nextEmail);
return false;
} else {
var nextEmail, inside_where;
nextEmail.value = address;
nextEmail.className = 'delemail';
inside_where = document.getElementById(<?php echo $infoItems['EmailGeral'] ?>);
inside_where.parentElement.removeChild(nextEmail);
return false;
}
}
</script>

You could add an id as the last parameter, and using it on your function :
<td><input type=\"checkbox\" id=\"{$infoItems['EmailGeral']}\"".($infoItems['Enviado']?' checked':' ')." onclick=\"emailNextWithAddress(this, '".$infoItems['EmailGeral']."', this.id);\"/></td>
<script>
function emailNextWithAddress(chk,address,id) {
if(chk.checked === true){
var nextEmail, inside_where;
nextEmail = document.createElement('input');
nextEmail.value = address;
nextEmail.type = 'text';
nextEmail.name = 'email[]';
nextEmail.className = 'insemail';
nextEmail.style.display = 'inline-block';
inside_where = document.getElementById('addEmail');
inside_where.appendChild(nextEmail);
return false;
} else {
var nextEmail, inside_where;
nextEmail.value = address;
nextEmail.className = 'delemail';
inside_where = document.getElementById(id);
inside_where.parentElement.removeChild(nextEmail);
return false;
}
}
</script>

at least you're missing some quotes around that id
pick whether double/single vs single/double quotes:
document.getElementById("<?php echo $infoItems['EmailGeral'] ?>")
document.getElementById('<?php echo $infoItems["EmailGeral"] ?>')

The snippet of php/html was missing a closing </td> tag after the checkbox.
The javascript function could, I believe, be simplified a little like this. I made an assumption here in that the new input element should be appended to the current table row - I could not determine what the element with id addEmail was or where it was. The below should append a new text field in the same cell as the checkbox, populate with the email address when checked and remove when the checkbox is unchecked.
<?php
$execItems = $conn->query("SELECT Nome,EmailGeral,Enviado FROM escolas");
while($infoItems = $execItems->fetch_array()){
$name=$infoItems['Nome'];
$email=$infoItems['EmailGeral'];
$checked=$infoItems['Enviado'] ? 'checked' : '';
echo "
<tr>
<td>$name</td>
<td>$email</td>
<td><input type='checkbox' id='{$email}' {$checked} onclick='emailNextWithAddress( this );' /></td>
</tr>";
}
?>
<script>
function emailNextWithAddress( chk ) {
try{
if( chk.checked === true ){
var nextEmail;
nextEmail = document.createElement('input');
nextEmail.value = chk.id;
nextEmail.type = 'text';
nextEmail.name = 'email[]';
nextEmail.className = 'insemail';
nextEmail.style.display = 'inline-block';
chk.parentNode.appendChild( nextEmail );
} else {
chk.parentNode.removeChild( chk.parentNode.querySelector('input[ name="email[]" ]') );
}
return false;
}catch( err ){
console.info( err.message )
}
}
</script>

Related

Javascript code produces errors when moved from inline to external file

I have a copy script built in to the page I am working on, and when the copy JS is inline, it works great, but as soon as I moved it external, it produces the following error:
copy.js:1 Uncaught TypeError: Cannot read property 'addEventListener' of null
I am unsure why because when inline there is no issues. Copy of the section code is:
<?php
$connect = mysqli_connect("localhost", "brandina_templat", "REMOVED", "brandina_templates");
$catresult = "SELECT * FROM categories";
$catquery = mysqli_query($connect,$catresult);
$catquery2 = mysqli_query($connect,$catresult);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Templates Sheet | Brandin Arsenault's</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/tabcontent.js"></script>
<link href="css/bootstrap.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<h1 align="center">Templates Sheet</h1>
<center><ul class="tabs">
<?php
if(!$catquery)
{
die('Invalid query: ' . mysql_error());
}
while($row = mysqli_fetch_array($catquery))
{
$number=$row['number'];
$tabname=$row['tabname'];
$catname=$row['catname'];
echo "<li class='tab-link' data-tab='$tabname'>$catname</li>";
}
?>
</ul>
<?php
if(!$catquery2)
{
die('Invalid query: ' . mysql_error());
}
while($row = mysqli_fetch_array($catquery2))
{
$number=$row['number'];
$tabname=$row['tabname'];
$catname=$row['catname'];
$result = "SELECT * FROM templates WHERE category=$number";
$query = mysqli_query($connect,$result);
echo "<div id='$tabname' class='tab-content'>
<table><center>";
$c = 0;
$n = 3;
if(!$query)
{
die('Invalid query: ' . mysql_error());
}
while($row = mysqli_fetch_array($query))
{
$id=$row['id'];
$longname=$row['longname'];
$shortname=$row['shortname'];
$text=$row['text'];
if($c % $n == 0 && $c != 0)
{
echo '</tr><tr>';
}
$c++;
echo "
<td>
<center><b>$longname</b></center><textarea id='$id' cols='25' rows='3'>$text</textarea><br /><button id='$shortname'>Copy</button>
</td>
<script>
var shortname = '$shortname';
</script>";
}
echo "</center></table></div>";
}
?>
<script src='js/copy.js'></script>
</center>
</div>
</body>
</html>
copy.js is:
document.getElementById(shortname).addEventListener('click', function() {
copyToClipboardMsg(document.getElementById('$id'), 'msg');
});
function copyToClipboardMsg(elem, msgElem) {
var succeed = copyToClipboard(elem);
var msg;
if (!succeed) {
msg = 'Copy not supported or blocked. Press Ctrl+c to copy.'
} else {
msg = 'Text copied to the clipboard.'
}
if (typeof msgElem === 'string') {
msgElem = document.getElementById(msgElem);
}
msgElem.innerHTML = msg;
setTimeout(function() {
msgElem.innerHTML = '';
}, 2000);
}
function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = '_hiddenCopyText_';
var isInput = elem.tagName === 'INPUT' || elem.tagName === 'TEXTAREA';
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement('textarea');
target.style.position = 'absolute';
target.style.left = '-9999px';
target.style.top = '0';
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// copy the selection
var succeed;
try {
succeed = document.execCommand('copy');
} catch(e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === 'function') {
currentFocus.focus();
}
if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = '';
}
return succeed;
}
Thanks in advance!
The variable $shortname exists when you use the inline code, but when you move your code to external it doesn't exists anymore.
You can use:
<script>
var shortname = '$shortname';
</script>
<script src='js/copy.js'></script>
And in your copy.js file you should use:
document.getElementById(shortname).addEventListener('click', function() {
Otherwise - the javascript code is looking for element that it's id is $shortname, and you don't really have one with the value.

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

POST Json to PHP get VAR

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.

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.

Categories