display info in popup - javascript

I have this leaderboard :
leaderboard
on clicking a name in the leaderboard, a popup gets displayed.
popup snap
Now ,I want to display info of any person whose name has been clicked in the popup.As,you can see the popup doesnot contain any data.
I have been using an active directory,from where I can fetch data like the profile pic and other info from a DB i am maintaing.
Question is How do i link the active directory and databases and display the required info in the popup,when a name is clicked.Please help
Javascript involved with the popup :
$(document).ready(function() {
$('.tab a').on('click', function(e) {
e.preventDefault();
var _this = $(this);
var block = _this.attr('href');
$(".tab").removeClass("active");
_this.parent().addClass("active");
$(".leadboardcontent").hide();
$(block).fadeIn();
});
/**
* Fade in the Popup
*/
$('.leaderboard li').on('click', function () {
$('#popup').fadeIn();
var mark = $(this).find('name').text();
var small = $(this).find('points').text();
$('#popup-name').text('Name: ' + name);
$('#popup-score').text('Score: ' + points);
});
});
for active directory I am using this variable and echo it wherever I want for the logged in user :
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$server = 'ldap:xxxxx';
$domain = 'xxx'
$port = xxx;
$ldap_connection = ldap_connect($server, $port);
if (! $ldap_connection)
{
echo '<p>LDAP SERVER CONNECTION FAILED</p>';
exit;
}
// Help talking to AD
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
$ldap_bind = #ldap_bind($ldap_connection, $username.$domain, $password);
if (! $ldap_bind)
{
echo '<p>LDAP BINDING FAILED</p>';
exit;
}
else
{
echo 'login successful <br/>';
}
$base_dn = "OU=Employees,OU=Accounts,OU=India,DC=asia,DC=manh,DC=com";
$filter ="(&(objectClass=user)(samaccountname=$username))";
$result = ldap_search($ldap_connection,$base_dn,$filter);
$rescount = ldap_count_entries($ldap_connection,$result);
$data = ldap_get_entries($ldap_connection,$result);
if ($data["count"] > 0)
{
for ($i=0; $i<$data["count"]; $i++)
{
if(isset($data[$i]["employeeid"][0]))
{
$user= $data[$i]["employeeid"][0];
session_start();
$_SESSION['id']=$user;
}
if (isset($data[$i]["thumbnailphoto"][0]))
{
$photo=$data[$i]["thumbnailphoto"][0];
$_SESSION['photo']=$photo;
}
if (isset($data[$i]["title"][0]))
{
$title=$data[$i]["title"][0];
$_SESSION['Employeetitle']=$title;
}
if (isset($data[$i]["department"][0]))
{
$department=$data[$i]["department"][0];
$_SESSION['Employeedepartment']=$department;
}
}
}
else
{
echo "<p>No results found!</p>";
}
if(isset($_SESSION['id']))
{
echo "session set";
header('location:Profile/index.php');
}
?>

Update
Replace code with following code
HTML
<li>
<mark>Weekly LB</mark>
<small>315</small>
<input type="hidden" class="email" value="<?php echo $_SESSION['Employeetitle']; ?>">
<input type="hidden" class="designation" value="<?php $_SESSION['Employeedepartment'] ?>">
<input type="hidden" class="pro_pic" value="<?php echo $_SESSION['photo']; ?>">
</li>
JS
/**
* Fade in the Popup
*/
$('.leaderboard li').on('click', function () {
$('#popup').fadeIn();
// Changes
var email = $(this).find('.email').val();
var designation = $(this).find('.designation').val();
var pro_pic = $(this).find('.pro_pic').val();
// -------------------
var mark = $(this).find('mark').text();
var small = $(this).find('small').text();
// Changes
$('#popup-email').text('Email: ' + email);
$('#popup-designation').text('Name: ' + designation);
$('.profile__image').attr("src", pro_pic);
// -------------------
$('#popup-name').text('Name: ' + mark);
$('#popup-score').text('Score: ' + small);
});
Let me know if you have any concerns for the same..

It seems your data is stored in db, and you already managed to fetch them correctly. So instead of doing an ajax call maybe you can consider all the necessary information / key as custom attributes in html tag, so that it can be fetched easily via JavaScript. i.e.;
<li id="someid" designation="..." rmanager="..." email="...">
<mark>Weekly LB</mark>
<small>315</small>
</li>
and using JQuery;
var designation = $('#someid').attr('designation');
$('#designation-field').text('Designation: ' + designation);
hope it will help.
By the way, this method has advantages and disadvantages;
Disadvantage: it will increase your listing page size
Advantage: will reduce client-server and database calls

