Im learning PHP, Html and twitter-bootstrap (v2.3.2). I'm trying to display a message depending on the value received by GET.
I have two alerts in different sections of the site and I want depending on the value received by GET display one or the other. not both.
i.e: http:localhost/test.php?load=lannister, should show the message: "A Lannister always pays his debts". however, the url: http:localhost/test.php?load=stark, should show the message: "you know nothing john snow". But I can not figure how to do this, I need a hand, I thought it could be done with an if-else, but I fail to understand how to do it at all. Any ideas?
Heres the code:
<?php session_start();?>
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<!-- Obtain Bootstrap style sheet from CDN (online service) so it doesn't have to be on my machine -->
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet" media="screen">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
window.setTimeout(function() {
$("#alert_message").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 2000);
</script>
<script type="text/javascript">
window.setTimeout(function() {
$("#alert_message2").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 2000);
</script>
</head>
<body>
<?php
$load = $_GET['load'];
switch ($load) {
case "stark":
$message="you know nothing john snow";
break;
case "lannister":
$message="A Lannister always pays his debts";
break;
}
?>
<?php
if ($load==='stark'){
echo "<div id=\"alert_message\" class=\"alert alert-error\">
<div id=\"alert_placeholder\" align=\"center\" style=\"color:#FFFFFF;font-size: 0.9em;\">".$message."</div>
</div>";
} else{
?>
<div class="container">
<div class="container">
<h1>Bootstrap CDN starter template using boostrapcdn.com</h1>
<p>Use this document as a way to quick start any new project.<br>
All you get is this message and a barebones HTML document.</p>
</div> <!-- /container -->
<?php
echo "<div id=\"alert_message2\" class=\"alert alert-error\">
<div align=\"center\" style=\"color:#FFFFFF;font-size: 0.85em;\" >".$message."</div>
</div>";
}?>
</div>
</body>
</html>
I know it's a silly question, but I've been thinking how to do it for hours without any success. Thanks in advance
You're correct in using a switch statement, but as #true stated in his comment, you should check to ensure the variable is set and not empty.
You could do that in long/short hand:
// long
if(isset($_GET['load']) && !empty($_GET['load'])) {
$load = $_GET['load'];
} else {
$load = null;
}
//short
$load = (isset($_GET['load']) && !empty($_GET['load'])) ? $_GET['load'] : null;
Since you set $load to null if it's not present/empty. You can test like this:
if($load == NULL) {
// message is error because neither stark/lannister selected
} else {
switch($load) {
case "stark":
//do start stuff here
break;
case "lannister":
// do lannister stuff here
break;
}
}
Now for the final part. This block of code:
if ($load==='stark'){
echo "<div id=\"alert_message\" class=\"alert alert-error\">
<div id=\"alert_placeholder\" align=\"center\" style=\"color:#FFFFFF;font-size: 0.9em;\">".$message."</div>
</div>";
}
Is not needed. (The if condition is not needed) As you already do the conditioning work in the switch statement to set the message that will be displayed in the alert box. Meaning you'd just have the echo somewhere in your markup!
echo "<div id=\"alert_message\" class=\"alert alert-error\">
<div id=\"alert_placeholder\" align=\"center\" style=\"color:#FFFFFF;font-size: 0.9em;\">".$message."</div>
</div>";
Try cleaning up the code a small amount to make life easier on you.
<?php if($_GET){
$load = isset($_GET['load']) ? $_GET['load'] : null;
}
if ($load == "stark") {
//ECHO
}
elseif ($load == "lannister") {
//echo
}
else {
//default
}
Related
I am trying to pass the ID of the clicked image to next page. When I developed my code, it didn't redirect me to the next page. When I click F12 and check the POST in network, it shows that the variable is passed correctly to the next page as shown in the attached image but it didn't redirect me to the next page. So now I know that the variable is passed and received correctly in the next page but I need what needed in my code to direct me to the next page,
Note: when I tried to put window.location.href = 'userevent.php'; it redirect me but without the variable and gives me error (Notice: Undefined index: clicked in)
Also when I use url: '#userevent.php.Action("delivery", "service")',, it gives me network status 403
this is my code:
<?php
session_start();
require "init.php";
login();
?>
<html>
<!--...-->
<head>
<meta charset="utf-8">
<title> Ghost </title>
<!-- <link rel="Stylesheet" href="css/style1.css">-->
<link rel="stylesheet" href="css/style2.css" media="screen" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script >
function myFunction(clicked) {
document.getElementById('test').innerHTML = clicked;
$.ajax({
type: "POST",
//url: '#userevent.php.Action("delivery", "service")',
url: 'userevent.php',
dataType:'json',
data: {"clicked": clicked},
success: function(data){
}
});
window.location.href = 'userevent.php';
}
</script>
</head>
<body>
<div class="sidenav">
Main Page
About Us
</div>
<div class="login-box">
<h1>Add Event</h1>
<div>
<p id="test"> </p>
<?php
// LOGIN USER
function login(){
global $con;
global $counter;
echo "<table align='center' >";
//$email = $mysqli->escape_string('');
$query="SELECT * FROM events ORDER BY ID ASC";
$result=mysqli_query($con,$query);
if ( $result->num_rows == 0 ) // User doesn't exist
echo "User with that ID doesn't exist!";
else { // User exists
$counter = 0;
$emptyArray = [];
while($row = $result->fetch_assoc())
{
$emptyArray[$counter]= $row["ID"];
if($counter == 0)
{
echo '<tr>';
}
echo '<td><img id=' . $row["ID"]. ' onClick="myFunction(this.id)" src="images/' . $row["photo"]. '" width="250px" height= "250px" alt="Avatar" >
<h1 id = "GFG_DOWN" style =
"color:white;text-align:center; font-size: 20px; font-weight: bold;"> '.$emptyArray[$counter].'
</h1> </td>';
$counter++;
if($counter == 3)
{
echo "</tr>";
$counter = 0;
}
}
}
}
mysqli_close($con);
?>
and this is the code in the second page:
<div class='textbox'>
<label> ID: ".$_POST['clicked']."</label>
</div>
The entire point of Ajax is that that request is made with JavaScript and the response is handled by JavaScript without navigating to a new page.
If you want to make a POST request and navigate to the resulting page, then use a <form>
window.location.href = 'userevent.php';
it redirect me but without the variable
Assigning a URL to location.href triggers browser navigation (with a GET request) to that URL.
It is a completely different request to the Ajax request so it doesn't have the data from that request.
Again: Use a form for this.
I read the data from database and I get the clicked id of the images.
Put the data you want to send in a submit button instead.
<form method="POST" action="userevent.php">
<?php while($row = $result->fetch_assoc()) ?>
<button name="clicked" value="<?php echo htmlspecialchars($row["ID"]); ?>">
<img src="images/<?php echo htmlspecialchars($row["photo"]); ?> alt="Put useful and unique alt text so people know what they are selecting if they can't see the image">
</button>
<?php } ?>
</form>
I think you are better off making a small form, since you want to send the user to a new page when clicking.
<?php while($row = $result->fetch_assoc()) ?>
<form action="userevent.php" method="POST">
<input type="hidden" name="clicked" value="$row["ID"]">
<img src="images/{{ $row['photo'] }}" class="img">
</form>
<?php } ?>
$('.img').click(function() {
this.form.submit();
});
*Edited to reflect your current edits.
In following function if the input is blue then it is giving result as: "header content goes here Your favorite color is blue!" whereas it is supposed to give- "Your favorite color is blue!", please help me correcting it. If input is red then it is ending statement here as: "header content goes here" which is correct.
Please forgive me if I am asking silly question as I am new to PHP and I don't know if it is ok or not to use function as variable in switch case.
test1.php
<?php
function header2() { ?>
header content goes here
<?php }
$good =header2();
$Input2 = $_POST['input'];
switch ($Input2) {
case "red":
echo $good;
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
main.js
$('[id=stringone]').click(function(){
var string =$('[id=stringotherone]').val();
$.post('test1.php',{input: string}, function(data){
$('[id=stringotherthanone]').text(data);
});
});
test.php
<! doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/hwcb.css">
</head>
<body>
<input type="button" value="Go" id="stringone">
<input type="text" id="stringotherone"/>
<p><div id="stringotherthanone"></div></p>
<script src="jquery.js"></script>
<script src="js/css.js"></script>
<script src="main.js"></script>
</body>
</html>
You need to return in the function otherwise it outputs when the function is called.
Example: https://3v4l.org/1Ptml vs. https://3v4l.org/ug778
$good =header2(); is outputting the header content goes here, not the echo $good; in the switch. That actually does nothing because that variable is empty.
Change
<?php
function header2() { ?>
header content goes here
<?php }
to
<?php
function header2() {
return 'header content goes here';
}
I have this problem: I can't find out how to hide a div that appears just when session begins. So I a have a X button for closing, and when the page is refreshed, the div appears again! But I don't want to stop the session.
My code:
<div id="got-points" style="display:<?php echo (isset($customer) && !empty($customer) && isset($customer['customer']) && !empty($customer['customer'])) ? 'block' : 'none'; ?>"> // Checks if session is active
<div class="got-points-bg" style="display: visible;">
<div class="got-points-box">
<img class="got-points-close" src="<?php echo base_url();?>static/images/i8.png" /> //Close Button
My text here
</div>
</div>
</div>
And js
<script>
$(document).ready(
function() {
$(".got-points-close").click(function() {
$(".got-points-bg").hide("fast");
});
});
</script>
If it is on refresh then it is easy; just do it in the PHP session; like this:
HTML:
<div id="got-points" style="display:<?php echo (isset($customer) && !empty($customer) && isset($customer['customer']) && !empty($customer['customer']) && empty($_SESSION['first_load'])) ? 'block' : 'none'; ?>"> // Checks if session is active
<div class="got-points-bg" style="display: visible;">
<div class="got-points-box">
<img class="got-points-close" src="<?php echo base_url();?>static/images/i8.png" /> //Close Button
My text here
</div>
</div>
</div>
and in your PHP before then (like on login/session start) - this will obviously need significant editing since you haven't included your PHP I can't guess it very well, but this should provide a starting point:
<?php
//load user check pseudo code
if !empty($_SESSION[user]) and whatever other checks... {
$_SESSION['first_load'] = False; //important line number 2
}
//login pseudo code to demonstrate placement within your code
if user & pass = valid {
$_SESSION['first_load'] = True; //important line number one
}
That is assuming you want th div output but not displayed on subsequent loads.
Interesting question, how about something like this?
<?php
if(isset($_SESSION['variable'])){
sleep(3); /* Duration(in seconds) div is displayed for */
echo
"<script>
$( document ).ready(function() {
$(".got-points-bg").hide("fast");
});
</script>";
}
?>
try this
<?php error_reporting(0); session_start(); if(empty($_SESSION['user'])) echo "<div id='togglediv'> My text here </div>"; ?>
hope it will work
I don't know if this is possible but I want to know if I can set the background color of a page depending on an if/else statement?
What I want is that if the if statement is met, then I want the background color of the body to be white, if the else statement is met where it contains a div, then I want the background color of the body to be grey.
Can this be done?
<?php
if (page()){
//all the code in the page
}else{
?>
<div class="boxed">
</div>
<?php
}
?>
UPDATE:
<?php
if (page()){
?>
<body class="bodypage <?php echo page()? "color1":"color2" ?>" >
</body>
<?php
}else{
<div class="boxed">
Continue with Current Assessment
</div>
}
?>
Yes it can be. How about you use a predefined class that have the background color you need:
.color1 {
background-color:red;
}
.color2 {
background-color:yellow;
}
<body class="boxed <?php echo page()? "color1":"color2" ?>" >
</body>
UPDATE:
<body class="bodypage <?php echo page()? "color1":"color2" ?>" >
<?php if (page()){?>
... all the page code
<?php else {?>
<div class="boxed">
Continue with Current Assessment
</div>
?>
A zillion ways to do this.
PHP:
$bodyClass = $condition ? 'foo' : 'bar';
...
echo <<< END_HTML
<body class="$bodyClass">
<!-- stuff here -->
</body>
END_HTML;
CSS:
body.foo { background-color:#fff; }
body.bar { background-color:#888; }
..is one way to do it.
Cheers
Try this
<body <?php if(true) {echo('style="background:red"'); } else { echo('style="background:white"'); } ?> >
</body>
You can do it this way using javascript & jQuery:
<script>
$(document).ready(function(condition){
if (cond) {
$(body).css("background-color","red");
} else {
$(body).css("background-color","blue");
}
});
</script>
Or in php you can just echo that code, with some changes.
Try to minimize the php influence on your design. (CSS for design, html for semantics, php for structure and javascript for interaction)
To accomplish this I recommend sending a hidden input to the browser containing a value:
if(statement) {
$color = '#ffffff';
} else {
$color = '#ff0000';
}
echo '<input id="pageColor" type="hidden" value="'.$color.'" />';
Now do the following with (for example) jquery:
$(document).ready(function() {
//change bg color based on input value
$('body').css('background-color', $('#pageColor').val());
});
Yep, you can do this.
One of the most elegant ways:
PHP part:
<?php
$style = 'background:'; # property
$given = page() ? 'red;' : 'black;'; # Ternary operator
$style .= $given; # Concatenate two strings
?>
HTML part:
<div class="boxed" style='<?php echo $style; ?>'></div>
Also you can create special CSS classes with predefined variety of CSS properties:
PHP part:
<?php
$class = page() ? 'first' : 'second'; # CSS classes defined in your stylesheet.
?>
HTML part:
<div class="boxed <?php echo $class;?>"></div>
And here you go. That's just a quick demonstration, you can replace this with you parameters.
sorry if the title is a little.. vague i couldnt pin it down.
So i am developing a friend request system which works i guess similar in concept to facebook. So you get a request and it lists them without a page reload.
However i get the div 'refreshing' or so i think i cant test the php which is where i have a problem, i will post the relevent code and files below.
It may look a little long winded but it shouldnt be too bad in reality. My php code should keep executing the query which is looking at the database in the updateFriendBox.php however it doesnt seem to be doing this. My code may be messy as well so I apologise.
myaccount.php
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function refreshDiv()
{
$.get('updateFriendBox.php', function(data){$('#refresh').html(data);});
}
$(function()
{
refreshDiv();
setInterval(refreshDiv, 5000);
});
function box(x){
if($('#'+x).is(":hidden")){
$('#'+x).slideDown(200);
} else {
$('#'+x).hide();
}
}
</script>
<?php
$addBox = '<div style="display:inline; padding:5px;">
Show/Hide Friend Requests
</div>';
// a bit further down in the code where its all called:
<? echo $addBox; ?></span>
<div class="friendSlide" id="fRequ" style="height:240px; overflow:auto;">Your friend requests: <br />
<div id="refresh"> <?php // this is where the refresh call is ?>
</div>
</center>
</div>
</div>
</div>
updateFriendBox.php:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function acceptFriendRequest(x) {
var url = "friendParse.php";
$.post(url,{ request: "acceptFriend", reqID: x}, function(data){
$("#req"+x).html(data).show().fadeOut(5000);
});
}
function denyFriendRequest(x) {
var url = "friendParse.php";
$.post(url,{ request: "denyFriend", reqID: x}, function(data){
$("#req"+x).html(data).show().fadeOut(5000);
});
}
</script>
</head>
<body>
<?php
include 'dbc.php';
$sql = "SELECT * FROM friendRecu WHERE mem2='" . $_SESSION['user_id'] . "' ORDER BY id ASC LIMIT 10";
$query = mysql_query($sql)or die(mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1) {
echo "No friend requests";
} else {
while($row = mysql_fetch_array($query)){
$requestID = $row['id'];
$req = $row['mem1'];
$sqlName = mysql_query("SELECT full_name FROM users WHERE id='$req'");
while($row = mysql_fetch_array($sqlName)){
$requesterName = $row['full_name'];
}
echo '<hr /><table width="100%", cellpadding="5"><tr><td width="17%" align="left"><div style="overflow:hidden; height:50px; color:white;"></div></td> <td width="83%">' . $requesterName . ' added you as a friend
<span id="req' . $requestID . '">
Accept
||
Deny
</span></td></tr>
</table>';
}
}
?>
I think you are having a problem because your updateFriendBox.php is returning too much. Remove all that inline JS code, place it in an include file, and include it from myaccount.php. You also shouldn't have <head> and <body> sections in your updateFriendBox.php file.
The ajax call here doesn't create a whole new page, you're getting additional HTML to add to the original page.
So the only thing you should have there is your SQL query, the loop, and your HTML output for each data row.