PHP Switch Case not ending statement after "break;" - php

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';
}

Related

Assign the text of an element as a php variable

i have a text inside an element. This text will changed according to a jQuery. As it changes, I need to pull that text as a php variable. This variable will be used later in the same document.
<div id="divId">sometext<div>
now, I want to assign a php code to assign "sometext" as the variable
I need the below;
<div id="divId">
sometext
<?php
$variable = (get text from "divId");
?>
<div>
then I can use it somewhere else like
<div>
<?php
if($variable == "sometext")
{
echo ($variable);
}
?>
<div>
I need help on the (get text from "divId")part
You cant do with PHP. please use javascript or jquery
please find way of jquery
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var getDivValue = $('#divId').html();
if(getDivValue == 'sometext'){
$('#divId').html('updateText');
}else if(getDivValue == 'other'){
$('#divId').html('updateTextTwo');
}
});
</script>
</head>
<body>
<div id="divId">sometext</div>
</body>
</html>

Show specific alert, depending on the value of GET in php

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
}

How to echo javascript code in php

I am having a problem with how to echo javascript in php. I have a form which on submit will execute itself and echo some text and will redirect to a page in 5secs. I am currently echoing this:
header("Refresh: 5;url=index2.php?ID=".$objResult["ID"]."");
echo '<html>';
echo '<head>';
echo '<title>Klant toevoegen</title>';
echo '<link rel="stylesheet" href="style.css" type="text/css" media="screen" />';
echo '</head>';
echo '<body>';
echo '<fieldset>';
echo ''.$Naam.' is added to the database, u will be redirected in a couple of seconds.<br><br>';
echo '</fieldset>';
echo '</body>';
echo '</html>';
The javascript I have is a countdown which counts down from 5 to 1. The code is this:
<script>
var countdownFrom = 5; // number of seconds
var countdownwin;
var stp;
function CountDownStart() {
stp = setInterval("CountDownTimer('CountDownTime')",1000)
}
function CountDownTimer(id)
{
if (countdownFrom==0) {clearInterval(stp); window.close(); }
else {
var x
var cntText = "Closing in "+countdownFrom+" seconds";
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = cntText; }
else if (document.all)
{
x = document.all[id];
x.innerHTML = cntText; }
}
countdownFrom--
}
</script>
<title>Untitled</title>
</head>
<body onload="CountDownStart()">
<Div id="CountDownTime"></div>
</body>
Now I would like to echo this countdown script to replace the <fieldset> in the html. I have tried several things like just add the whole code in 1 echo ''; and I tried to echo all the lines seperately but with both it crashes my whole script. If anyone knows how to do this it would be great!
I Wouldn't write all those echo's, instead, leave all the HTML and JS outside the PHP block
<?php
some php code
?>
HTML AND JS
<?php
More php if required
?>
And use
<?=$Naam?>
To inject your values where required
Alternatively you should look into template engines
Try to use
echo <<<EOT
/* some text here */
EOT;
You can put the script in a separate .js file and echo the script tag:
<? echo "<script type='text/javascript' src='path/to/script.js' ></script> ?>
Don't forget to remove any HTML tags from the JS file, like <body>, <head>, etc.

set background color for body depending on if/else statement

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.

Following a Codeigniter/Ajax/Jquery tutorial: Can't seem to debug what I'm doing wrong

