Hide/Show Input's based on mysql data - php

I have an active session in my page using: $_session_start(); I want to hide part of my form and show another based on the users previous entries.
Basically I offer Direct Deposit and Paper Check I want to be able to have the user only see the fields required for them to complete previously (in signup so the values are already in the database)
Right now the database table is set up like this:
paper_check with a value of 1 (yes pay this way) or 0 (no pay this way)
and the same thing with direct deposit. I need a way to show/hide the fields associated with each based on the users previous selections.
I typed this up but it doesn't seem to do anything. Please help me!!!!! (The class names hide and show are in my css and working properly!)
<?php
if ($_SESSION['direct_deposit'] == 1)
{
$doc->getElementById('check_payable_to')->className+" hide";
}
else
{
$doc->getElementById('name_on_account')->className+" hide";
$doc->getElementById('check_payable_to')->className+" show";
}
?>

I don't see a className property in the PHP DOM library. It looks like this is the way to add a class to an element:
$doc->getElementById('check_payable_to')->setAttribute('class',
$doc->getElementById('check_payable_to')->getAttribute('class') . " hide");
Do you have error reporting enabled? It should be warning about the unknown property.
If you want to do this in Javascript instead of PHP, have your PHP do something like:
<script>
var direct_deposit = <?php echo $_SESSION['direct_deposit']; ?>;
if (direct_deposit == 1) {
/* Do what you want */
} else {
/* Do what else you want */
}
</script>

In your question you said "I have an active session in my page using: $_session_start();" You shouldn't use $_session_start(). It should be session_start() .

className+" hide" should be className .= " hide"

By wrapping each section in it's own div like so:
<div id="paperCheck class="show">
<!--Your Paper Check Information here-->
</div>
<div id="directDeposit" class="show">
<!--Your Direct Deposit Information here-->
</div>
And then by using javascript you are able to do the following:
var direct_deposit = <?php echo $_SESSION['direct_deposit']; ?>;
if (direct_deposit == 1)
{
document.getElementById('paperCheck').className ="hide";
}
else
{
document.getElementById('directDeposit').className ="hide";
}

Related

PHP How to get userID (variable) in pop up modal