Did you try like this...
Define class of li elements as below..
<div class="leaderboard">
<ul>
<li class="name">value</li>
<li class="points">value</li>
</ul>
</div>
Then fetch value like this
var name= $(".leaderboard").find('.name').text();
var points= $(".leaderboard").find('.points').text();
$('#popup-name').text('Name: ' + name);
$('#popup-score').text('Score: ' + points);

Related

PHP translation From SQL Database

My site pulls test questions from a database, and some of these questions have images associated with them.
The images pull in fine and everything works as expected, but when trying to pull the answers for these questions, which sometimes also have images, there is a translation issue causing just the reference index to be called and no image displayed (the text still appears that is associated with the answer however).
Question Picture Example
Answer Picture Example - An image should appear in the highlighted area
I can't tell if the issue is caused in the HTML/PHP interpretation of calling an answer or in the function that defines the answer to be called. Code snippets below.
First is the HTML/PHP and JS. All things pertaining to answers are "Rationale" All things pertaining to images are "equations":
<?php
for ($i = 0; $i < $displayCount; $i++) {
$workingDate = date('Y-m-d', time()-($i*24*60*60));
$QID = updateQOTD($ar, $workingDate, $level);
$questionInfo = getQuestion($ar, $QID);
echo $workingDate."<br><br>";
if(isset($questionInfo->VIGNETTE)) {
echo "<strong>Vignette</strong>:<br>";
echo $questionInfo->VIGNETTE;
echo "<br><br>";
}
$equation = getEquation($ar, $QID);
$eq_text = '';
if (isset($equation)) {
$file = $equation->FILE_NAME;
$eq_text = '<img src="/lcms/images/equations/' . $file . '">';
}
echo "<strong>Question</strong>:<br><br>";
$qtext = $questionInfo->TEXT ;
$qtext = preg_replace('/<equation id="\d+"\/>/', $eq_text, $qtext);
echo $qtext;
echo "<br><br>";
?>
<div id='response_<?php echo $i; ?>'></div>
<div class='rationale margin-top-20'><br><strong>Rationale:</strong><br>
<?php echo $questionInfo->RATIONALE; ?>
</div>
<?php
}
?>
<button id="grade" class="btn-theme" type="button">Grade My Choices</button>
<? require_once(getenv("DOCUMENT_ROOT")."/inc/footer.pilot.php"); ?>
<script type="text/javascript">
$(document).ready(function(){
$(".rationale").hide();
$("response_1").hide();
$("response_2").hide();
$("response_3").hide();
$("response_4").hide();
$("response_5").hide();
$("#grade").click(function () {
$(".correctMark").html("<img src='../../images/600px-Green_check.png' />");
$(".incorrectMark").html("<img src='../../images/600px-Red_x.png' />");
$(".rationale").slideDown("fast");
if ($("input[name='question_1']:checked").val() == 'correct') {
$("#response_1").text("Your answer was correct!");
$("#response_1").slideDown("slow");
}
});
});
</script>
And here is the database code call SQL and function defining Rationale:
function getEquation($ar, $QID) {
if (isset($QID) && $QID > 0) {
$selectSql = sprintf("SELECT e.FILE_NAME FROM equation_tbl e, equation_question_link_tbl eq WHERE eq.QUESTION_ID = %s AND e.ID = eq.EQUATION_ID ",
$QID);
$equation = $ar->get_row($selectSql);
return $equation;
}
}
function getQuestion($ar, $QID) {
$selectSql = sprintf("SELECT case_tbl.TEXT as VIGNETTE, question_tbl.TEXT, question_tbl.ANSWER_1, question_tbl.ANSWER_2, question_tbl.ANSWER_3, question_tbl.ANSWER_4, question_tbl.ANSWER_5, question_tbl.ANSWER_6, question_tbl.ANSWER_7, question_tbl.ANSWER_8, question_tbl.RATIONALE FROM question_tbl LEFT JOIN case_tbl ON question_tbl.CASE_ID = case_tbl.ID WHERE question_tbl.ID = %s",
$QID);
$question = $ar->get_row($selectSql);
return $question;
}
function makeAnswerArray($questionInfo) {
$answers[0] = array($questionInfo->ANSWER_1, 'correct');
$answers[1] = array($questionInfo->ANSWER_2, 'incorrect');
$answers[2] = array($questionInfo->ANSWER_3, 'incorrect');
if(isset($questionInfo->ANSWER_4) && $questionInfo->ANSWER_4 > ' ') {
$answers[3] = array($questionInfo->ANSWER_4, 'incorrect');
if(isset($questionInfo->ANSWER_5) && $questionInfo->ANSWER_5 > ' ') {
$answers[4] = array($questionInfo->ANSWER_5, 'incorrect');
if(isset($questionInfo->ANSWER_6) && $questionInfo->ANSWER_6 > ' ') {
$answers[5] = array($questionInfo->ANSWER_6, 'incorrect');
if(isset($questionInfo->ANSWER_7) && $questionInfo->ANSWER_7 > ' ') {
$answers[6] = array($questionInfo->ANSWER_7, 'incorrect');
if(isset($questionInfo->ANSWER_8) && $questionInfo->ANSWER_8 > ' ') {
$answers[7] = array($questionInfo->ANSWER_8, 'incorrect');
}
}
}
}
}
return $answers;
}
Is there any reason why the images associated with Rationales are not pulling through when expected?
I would start by checking the values of $equation with var_dump($equation) and also var_dump($question) to look for any anomalies. I suspect you've got incomplete data creeping in that looks like /lcms/images/equations/NULL or something similar which should be obvious enough, when dumped.
If this is the case, look at extending your handling of these vars to be more strict about the expected value.
Truth be told, it's going to be difficult to help if we cannot run the code. But I would start by checking data integrity of the MySQL result. Bit of a SQL join in there too that only you will know the correct format of, which would be my next port of call.

