How to echo javascript code in php - 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.

Related

Reconciling Show/Hide JQuery Script into PHP

I currently have some php script that outputs results from a query. I would like to add at the end two buttons that will show/hide the final element, but am not sure how to do this.
The following is my php script:
while($result = mysqli_fetch_array($iname))
{
echo "<b>Event Name:</b> " .$result['EventName'];
echo "<br> ";
echo "<b>Location:</b> ".$result['Location'];
echo "<br>";
//this is where I would like to add my two buttons, that would show the "hidden" content when clicked
And here is what I have written in an HTML script, that I would like to reconcile into the PHP output:
<!DOCTYPE html>
<html>
<head>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js></script>
<script>
$(document).ready(function(){
$("#hidden").hide();
$("#hide").click(function(){
$("#hidden").hide(500);
});
$("#show").click(function(){
$("#hidden").show(500);
});
});
</script>
</head>
<body>
<button id="show">Show</button>
<button id="hide">Hide</button>
<p id="hidden">
Some Random Text that will be shown when the buttons are clicked
</p>
</body>
</html>
Any suggestions as to how this should be done?
How about if you get the number of result rows with $num_rows = mysql_num_rows($result);
Then, put a counter in your loop.
$counter = 1;
$theClass="";
while($result = mysqli_fetch_array($iname))
{
if ($counter == mysql_num_rows($result);){
$theClass="showHide";
}
echo "<div class='$theClass'>";
echo "<b>Event Name:</b> " .$result['EventName'];
echo "<br> ";
echo "<b>Location:</b> ".$result['Location'];
echo "<br>";
echo "</div>
$counter++;
}
Then, apply your javascript to the div whose class="showHide"

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
}

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.

How to use JQuery and PHP?