A number of employees and their info gets shown on a page. The info of employees gets retrieved via a DB and then a foreach() loop is used to display all employees who fit the search criteria, an example can be seen on image below
Now when the user clicks the button, a simple Bootstrap pop up modal gets triggered, with some basic form fields. As can be seen from example image below
My Problem
I need to get the $userID when a button is clicked to work with / process data in modal.
Below is an extract of relevant code:
$teacherClass = new TeacherSearch();
$teachers = $teacherClass->showAllTeachers();
if (is_array($teachers)) {
foreach ($teachers as $teacher) {
$src = $teacher['userID'];
<div class="teacher-info">
<p class="teacherLabel">
NAME:
<?php
echo $teacher['name'];
?>
</p>
<p class="teacherLabel">
HEADLINE:
<?php
echo $teacher['headline'];
?>
<p class="teacherLabel">
LOCATION:
<?php
echo $teacher['location']
?>
</p>
<!--BUTTON GOES HERE-->
}//foreach
What I've tried
Ive tried using an <a> element binding a parameter with userID to it, like so:
Hire <?php echo $teacher['name'] ?>
As is to be expected the following triggered a new page reload inside the modal.
I then tried using a # sign for ahref attribute and then biding parameter $userID to it like so:
The above lead to an undefined index error as can be seen in the picture above.
Conclusion
I hope this question makes sense, I'm pretty much out of ideas, no idea how to further approach this problem.
You add the user-id in the anchor tag.To get the contents of the attribute data-id you have to use
<a id="myid" data-id="123">link</a>
<script>
$('#myid').data("id");
</script>
use javascript function to get userID and show modal:
<a onclick="myfunction('<?php echo $userID; ?>')>Hire <?php echo $teacher['name'] ?></a>
javascript function:
var userID; // global
function myfunction(id){
userID = id;
$("#myModal").modal("show");
//do somethings with user id here
}

PHP: How to populate a page dynamically once the user clicks on the URL

With help from #teresko I've managed to create dynamic pages (& their urls) for my site using the loop below. My problem is how do i get the newly created page at ahref to combine data I have in database with the template (which I already have ready), so that when the user clicks on it, she/he goes to the page populated with the data. Am i supposed to use a javascript click function (would rather not). How would i do it with php and html?
Here is the loop generating the URLs:
<?php foreach ($reciperow as $recipe) { ?>
<h2><?php echo $recipe['rectitle'];?></h2>
<p class="subhead"><?php echo $recipe['recsummary']; ?></p>
<?php } ?>
Would really appreciate a solution that stays clear of routing, since my site's a basic project and I plan to get to MVC and PHP routing in the next projects. Thanks.
If you meant How, when user clicks generated link, show him page with data from database accordingly to "id" he/she selected, then do the following:
<?php
$id = intval($_REQUEST['id']);
if ($id) { // user get here by clicking on link with id
$data = ... // fetch data from database
?>
<sometag>Some data from database:<?php echo $data['somecollumn']; ?></sometag>
...
<?php
} else {
// user just opened first page
// generate links list as usual
...
foreach ($reciperow as $recipe) {
?>
<h2><?php echo $recipe['rectitle'];?></h2>
<p class="subhead"><?php echo $recipe['recsummary']; ?></p>
<?php
}
...
}
?>
Edit:
Is this how it is normally done for simple sites?
Depends.
If you has only one entity in datadabe, then there will be no arguments clash, id is identifier only for recipies, but if you intent to show also details for, f.e. ingredients, furniture and/or more, then you must add specificators.
Like, links will look like
<a href="?show=recipie&id=<?php echo $recipe['uniqno'];?>">
<a href="?show=ingredient&id=<?php echo $ingredients['id'];?>">
... and then data must be fetched and displayed correspondingly:
$id = ...;
if ($id)
switch ($_REQUEST['show']) {
case 'recipie':
// show recipie data
break;
case 'ingredient':
// show ingredient data
break;
case ...
default:
// show start page
}
But with addition of another entities yours .php file will grow. Another solution will be to add separate scripts for handling each entity:
// generate links list as usual
...
foreach ($reciperow as $recipe) { // look at `recipie.php` portion of link's href
?>
<h2><?php echo $recipe['rectitle'];?></h2>
<p class="subhead"><?php echo $recipe['recsummary']; ?></p>
<?php
}
And add recipie.php file in the same folder as base script with following contents:
<?php
$id = intval($_REQUEST['id']);
if ($id) { // user get here by clicking on link with id
$data = ... // fetch data from database
?>
<sometag>Some data from database:<?php echo $data['somecollumn']; ?></sometag>
...
<?php
} else {
?>
<h1 class="error">No recipie ID specified</h1>
<?php
}
<?
Further exploring will bring you to concepts of MVC and routing via human-friendly-links format, when links looks like /home, /recipie/12 and/or /recipie/?id=12 or even /recipie/12-cream-pie. But that's story for another time...

Enable/disable div according to guest/user entrance using php and jquery

I want to enable or disable a div according to the session if it starts with an user or a guest. I want to do something like this:
First, i will evaluate if it is user or not by doing this:
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
}
?>
then in jquery, i would like to say:
$('.box').click(function(){ // labBox appears when box is clicked
if(<?php $guest?>)
$("#LabBox").hide();
else
$("#LabBox").show();
});
Question: how can i use my php boolean var $guest to disable or hide some elements of my website?
Do i have to do two distinct php files? one for users and other for guest (e.g, home.php and home_guest.php)?
you could do the alternative such as
<script>
var guest = '<?php echo $guest; ?>';
$('.box').click(function(){ // labBox appears when box is clicked
if(guest === "true") {
$("#LabBox").hide();
} else {
$("#LabBox").show();
}
});
</script>
This would simply allow you to pass the PHP value to a Javascript variable, in order for you to use it within the onClick.
Remember: everything that reaches the client can be manipulated. Therefore, if you send an hidden element (say, an hidden <div>) any tech-savvy user can, and will, easily make them visible.
You MUST perform the checks about the login/guest status in your PHP script, and don't rely on jQuery to assemble the page at client side (hey, after all, the user may have disabled javascript altogether!)
You don't need two pages (eg: home.php and home_guest.php) to render different content based on the user level. Just use appropriately session/cookies and different echos.
Use a hidden input, populated by PHP, which jQuery can grab:
<?php
echo "<input type=hidden id=guestcheck value=$guest/>"
?>
if ("#guestcheck").val()) {
}
I personally like this method because it allows me to check the source when debugging to find out where any errors may be (for instance you can plainly see in the source when viewing the page whether or not GUEST is true)
It depends on contents of those files. If the only difference is visibility of the block, it's more reasonable to do the check inline.
<?php if (isset($_SESSION['idUser'])) { ?>
$('.box').click(function() { $("#LabBox").show(); }
<?php } ?>
Personally I would do it in the HTML rather than the JS file...
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$loggedin=true;
} else {
$loggedin=false;
}
?>
Then later on..
<?php if($loggedin===true){?>
<div>User is logged in</div>
<?php }else{?>
<div>Guest is viewing page</div>
<?php }?>
This means that the div for the user is not shown to the guest, whereas your currently solution only hides it from view (user could just use firebug/viewsource!
Why don't you just show/hide your div in the php depended on if they are a guest or not...
So...
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
}
if($guest===true){
echo "<div></div>";
}
else{
//dont echo div
}
?>
PHP / server-side:
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
// add #LabBox element from here to avoid junk/hidden elements for guests
}
?>
JQuery / client-side:
$('.box').click(function(){ // labBox appears when box is clicked
if (!<?php echo $guest?> && $('#LabBox').length > 0) {
$('#LabBox').show();
}
});
Then it is critical that any action requested by the user pass the "guest or not?" test before being granted from the server-side.