PHP to read DB value, JS to increment it, AJAX to save to DB, but why does it default to 0.0 before refreshing the page?

I am making a temperature target page where the form will read the current target, allow the user to +/- by 0.5 using Javascript buttons and then 'set' the target which takes the new value and saves it back to the database.
I have a working page which can read the DB value and set it, but then automatically reverts to '0.0' as the target. If the page is refreshed then it will display the target, but sometimes saves it at 0.0 in the DB.
I'm very confused as to why as I've spent far too long on this, but its bugging me! Any help is much appreciated, thanks.
Here is my code:
<?php
$conn = connect DB stuff here...
$queryTarget = "SELECT * FROM target;";
$result2 = $conn->query($queryTarget);
$conn->close();
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$target = $row['target'];
}
}
?>
<form id="input" method="post" action="">
Temp <input type="text" value="<?php echo $target; ?>" name="temp" id="temp" >
<input type="button" id="Up" value="up" / >
<input type="button" id="Down" value="down"/ >
<input type="submit" id="submit" value="submit " name="submit">
</form>
<?php
$conn = connect DB stuff here...
$temp = $_POST['temp'];
$updateTarget = "UPDATE target SET target = '";
$updateTarget = $updateTarget . $temp . "' WHERE id = 1;";
$result = $conn->query($updateTarget);
$conn->close();
?>
<script>
var min = 15,
max = 25;
$("#Up").click(function(){
if($("#temp").val() < 25 && $("#temp").val() >= 15)
$("#temp").val(Number($("#temp").val()) + 0.5);
});
$("#Down").click(function(){
if($("#temp").val() <= 25 && $("#temp").val() > 15)
$("#temp").val(Number($("#temp").val()) - 0.5);
});
</script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'form.php',
data: srt,
success: function(d) {
$("#input").html(d);
}
return false;
});
});
});
</script>
just echo this temp value
<?php
//$conn = connect DB stuff here...
$temp = $_POST['temp'];
or
print_r($_POST);
echo $temp;
die();
$updateTarget = "UPDATE target SET target = '";
$updateTarget = $updateTarget . $temp . "' WHERE id = 1;";
then check alert if alert show right data then
then use single query like this
$updateTarget = "UPDATE target SET target = '$temp' WHERE id = 1";
//i think it will help you to find issue
$result = $conn->query($updateTarget);
$conn->close();
?>
and your javascript function need to update
<script>
$(document).ready(function(){
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'form.php',
data: srt,
success: function(d) {
alert(d);
$("#input").html(d);
}
});
return false;
});
});
</script>
if you find right data then check your db structure that is it allow float etc. i think it will work
you can also check this
How to Search value from input by mysqli in database

How can I make the delete buttons fully functional with right ID using php, AJAX or MySQL?

