Is it possible to passing data in same PHP file? - javascript

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.

Related

Why does php code not recognize a database update?

I have some php and html code and a small bit of JavaScript. Its a like system. Click the like button or dislike button and when you exit/leave the page the JavaScript and ajax runs a php file to update the database with the changes.(+1 to likes or +1 to dislikes or -1 to dislikes etc.) There is one problem. I click like/dislike and then i leave/ refresh page and the likes have not changed in value. If i dont click anything, which means im not updating the database and i refresh/leave a second time the likes are updated on the screen to what they should be. The database gets updated when its suppose to, its the code that dosnt use the new value for whatever reason. Here's my code:
<?php
session_start();
error_reporting(0);
$GOTID = $_GET['id'];
$GOTtitle = $_GET['title'];
include_once "mysql_connect.php";
include_once "like.php";
//include_once "dislike.php";
$email ='';
$log = null;
$log1 = null;
if(isset($_SESSION["ID"])){
$log1 = $_SESSION["ID"];
}else{
$log1=null;
}
if(isset($_SESSION["EMAIL"])){
$log = $_SESSION["EMAIL"];
$email = $_SESSION["EMAIL"];
// echo $email;
}else{
$log=null;
}
$_SESSION["EMAIL"] = $log;
$title = "";
$text="";
$tags = "";
$views = "";
$likes = "";
$dislikes = "";
$id = "";
$userid = "";
$date = "";
$thumbnail = "";
$imageext = "";
$texttype = "";
$data = mysql_query("SELECT * FROM videos WHERE id=$GOTID");
while ($row = mysql_fetch_array($data)) {
$title = $row[0];
$descrip = $row[1];
$id = $row[2];
$userid = $row[3];
$date = $row[4];
$views = $row[5];
$likes = $row[6];
$dislikes = $row[7];
$thumbnail = $row[8];
$imagext = $row[10];
$videourl = $row[11];
}
if($likes != '0' || $dislikes !='0'){
$total = $likes + $dislikes;
$likebar = round(($likes / $total) * 100);
$finlikes = (($likebar * 150)/100);
}else{
$finlikes = 150;
}
$query5 = mysql_query("UPDATE `videos` SET `views` = `views`+1 WHERE `videos`.`id` = $GOTID;");
$stop = false;
$fetchlast = mysql_query("SELECT `id` FROM videos WHERE id=(SELECT MAX(id) FROM videos)");
$lastrow = mysql_fetch_row($fetchlast);
$lastid = $lastrow[0];
for ($i=1; $i <= $lastid; $i++) {
if($GOTID == $id){
$stop = true;
break;
}else{
if($i >=$lastid && $GOTID != $id){
$stop = false;
header('HTTP/1.0 404 Not Found');
$_GET['e'] = 404;
die();
exit;
}
}
}
$username = '';
$userrep = '';
$rank = '';
$imageData = '';
$currentname = mysql_query("SELECT * FROM allaccounts WHERE id=$userid");
while ($row = mysql_fetch_array($currentname)) {
$username = $row[0];
$rank = $row[3];
$userrep = $row[7];
$data = $row["image"];
$ext = $row["filetype"];
// $img1 = Img_Resize($data);
// $imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
}
$liked = false;
$disliked = false;
$done = false;
$thing = mysql_query("SELECT `id` FROM likes WHERE id=(SELECT MAX(id) FROM likes)");
$lastrow = mysql_fetch_row($thing);
$lastid = $lastrow[0];
if($lastid == null || $lastid == '0'){
$lastid = '1';
}
$state1 = '';
for ($i=1; $i <= $lastid+1; $i++) {
$current = mysql_query("SELECT * FROM likes WHERE id=$i");
while ($row = mysql_fetch_array($current)) {
$id1 = $row[0];
$userid1 = $row[1];
$state1 = $row[2];
$articleid1 = $row[3];
if($done == false){
if($email == $userid1 && $articleid1 == $id && $state1 == '1'){
$liked = true;
$disliked = false;
$done = true;
break;
}else{
$liked = false;
}
if($email == $userid1 && $articleid1 == $id && $state1 == '0'){
$disliked = false;
$liked = false;
$done = true;
break;
}
if($email == $userid1 && $articleid1 == $id && $state1 == '2'){
$disliked = true;
$liked = false;
$done = true;
break;
}else{
$disliked = false;
}
}
}
}
$donetitle = str_replace(" ", "-", $title);
$_SESSION["prevpage"] = "video/".$id."/".$donetitle."";
$lik = mysql_query("SELECT * FROM videos WHERE id=$GOTID");
while ($row22 = mysql_fetch_array($lik)) {
$Olikes = $row22[6];
}
$dis = mysql_query("SELECT * FROM videos WHERE id=$GOTID");
while ($row22 = mysql_fetch_array($dis)) {
$Odislikes = $row22[7];
}
?>
<html>
<head>
<title><?php echo $title;?></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"language="javascript" type="text/javascript"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/javascript">
var likes = <?php echo $likes;?>;
var dislikes = <?php echo $dislikes;?>;
</script>
<div class = "container_24">
<header>
</header>
<div class = "main clearfix">
<div class ="grid_24 ">
<div id = "rectarticletop">
<a onclick='like()' id="likebtn"><img id="alike"src="img/icons/like.png" alt = "like"/></a>
<div id="dislikes"><div style="width:<?php echo($finlikes);?>;" id="likes"></div></div>
<a onclick="dislike()" id="dislikebtn"><img id="adislike" src="img/icons/dislike.png" alt = "dislike" /></a>
<p id= "likesnum"><?php echo $likes; ?></p>
<p id= "dislikesnum"><?php echo $dislikes; ?></p>
<script type="text/javascript">
var Liked = "<?php echo $liked;?>";
var Disliked = "<?php echo $disliked;?>";
var Art = "<?php echo $id;?>";
var User = "<?php echo $email;?>";
var olikes = "<?php echo $Olikes;?>";
var odislikes = "<?php echo $Odislikes;?>";
var state = "<?php echo $state1; ?>";
if(Liked == null){
Liked = false;
}
if(Disliked == null){
Disliked == false;
}
if(!Liked){
console.log("not liked!");
}
if(!Disliked){
console.log("not disliked!");
}
var loged = "<?php echo($log);?>";
window.onbeforeunload = function() {
$.ajax({
type: "GET",
url: 'dealLikes.php?article='+Art+'&user='+User+'&state=1&likes='+likes+'&dislikes='+dislikes+'&Olikes='+olikes+'&Odislikes='+odislikes+'&prev='+state+'',
success: function(data){
console.log("Its done!");
}
});
};
setInterval(function changetext(){
document.getElementById('likesnum').innerHTML = likes;
document.getElementById('dislikesnum').innerHTML = dislikes;
if(Liked){
document.getElementById('alike').src = "img/icons/like1.png";
}else{
document.getElementById('alike').src = "img/icons/like.png";
}
if(Disliked){
document.getElementById('adislike').src = "img/icons/dislike1.png";
}else{
document.getElementById('adislike').src = "img/icons/dislike.png";
}
},20);
function like(){
if(loged){
if(Liked){
likes-=1;
Liked = false;
// document.getElementById('alike').src = "img/icons/like.png";
}else if(Disliked){
dislikes-=1;
Disliked = false;
likes+=1;
Liked = true;
// document.getElementById('alike').src = "img/icons/like1.png";
// document.getElementById('adislike').src = "img/icons/dislike.png";
}else{
likes+=1;
Liked = true;
// document.getElementById('alike').src = "img/icons/like1.png";
}
}else{
window.location = "login";
}
}
function dislike(){
if(loged){
if(Disliked){
dislikes-=1;
Disliked = false;
// document.getElementById('adislike').src = "img/icons/dislike.png";
}else if(Liked){
likes-=1;
Liked = false;
dislikes+=1;
Disliked = true;
// document.getElementById('adislike').src = "img/icons/dislike1.png";
//document.getElementById('alike').src = "img/icons/like.png";
}else{
dislikes+=1;
Disliked = true;
// document.getElementById('adislike').src = "img/icons/dislike1.png";
}
}else{
window.location = "login";
}
}
</script>
</div>
</div>
</div>
</div>
</body>
</html>
What is wrong with the code that makes it not update the amount of likes on the first refresh but does update on the second refresh?

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.