php search won't clear when javascript onclick is clicked

So this is what I have - A javascript onclick event that will parse json from my MySQL database data and display it when someone clicks on a seat.
var jsonData = <?php echo json_encode($array); ?>;
function displayInfoForDiv(i){
document.getElementById('fname').innerHTML = jsonData[i].first_name;
document.getElementById('lname').innerHTML = jsonData[i].last_name;
}
Output
<?php while ($row = mysql_fetch_array($sql)){ ?>
<p><span id="fname"><?php echo $row['first_name']; ?></span></p>
<p><span id="lname"><?php echo $row['last_name']; ?></span></p>
<?php } ?>
The PHP is for my search box when you try to look up a name - I'm using this
$sql = mysql_query("select * from people where first_name like '%$term%' OR last_name LIKE '%$term2%'");
So the problem I'm having is when I conduct a search for Matt, more then one result will show up. Say:
Matt
Hasselbeck
Matt
Hew
But if I use the onclick event and click on joe's seat, it will display like this:
Joe
Frill
Matt
Hew
So the problem is that the search results will remain when I trigger the onClick event but the first one will change.
My question is, is there a way when I click on a seat to clear the search results and only display the one but when I conduct a search to display the similar names.
I'm using the PHP and JS to call the same data because, the JS only has a range of floor, while the php is grabbing everything from the database.
Hopefully this is clear and thank you for any input.
You Have Two Issues going on here.
You are using the same value for the id attribute multiple times.
Your result setup is logically flawed
Solution to Issue 1
Change id attribute to class attribute
When you use document.getElementById in javascript it returns the first element with that id.
Which means that if you have multiple ids with the same value only the first element will be selected. So your function should be changed to the following
function displayInfoForDiv(i){
document.getElementsByClassName('fname')[i].innerHTML = jsonData[i].first_name;
document.getElementsByClassName('lname')[i].innerHTML = jsonData[i].last_name;
}
Solution to Issue 2
Use template for results
Wrap all results in a div tag
By wrapping results into a div tag you will be able to clear results by clearing the html for that div tag.
<div id='Results'>
<?php while ($row = mysql_fetch_array($sql)){ ?>
<p><span class="fname"><?php echo $row['first_name']; ?></span></p>
<p><span class="lname"><?php echo $row['last_name']; ?></span></p>
<?php } ?>
</div>
<script>
function clearResults()
{
document.getElementById('Results').innerHTML='';
}
</script>
To use a template for results I would recommend underscore.js
So a template for your needs would look like the following:
<script id='result-template' type="text/x-jquery-tmpl">
<p><span class="fname">${first_name}</span></p>
<p><span class="lname">${last_name}</span></p>
</script>
And to utilize the template you would do the following:
The code below assumes you have included underscore.js
function LoadResults(jsonData)
{
_.templateSettings = {
interpolate: /\$\{(.+?)\}/g
};
var output='',
resultDiv=document.getElementById('Results');
template= _.template(
document.getElementById('result-template').innerHTML
);
clearResults();
for(x in jsonData)
{
resultDiv.innerHTML+=template(jsonData[x]);
}
}

PHP and MySQL Image one click action script

I am currently doing a project, and I want to know if it's possible if I could click an image then it will send a query to the database. since I am doing a project about Online menu. where I will click the image then there'll be query to be sent in the database, and after that the customers order wil appear in the side of the screen. is this possible? if so how ?
You really have several options of how you want to do this. The most basic being to surround your image in a link tag like so:
<image />
You can then either handle the click with an actual refresh. Or, you can handle it with ajax if you don't want the page to refresh.
Do your work on another php page.
If you need to do this through ajax. Let's suppose you want to load the content sent from the server in the div 'itemdetails'. You can specify this as the image tag(using jquery:
<img src="url/of/image" onclick="$('#itemdetails').load('http://yoursiteurl/items?id=itemid')">
The best way of doing that for me is using jquery like this:
Javascript:
function orderedSomething(id) {
$.post("ajaxOrder.php",{ orderID:id,rand:Math.random() } ,function(response) {
if(response=='ok') {
$("#alert").fadeTo(250,0.1,function() {
$(this).html('Your order is coming.').fadeTo(150,1);
});
} else {
$("#alert").fadeTo(250,0.1,function() {
$(this).html(response).fadeTo(150,1);
});
}
});
}
The php file ajaxOrder:
<?php
if($_POST['orderID']) {
$res = $query('check stock'); //Assuming that there is no info related to your table
if(mysql_num_rows($res)>0) {
$query('insert DB'); //Assuming that there is no info related to your table
echo 'ok';
} else {
echo 'Your order is out of stock';
}
}
?>
So your html should be:
<div id="alert"></div>
<img src="images/ice-cream.gif" onClick="orderedSomething(<?=$iceId?>)" style="cursor:pointer" />

Categories