I'm following the tutorial here:
http://www.jotorres.com/2012/01/using-jquery-and-ajax-with-codeigniter/
For my view, I have:
<script type="text/javascript" src="<?php echo jquery ?>"></script>
<button type="button" name="getdata" id="getdata">Get Data.</button>
<div id="result_table">
</div>
<script type="text/javascript" language="javascript">
$('#getdata').click(function(){
$.ajax({
url: "<?php echo base_url().'users/get_all_users';?>",
type:'POST',
dataType: 'json',
success: function(output_string){
$("#result_table").append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
</script>
The header and footer are predominantly links to other pages on the website but the relevant sections of the header and beginning are:
<!DOCTYPE html>
<!-- Website template by Jeremiah Tantongco, jtantongco#gmail.com -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $title ?> </title>
<link rel="stylesheet" href="<?php echo template ?>" type="text/css" />
<link rel="stylesheet" href="<?php echo display_elements ?>" type="text/css" />
</head>
Note: template and display_elements are variables pointing to css files somewhere on the server declared in config/constants
Note: jquery is a variable declared in config/constants that points to the newest jquery file on the server. It is the newest developer version available.
for controller methods:
public function test(){
$this->renderTemp_noData('users/test', 'Test page');
}
public function get_all_users(){
$query = $this->db->get('users');
if($query->num_rows > 0){
$header = false;
$output_string = "";
$output_string .= "<table border='1'>\n";
foreach ($query->result() as $row){
$output_string .= "<tr>\n";
$output_string .= "<th>{" . $row->uid ."}</th>\n";
$output_string .= "</tr>\n";
}
$output_string .= "</table>\n";
}
else{
$output_string = "There are no results";
}
//echo $output_string;
echo json_encode($output_string);
}
public function renderTemp_noData($page, $title) {
$data['title'] = $title;
$accountType = $this->session->userdata('aid');
switch ($accountType) {
case 0:
$this->load->view('templates/LI_header', $data);
$this->load->view($page);
$this->load->view('templates/LI_footer');
break;
case 1:
$this->load->view('templates/LI_header_role1',$data);
$this->load->view($page);
$this->load->view('templates/LI_footer_role1');
break;
case 2:
$this->load->view('templates/LI_header_role2',$data);
$this->load->view($page);
$this->load->view('templates/LI_footer_role2');
break;
case 3:
$this->load->view('templates/LI_header_role3',$data);
$this->load->view($page);
$this->load->view('templates/LI_footer_role3');
break;
default:
redirect('/sessions/log_in/','refresh');
}
}
When I go to the page with the Get Data button, I press it and nothing happens. So if anyone knows how to expose the error message that would be great. Also, When I test to see output for get_all_users, this is what I get:
"<table border='1'>\n<tr>\n<th>{1}<\/th>\n<\/tr>\n<tr>\n<th>{2}<\/th>\n<\/tr>\n<tr>\n<th>{3}<\/th>\n<\/tr>\n<tr>\n<th>{4}<\/th>\n<\/tr>\n<tr>\n<th>{5}<\/th>\n<\/tr>\n<tr>\n<th>{6}<\/th>\n<\/tr>\n<tr>\n<th>{7}<\/th>\n<\/tr>\n<tr>\n<th>{8}<\/th>\n<\/tr>\n<tr>\n<th>{9}<\/th>\n<\/tr>\n<tr>\n<th>{10}<\/th>\n<\/tr>\n<tr>\n<th>{12}<\/th>\n<\/tr>\n<tr>\n<th>{13}<\/th>\n<\/tr>\n<tr>\n<th>{14}<\/th>\n<\/tr>\n<tr>\n<th>{15}<\/th>\n<\/tr>\n<tr>\n<th>{16}<\/th>\n<\/tr>\n<tr>\n<th>{17}<\/th>\n<\/tr>\n<tr>\n<th>{18}<\/th>\n<\/tr>\n<\/table>\n"
Is JSON supposed to look this way? My gut says no but this is the first time I've ever used JSON, Jquery, and AJAX. Also, The numerical values are correct. Looking at my database, there are only UIDs 1-18 with no 11.
Your get_all_users() function adds HTML to your $output_string, which you are then json_encoding. That's not quite how JSON works. Replace with:
public function get_all_users() {
$this->output->set_content_type('text/javascript; charset=UTF-8');
$query = $this->db->get('users');
echo json_encode($query->result());
}
That said, your database calls should live in a model, not your controller.

Categories