javascript for loop in codeigniter

Here's my view :
$(".qty").keyup(function(){
var qty = $(this).val();
var bt = (this.id);
var bts = $('#bts'+bt).val();
var edge = $('#edge'+bt).val();
for (var i = 1; i<edge; ++i) {
var batas = $('#bts'+i).val();console.log(batas);
}
});
<input type="hidden" id="<?php echo 'edge'.$items['id']?>" value="<?php echo $items['options']['jum']?>"/>
<?php
foreach ($items['options']['stok'] as $stok) {
$er = $stok['stokbagus'];
$length = $items['options']['jum'];
for ($i=1; $i< $length; $i++) {
echo '<input type="text" rel="'.$items['rowid'].'" id="bts'.$i.'" value="'.$er.'"/>';
}
}
?>
$items['options']['jum'] contains = 2.
$stok['stokbagus'] contains = 30 and 21.
It'll display the first one (30). How to display all $stok['stokbagus'] in javascript?
Because i want to compare $(".qty").val() with all of $stok['stokbagus']
Okay. Here is what you should do.
If your $stok['stokbagus'] variable is array, then you should select the first and the second variable like this:
$first = $stok['stokbagus'][0];
$second = $stok['stokbagus'][1];
Else if, your $stok['stokbagus'] variable is a string and has 30,21 like this;
$vars = explode(",", $stok['stokbagus']);
$first = $vars[0];
$second = $vars[0];
You are saying that $stok['stokbagus'] variable has 30 and 21 values then it must be an array.
To show all values in your $stok['stokbagus'];
implode(', ', $stok['stokbagus']; // or just use $er.
Full:
echo '<input type="text" rel="'.$items['rowid'].'" id="bts'.$i.'" value="'.implode(', ', $er).'"/>';
Update:
<?php
foreach ($items['options']['stok'] as $stok) {
$er = $stok['stokbagus'];
$length = $items['options']['jum'];
for ($i=1; $i < $length; $i++) {
if(is_array($er)) {
foreach($er as $key => $value) {
echo '<input type="text" rel="'.$items['rowid'].'" class="bts" data-id="'.$i.'" value="'.$value.'"/>';
}
} else {
echo '<input type="text" rel="'.$items['rowid'].'" id="bts'.$i.'" value="'.$er.'"/>';
}
}
}
Js:
$(".qty").keyup(function(){
var qty = $(this).val();
var bt = (this.id);
var bts = $('#bts'+bt).val();
var edge = $('#edge'+bt).val();
for (var i = 1; i<edge; ++i) {
// I don't know what do you want to do with batas variable...
if($('.bts').length > 1) {
$('.bts').each(function(){
console.log($(this).val());
});
} else {
var batas = $('#bts'+i).val();console.log(batas);
}
}
});

Categories