i have display data from xml file to the index.php like this
function processXML($node){
foreach($node->children() as $agent => $data){
$agent= trim($agent);
if($agent=='image')
{
echo '<div><img src="'.$data.'" ></div>';
echo '<div>';
echo '</div>';
}
elseif($agent=='id')
{
echo '<div class = "Left">';
echo '<input type = "button" name="Agent" id = "'.$data.'" class = "subs-btn" value = "Select this Agent" OnClick = Selected(this.id);>';
$_SESSION['Selected'] = $data;
echo '</div>';
echo '<br/>';
echo '<br/>';
}
else
{
echo '<div class = "inline1">';
echo $data;
echo '</div>';
echo '<br/>';
}
processXML($data);
}
}
processXML($xml);
you guys can see here i am generating a button and onclick function is call - Selected(this.id);
So here is the code of function
function Selected(elem) {
var buttons = document.getElementsByClassName('subs-btn');
var length = buttons.length;
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundImage="url('images/subs-btn.png')";
buttons[i].value="Select this Agent";
}
document.getElementById(elem).style.backgroundImage="url('images/subs-btn-act.png')";
document.getElementById(elem).value="Agent Selected";
}
So due to this agent is selected. Now i had one button at the end of the page
<input type = "submit" name="Continue" class = "btn btn-primary right" value = "Continue">
now i want to display data which is related to selected agent on another page. So how can i display this data with respect to selected agent?
Please Help.
You would need to something along the lines of the following. This is more just psuedo code than an actual working example, as I don't know what you want to display about an agent
Note: I am assuming you have jQuery included.
JS
function Selected(elem) {
var buttons = document.getElementsByClassName('subs-btn');
var length = buttons.length;
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundImage="url('images/subs-btn.png')";
buttons[i].value="Select this Agent";
}
document.getElementById(elem).style.backgroundImage="url('images/subs-btn-act.png')";
document.getElementById(elem).value="Agent Selected";
//Start here
var AgentData = ""//something about the agent. their id or some other identifier
//here you would make an ajax call to a php script
$.ajax({
type:"POST",
data: AgentData,
url: "someurl"
});
}
PHP
$_SESSION["AgentData"] = $_POST["AgentData"];
Now you would be able to access that data about the selected agent anywhere as long as there is a valid session.
Related
I'm having some issues submitting an HTML form. The form allows the user to add skills to the HTML page using a button. These newly created skills then need to be inserted into the database. The problem is, I can only insert one skill at a time. The skills are entered as checkboxes and all checked skills should be entered in the database. I think my issue is that each checkbox that is created dynamically shares the same $skill_name variable, but this is not an issue when I grab existing skills from the database to display. I added some ajax to try and save each skill in a post statement as they are created, but it doesn't help when I actually go to insert. The INSERT statement looks something like this:
if(!empty($_POST["backend"])){
$backend = $_POST["backend"];
$sql2 = "INSERT INTO skill (skill_cat_id, skill_name) VALUES (?,?)";
$skill_cat_id = 1;
for ($i = 0; $i < count($backend); $i++){
$skill_name = $_POST["skill_name"];
if($stmt = $mysqli->prepare($sql2)){
$stmt->bind_param("is", $skill_cat_id, $backend[$i]);
if ($stmt->execute()) {
echo "<script>
alert('Success!');
</script>";
}
else{
echo "<script>
alert('Failure!');
</script>";
}
}
}
}
And the HTML for looks like this:
<h5>Backend Technologies </h5>
<div class="container">
<div id = "backendDiv">
<?php
$backend=getbackendtech();
while($row = $backend -> fetch_assoc()) {
// echo "<input type='checkbox' value='{$data['skill_name']}'>". $data['skill_name'];
echo "<div class=\"list-group-item checkbox\" id = \"backendCheckBoxes\">
<label><input type=\"checkbox\" name=\"backend[]\" class=\"common_selector form\" value='{$row['skill_name']}'> {$row['skill_name']}</label>
</div>";
}
echo"<input type=\"button\" class='btn btn-warning btn-sm' id = \"addBackendButton\" value = \"Add\" onclick=\"addSkill('backendCheckBoxes', 'backendDiv', 'backend', 'addBackendButton')\">";
?>
</div>
</div>
And here is the addSkill event:
function addSkill(checkBoxDivId, divId, nameId, buttonId){
//Variables
//Creating new elements for new skills and
//setting their attributes
let count = 0;
console.log(checkBoxDivId);
let existingSkills = document.querySelectorAll("div[id =" + checkBoxDivId +"]");
console.log(existingSkills);
for (let i = 0; i < existingSkills.length; i++){
count++;
}
let uniqueId = count+1;
console.log(uniqueId);
let hiddenValue = document.createElement("input");
hiddenValue.setAttribute("hidden", true);
hiddenValue.setAttribute("name", "skill_name");
let checkBoxDiv = document.createElement("div");
checkBoxDiv.setAttribute("id", checkBoxDivId);
checkBoxDiv.setAttribute("class", "list-group-item checkbox");
//console.log(checkBoxDiv);
let textBoxParent = document.getElementById(divId);
//console.log(textBoxParent);
let newTextBox = document.createElement("input");
newTextBox.setAttribute("type","text");
newTextBox.setAttribute("id", "newTextBox");
let newCheckBox = document.createElement("input");
newCheckBox.setAttribute("name", nameId);
newCheckBox.setAttribute("class", "common_selector form");
newCheckBox.setAttribute("type","checkbox");
newCheckBox.setAttribute("checked", true);
newCheckBox.setAttribute("value", uniqueId);
let newLabel = document.createElement("label");
newLabel.setAttribute("for", "newCheckBox");
let addButton = document.getElementById(buttonId);
//console.log(addButton);
//adding textbox to page
textBoxParent.appendChild(newTextBox);
//When an enter key is pressed the newly created textBox
//will be removed and a new checkbox will appear
newTextBox.addEventListener("keypress", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
//console.log(newTextBox.value);
//Canceling the default action, if needed
event.preventDefault();
event.stopPropagation();
//Setting Label value
newLabel.innerHTML = newTextBox.value;
let skill_name = newLabel.innerHTML;
console.log(newCheckBox.getAttribute("value"));
//posting skill name to database
hiddenValue.setAttribute("value", newLabel.innerHTML);
console.log(hiddenValue);
//Remove textbox from page
textBoxParent.removeChild(newTextBox);
//Adding new Checkbox to Div
checkBoxDiv.appendChild(newCheckBox);
checkBoxDiv.appendChild(newLabel);
//checkBoxDiv.appendChild(hiddenValue);
//Adding new Checkbox Div to page
addButton.before(checkBoxDiv);
$.ajax({
type: 'post',
data: {skill_name: skill_name},
success: function(response){
alert(skill_name);
}
});
}
});
}
I have the following code which returns the result I require inside of a tab. But because the JavaScript is in the same file it shows a blank tab when there is no data to show. I remove the JavaScript and the tab disappears. How can I run the JavaScript only if data is present so the tab will disappear? Or can I call it from another file?
<?php echo $block->escapeHtml($block->getProduct()->getData($this->getCode()));
?>
<script type="text/JavaScript">
var commareplace = document.querySelectorAll("div > #bikefitment");
for (var i = 0; i < commareplace.length; i++) {
commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
}
</script>
Since you have to hide the tab if escapeHtml() returns empty value. So you can create a condition block to add the script if escapeHtml() returns a non-empty value.
<?php $EH = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
if ($EH) {
echo $EH;
?>
<script type="text/JavaScript">
var commareplace = document.querySelectorAll("div > #bikefitment");
for (var i = 0; i < commareplace.length; i++) {
commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
}
</script>
<?php } ?>
My knowledge on PHP is not the best, so I will just describe it like that.
Just save the data in a variable
If the data exists (e.g. is not empty)
Print data and JavaScript code
If it does not exist, do nothing
Here is some pseudo-code:
<?php
data = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
if (data exists) {
echo data;
echo /* Your JavaScript Code*/;
}
?>
Use a if statement that within the php tags that check value id present then you can render the the java script tags as well as the value.
<?php
$val = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
$script = '<script type="text/JavaScript">
var commareplace = document.querySelectorAll("div > #bikefitment");
for (var i = 0; i < commareplace.length; i++) {
commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
}
</script>';
if($val != "" || $val !=null)
{
echo $val;
echo $script;
}
?>
I'm having an issue to load all the movieID and parse it into the location $movieID for url2.
With the code that i am having now (First Code), it will only retrieve one particular movie. When I click on the button, it have an alert box stating if it's success or error. I understand that because $url2 is outside of the loop. Hence, it's only able to retrieve one particular movie.
On second code, I have place it inside the for loop. However, it will keep looping and when I try to click on the button, it doesn't works. There is no alert box pop up.
How can I make the button works for all the $movieID that parse through the link?
First Code:
<?php
$url1 = json_decode(file_get_contents('http://www.movie.com:/retrieveMovies'));
$counter = count($url1);
for ($i = 0; $i < $counter; $i++){
$movieID = $url1[$i]->movieId ;
}
$url2 = json_decode(file_get_contents(' http://movie.com/movieOne?seatNum=' . $movieID),TRUE);
foreach ($url2 as $obj){
$testingResult = $obj['avail'];
echo "<button onclick = testBTN('".$testingResult."')>Seat ID</button>";
}
?>
<script>
function testBTN(x) {
if (x == "OK"){
alert("Seat booked" );
}
else
{
alert("Error in booking seats" );
}
}
</script>
second code:
<?php
$url1 = json_decode(file_get_contents('http://www.movie.com:/retrieveMovies'));
$counter = count($url1);
for ($i = 0; $i < $counter; $i++){
$movieID = $url1[$i]->movieId ;
$url2 = json_decode(file_get_contents(' http://movie.com/movieOne?seatNum=' . $movieID),TRUE);
foreach ($url2 as $obj){
$testingResult = $obj['avail'];
echo "<button onclick = testBTN('".$testingResult."')>Seat ID</button>";
}
}
?>
<script>
function testBTN(x) {
if (x == "OK"){
alert("Seat booked" );
}
else
{
alert("Error in booking seats" );
}
}
</script>
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);
I have a javascript function that clones a div which contains a inputfield, now the problem is that the cloned inputfield values isnt send through post. Only the first value of the array gets a value.
Anyone know what could be the problem?
Post button:
if(isset($_POST['VolgendeStap'])) {
$phonenumberAmount = count($_POST['phoneNumbers']);
echo $phonenumberAmount;
echo '<br>';
echo $_POST['phoneNumbers'][0];
echo $_POST['phoneNumbers'][1];
}
Divs with inputfield
echo "<div class='allPhoneNumbers'>";
for($j = 0; $j < $phonenumberAmount; $j++) {
echo "<div id='phoneNumber{$j}'>";
echo "<input type='text' name='phoneNumbers[]'>";
echo "<input type='button' class='removeButton' value='x'>";
echo "</div>";
echo '<script>';
echo 'current++;';
echo '</script>';
}
echo "</div>";
echo "<input type='button' id='cloneButton' onclick='cloneDiv(phoneNumber0);' value='Nog een nummer'>";
Javascript:
var max = 5;
var current = 0;
// Duplicates the DIV
function cloneDiv(divID) {
if(current < max) {
var newDiv = $(divID).clone();
newDiv.attr("id", "phoneNumber"+current);
current++;
newDiv.children()[0].value = '';
newDiv.find(".removeButton").show();
newDiv.children()[1].onclick = function() {
$(this.parentNode).remove();
current--;
if(current < max) {
$("#cloneButton").show();
}
};
newDiv.appendTo(".allPhoneNumbers");
if(current == max) {
$("#cloneButton").hide();
}
}
}
it looks like you are declaring the "var current = 0" on every page load, and when you post the form it executes that part of code (couse it causes the page to reload) and that's why you always see only the first one. You should have a function that sets the "current" initial and future values by actually counting the number of divs. Let me know if it works out, cheers!