I am creating a PHP App and am using JQuery but have run into problems. For example, below is the code for a page i am writing, the alert() function calls when the pages loads but the second javascript Jquery code does not, I cannot see why one line works but the second does not?
help.php
<?php
echo "<script>";
echo "alert(\"Loaded\");";
echo "$(\"#newDiv\").draggable().resizable();";
echo "</script>";
echo "<div id=\"newDiv\">";
echo "</div>";
?>
The page calls the alert and creates the div but does not execute the jquery statement.
I think this may be due to have my page is structures and loaded. pages are loaded inside a div using Jquery and AJAX so the only page the user actually "loads" is an index.php page like so:
index.php
<html>
<head>
<title>BluePrintr Web Application.</title>
<link rel="stylesheet" type="text/css" href="public.css" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript" language="javascript" src="myLibs.js"></script>
</head>
<body>
<?php
echo "<div id=\"web_Page\">";
//////////////////////////////////////////////////////
echo "<div id=\"web_Header\">";
require("public/templates/header.php");
echo "</div>";
//////////////////////////////////////////////////////
echo "<div id=\"web_Menu\" class=\"horizontalcssmenu\">";
require("public/templates/menu.php");
echo "</div>";
//////////////////////////////////////////////////////
echo "<div id=\"web_Content\">";
echo "</div>";
//////////////////////////////////////////////////////
echo "<div id=\"web_Footer\">";
require("public/templates/footer.php");
echo "</div>";
echo "</div>";
?>
The menu loads and then any page selected from this menu is then loaded into the "#web_Content" div. So when the help.php page is selected from the menu, it injects the script into the div.
Can anyone see why the javascript code will not execute on help.php?
You need to wrap the jquery to initialize only after the page loads
<?php
echo "<script type='text/javascript'>";
echo "alert(\"Loaded\");";
echo "$(function(){$(\"#newDiv\").draggable().resizable();});";
echo "</script>";
echo "<div id=\"newDiv\">";
echo "</div>";
?>`
The $(function(){}); will cause the code to wait until after the page has been completely loaded.. I'm assuming you are also loading jQuery UI as you are using .draggable()?
Do this:
<script type='javascript'>
$(document).ready (function() {
alert('Hi');
// Other initialization
});
</script>
Also, just write all of that as HTML. Use PHP like this:
<html>
<body>
<?php if ($var == true) {?>
<p>Hello</p>
<?php } ?>
</body>
</html>
If $var is false, the page is blank. This makes things much more readable.
your javascript may be executing before the page has finished rendering in the browser
have a look at the jquery ready function for examples
http://api.jquery.com/ready/
As mentioned, you need to wrap your jQuery code inside $(document).ready().
You should stop doing it the way you are now and use a templating system, with a proper MVC architecture for serving your pages. It's just gonna be hell for you if you keep doing it this way. You should never have PHP outputting javascript code, this should be written by you in seperate files in a functional way and then included in your HTML file.
There is another good way like below:
$alert = <<<LABEL
<script>
$(document).ready (function() {
alert('Hi');
// Other initialization
});
</script>
LABEL;
echo $alert;

how to add script inside a php code?

How can I add script inside a php code? suppose i want to give an alert for a button click.. how can i do that??
You can just echo all the HTML as normal:
<?php
echo '<input type="button" onclick="alert(\'Clicky!\')"/>';
?>
<?php
echo"<script language='javascript'>
</script>
";
?>
You mean JavaScript? Just output it like anything else in the page:
<script type="text/javascript">
<?php echo "alert('message');"; ?>
</script>
If want PHP to generate a custom message for the alert dialog, then basically you want to write your JavaScript as usual in the HTML, but insert PHP echo statements in the middle of your JavaScript where you want the messages, like:
<script type="text/javascript">
alert('<?php echo $custom_message; ?>');
</script>
Or you could even do something like this:
<script type="text/javascript">
var alertMsg = '<?php echo $custom_message; ?>';
alert(alertMsg);
</script>
Basically, think about where in your JavaScript you want PHP to generate dynamic output and just put an echo statement there.
To avoid escaping lot of characters:
echo <<<MYSCRIPT
... script here...
MYSCRIPT;
or just turn off php parsing for a while:
?>
...your script here
<?php
You could use PHP's file_get_contents();
<?php
$script = file_get_contents('javascriptFile.js');
echo "<script>".$script."</script>";
?>
For more information on the function:
http://php.net/manual/en/function.file-get-contents.php
You mean you want to show a javascript alert when a button is clicked on a PHP generated page?
echo('<button type="button" onclick="alert(\'Alrt Text!\');">My Button</button>');
Would do that
You can insert script to HTML like in any other (non-PHP) page, PHP processes it like any other code:
<button id="butt">
→ Click ME! ←
</button>
<script>
document.getElementById("butt").onclick = function () {
alert("Message");
}
</script>
You can use onSOMETHING attributes:
<button onclick="alert('Message')">Button</button>
To generate message in PHP, use json_encode function (it can convert to JavaScript everything that can be expressed in JSON — arrays, objects, strings, …):
<?php $message = "Your message variable"; ?>
<button onclick="alert(<?=htmlspecialchars(json_encode($message), ENT_QUOTES)?>)">Click me!</button>
If you generate code for <script> tags, do NOT use htmlspecialchars or similar function:
<?php $var = "Test string"; ?>
<button id="butt">Button</button>
<script>
document.getElementById("butt").onclick = function () {
alert(<?=json_encode($var)?>);
}
</script>
You can generate whole JavaScript files, not only JavaScript embedded into HTML. You still have to name them with .php extension (like script.php). Just send the correct header.
script.php – The JavaScript file
<?php header("Content-Type: application/javascript"); /* This meant the file can be used in script tag */ ?>
<?php $var = "Message"; ?>
document.getElementById("butt").onclick = function () {
alert(<?=json_encode($var)?>);
}
index.html – Example page that uses script.php
<!doctype html>
<html lang=en>
<head>
<meta charset="utf-8">
<title>Page title</title>
</head>
<body>
<button id="butt">
BUTTON
</button>
<script src="script.js"></script>
</body>
</html>
Exactly the same way you add HTML tags. Echo it
One way to avoid accidentally including the same script twice is to implement a script management module in your templating system. The typical way to include a script is to use the SCRIPT tag in your HTML page.
<script type="text/javascript" src="menu_1.0.17.js"></script>
An alternative in PHP would be to create a function called insertScript.
<?php insertScript("menu.js") ?>
To add javascript inside a PHP code you can do this
<?php
echo "<script>alert('message');</script>";
?>
Better this
<?php
echo "<script src='myScript.js'></script>";
?>
And this for WordPress function.php file
<?php
$script= get_template_directory_uri() . '/myScript.js';
echo "<script src=".$script."></script>";
?>
In your php file you can do something like this :
<?
//Your php code
?>
<script type="text/javascript">
//Your javascript code
</script>
<?php //Your php code

Categories