I am having a little problem with this, every delete button is supposed to delete the record of its own id. If we click 164 it must delete the record of 164. It works fine if I remove the ajax and ask the form to validate directly, but if I use AJAX it only deletes the record of 1st record regardless of what button I press e.g. in current scenario it will always delete the record of 159 even if I press 164 button. My code gives the following output: Remember it works fine if I ask the form to validate directly from other PHP file.
This is my output please have a look at it. Its quite simple!
if(is_numeric($lumens) && $lumens < 5000 && $lumens >250){
if(is_numeric($THD) && $THD <= 20 && $THD >=0){
if(is_numeric($scaled_power_factor) && $scaled_power_factor >=0.9){
if(is_numeric($scaled_cct) && $scaled_cct <=5700){
if(is_numeric($scaled_cri) && $scaled_cri >=65){
if(is_numeric($scaled_input_power)){
$con = new mysqli(localhost, asd, myp, rec);
if(!$con){
echo "Couldn't connect to the database";
}
else{
$id = $_SESSION['user_id'];
$query = "INSERT INTO scaling_performance_data SET
MODEL_NUMBER = '$model_number',
LUMENS = '$lumens',
scaled_luminaire_efficacy = '$lm_w',
scaled_input_power = '$scaled_input_power',
THD = '$THD',
SCALED_POWER_FACTOR = '$scaled_power_factor',
SCALED_CCT = '$scaled_cct',
SCALED_CRI = '$scaled_cri',
HOUSING_VARIATION = '$housing_variation',
user_id = '$id'
";
if($con->query($query)){
$sql = "SELECT * FROM scaling_performance_data WHERE user_id='$id';";
$result = $con->query($sql);
if($result){
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
?>
<form>
<table>
<tr>
<th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th><input type="button" name ="delete_id" id="delete_id" value="<?php echo $row['ID'];?>" onclick="vlid();"/></th>
</tr>
</table>
<script type="text/javascript">
function vlid(){
var delete_id = $('#delete_id').val();
alert(delete_id);
$.post('validator.php',{
postdelete_id : delete_id
},
function(data){
$('#del').html(data);
}
)
}
</script>
</form>
<?php
}
}
validator.php is:
$id = $_POST['postdelete_id'];
$con = new mysqli(localhost, asd, myp, rec);
if(!$con){
echo "Couldn't connect to the database";
}
else{
$query="DELETE FROM scaling_performance_data WHERE ID='$id';";
if($con->query($query)){
echo "Your Result was deleted successful";
echo $id;
}else{
echo "There was a problem Please try again later";
}
}
The problem is that in your vlid() function, JQuery is only selecting the first element with id = delete_id. I would try passing the ID to the vlid() function like this:
<input type="button" ... onclick="vlid(<?php echo $row['ID'];?>)"/>
And then modify your vlid() function to accept the ID parameter.
Try var delete_id = $(event.target).val(); instead of: var delete_id = $('#delete_id').val();
1st ID must be unique so use
class="delete_id"
instead of
id="delete_id"
2nd remove onclick="vlid();" and use
$(document).ready(function(){
$('body').on('click','.delete_id',function(){
var getValue = parseInt($(this).val());
$.post('validator.php',{postdelete_id : getValue},function(data){
$('#del').html(data);
});
});
});
and to remove the tr which deleted use
$(document).ready(function(){
$('body').on('click','.delete_id',function(){
var thisBtn = $(this);
var getValue = parseInt(thisBtn .val());
$.post('validator.php',{postdelete_id : getValue},function(data){
$('#del').html(data);
thisBtn.closest('tr').remove();
});
});
});

Uncaught ReferenceError: output is not defined when using jQuery $.post() in file file

I have a dynamic search which uses jQuery and a PHP search file to dynamically show the results below. I just changed my log in scripts and sessions; now i am having issues with a search bar that searches through the members in a DB. When I was going through the testing I see that on each keyUp the jQuery function runs properly but there is some sort of issue inside of my search.php file. It seems like there is no $userCount or $userCount = 0 because it will display "There Were No Search Results"which only happens when it equals $userCount== 0
Here are the parts of my index.php
<script type="text/javascript">
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
if (searchTxt == '') {
// $.post("includes/search.php", {searchVal:searchTxt},
// function(output){
// $("#userResults").html(output);
// });
}else{
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
$("#userResults").html(output);
});
console.log(output);
}
}
</script>
<form class="editUser" action="index.php" method="post">
<h1>Search For Employee</h1>
<input type="text" name="userSearch" id="userSearch" placeholder="Search For Employee By First Or Last Name | Press Space To View All Employees" onkeyup="searchUserQ();" />
<submit type="submit" />
div id="userResults">
</div>
</form>
and here is my search.php file
<?php
// this file connects to the database
include("connect.inc.php");
if(isset($_POST['searchVal'])){
// turn that the user searched into a varible
$searchQ = $_POST['searchVal'];
// delete any symbols for security
$searchQ = preg_replace("#[^0-9a-z]#i", "", $searchQ);
$output = "";
// Search through these columns inside the main database
$userSearchQuery = mysql_query("SELECT * FROM dealerEmployees WHERE
firstName LIKE '%$searchQ%' or
lastName LIKE '%$searchQ%'
");
// count the number of results
$userCount = mysql_num_rows($userSearchQuery);
if($userCount == 0){
// $output = "There Were No Search Results";
}else{
while($row = mysql_fetch_array($userSearchQuery)){
// define dynamic varibles for each loop iteration
$id = $row['id'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$address = $row['address'];
$phone = $row['phone'];
$email = $row['email'];
$passwordQ = $row['password'];
$permission = $row['permission'];
$photo = "images/" . $row['profilePhoto'];
$output .= "<li><div class='employeeSearch' style=\"background: url('$photo'); width: 75px; height: 75px\"></div><h6>" . $firstName . "</h6>" . " " . "<h6>" . $lastName . "</h6><a href='#' class='employee' data-firstName='$firstName' data-lastName='$lastName' data-address='$address' data-phone='$phone' data-email='$email' data-password='$passwordQ' data-permission='$permission' data-id='$id'>Select Employee</a></li>";
}
}
}
echo $output;
Any suggestions why this is happening?
The reason for the error in the title is that you have console.log(output) outside the callback function. This has two problems: First, the variable output is not in scope; second, it runs immediately, not after the AJAX call returns. Move it into the callback:
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
if (searchTxt != '') {
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
console.log(output);
$("#userResults").html(output);
});
}
}

Ajax call not working after page reload.

I have my home page in php with checkboxes by the names of brand and store list.and in the end one submit button which is given below
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="brand"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
function get_store_value(){
var d_value=[];
$('input[name="store"]:checked').each(function () {
d_value.push(this.value);
});
return d_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function (e)
{e.preventDefault();
alert("hi");
//var os = $('#originState').val();
//var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
var store=get_store_value();
//var queryString = "os=" + os;
var data = "?ser=" + ser;
var queryString = "&ser=" + ser;
alert(ser);
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: {ser:ser,store:store},
dataType : 'html',
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>
brand
<input type="checkbox" name="brand" value="Sunbaby" />Sunbaby
<br/>
<input type="checkbox" name="brand" value="Advance Baby" />Advance Baby
<br/>
store
<br/>
<input type="checkbox" name="store" value="JCPenny" />JCPenny
<br/>
<input type="checkbox" name="store" value="Supermart" />Suoermart
<br/>
<input type="checkbox" name="store" value="Target" />Target
<br/>
<button id="btnSubmit">sort</button>
<div id="results">
</div>
</body>
</html>
On click of submit,button it goes for ajax call and displays the result in results div.
<?php
include('connection.php');
$query=$_POST['ser'];
$query1=$_POST['store'];
echo $query;
echo $query1;
$query=explode(",",$query);
$query = array_filter($query);
$query1=explode(",",$query1);
$query1 = array_filter($query1);
$result=count($query);
$result1=count($query1);
//echo $result;
echo $result1;
$parts = array();
$limit = 10;
$offset = 0;
if(!empty($query))
{
foreach( $query as $queryword ){
$parts[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
$brandsql='SELECT * FROM XML WHERE ('.implode ('OR',$parts).') order by price asc';
$brandsql1=mysql_query($brandsql);
$numrows = mysql_num_rows($brandsql1);
$countArray=array();
print($brandsql);
echo "<br />";
while($row = mysql_fetch_array($brandsql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
$parts1=array();
if(!empty($query1)){
foreach( $query1 as $queryword1 ){
$parts1[] = '`STORE` LIKE "%'.$queryword1.'%"';
}
$storesql='SELECT * FROM XML WHERE ('.implode ('OR',$parts1).') order by price desc';
$storesql1=mysql_query($storesql);
$numrows1 = mysql_num_rows($storesql1);
$countArray=array();
print($storesql);
while($row = mysql_fetch_array($storesql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
?>
<?php
foreach($countArray as $array)
{
?>
<div>
hi</div>
<?php $i++; } ?>
But iF I refresh my page or press F5 from keyboard,after getting content in results div,it goes back to previous content i.e.first page with checkboxes and submit button.
Please tell me where m doing wrong in the code or what do i need to include so that after ajax call if i refresh the page,content should remain same,should not go to previous content...
Use setTimeout() to run a refresh on the page after X seconds inside the AJAX callback, after you display content.
You could use the _SESSION variable in your PHP script to store what checkboxes were selected most recently, and display results on your results div, appropriately.
Although, if a user clicks refresh he might want to reset the choices he made anyway. You could give him a warning that his changes will be lost if he refreshes.
window.onbeforeunload = function() {
return confirm("You have made changes to this form. Do you want to continue without saving these changes?");
}

Categories

Resources