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
Related
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>
I wanted to insert php on html5
i trying copy code from w3schools
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
</head>
<body>
<div id="result"> </div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("do_dropdown.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
my do_dropdown.php just select data from drop down list
but it doesn't show anything.
what do i miss?
the right thing to do, for my opinion
is to send your options data as JSON and to parse it with JS to required dropdown
for easy solution that will fit your situation, ill assume this is your PHP code:
//file name: do_dropdown.php
<?php
$options = [1,2,3,4,5];
echo '<select name="name">';
foreach $options as $option{
echo "<option value=$option>$option</option>";
}
echo '</select>';
?>
so you need to change your html file to PHP file (file.html -> file.php) and make sure you run on it PHP server (localhost as you are using right now)
<div id="result">
<?php
require_once "do_dropdown.php";
?>
</div>
there are much better solutions for this, but I guess your'e new in business so good luck :)
why don't you try this ?
I think, It should not create any problem even if you're using HTML5. NOTE :: it should be .php extension file
<html>
<body>
<?php
....your code
....from file <do_dropdown.php>
?>
</body>
</html>
you can also create a function and call it from here.
When I generate PHP within a file that is asynchronously loaded by jQuery, the text seems to jitter or flicker a little while the animation runs. This does not happen to the regular HTML in the requested file, only the content generated with PHP.
Just want some hints as to what can end the jitter.
Here is the jQuery in the main.php:
$(document).ready(function(){
var demo = $('#demo');
demo.hide();
$("button").click(function(){
demo.load('demo.php', function() {
demo.show('medium');
});
});
});
Here is the HTML and PHP in demo.php:
<p><?php echo "Hello World with PHP trough AJAX"; ?></p>
I’m really unsure where to begin. Should I just avoid using PHP in demo.php alltogether? Even so I'd really like to have to possibility to use PHP in scripts called trough AJAX.
As per request, here is the whole darn thing:
main.php:
<!DOCTYPE html>
<html>
<head>
<title>Testing Ajax</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<meta charset="utf-8" />
<script type="text/javascript" src="js/jquery-1.9.0.js"></script>
<script>
$(document).ready(function(){
var demo = $('#demo');
demo.hide();
$("button").click(function(){
demo.load('demo.php', function() {
demo.show('medium');
});
});
});
</script>
<style type="text/css">
#demo {background-color: MidnightBlue;color: white;padding: 0.1em 1em 1.5em 1.5em;}
#demo h1 {color: white;}
</style>
</head>
<body>
<section>
<article>
<h1>Ajax</h1>
<hr />
<button>Load External Content</button>
<div id="demo"></div>
</article>
</section>
</body>
</html>
(I like MidnightBlue better than CornflowerBlue...)
demo.php:
<h1>Ajax criex Hello World!</h1>
<p><?php echo "PHP also cries Hello World trough Ajax!"; ?></p>
Technically speaking, there is absolutely no difference between text generated with PHP versus text generated in ASP.net versus text contained in a .txt file versus text caused by typing on your keyboard -- it is all letters and numbers. Indeed, I would go as far to say that, examining text absent other clues, it is completely and 100% impossible to tell how it was created. No, you should not avoid PHP with AJAX.
Any "jittering" that you see is a product of some other issue, most likely related to browser performance - processor availability, free memory, current process memory consumption, extension activity/interference with page content, etc.
I don't know if this will help you. Probably not if the code shown above is really all your code.
But: Some time back I also had a jittering problem in animations when I loaded content via Ajax. The reason was: The loaded content contained Javascript code with other animation commands and then both animations interfered. Maybe this is also the case here.
In my test whilst trying to reproduce the "jitter" your code is producing an infinite ajax loop (View it in Web Console, your see) thats most likely your jitter effect:
Heres a basic PHP and AJAX example:
<?php
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest' && $_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['action'])){
$action = $_POST['action'];
switch($action){
case "hello":
echo "Hello World with PHP through AJAX";
break;
case "foobar":
echo "Hello Foobar";
break;
}
die;
}
?>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var action = this.value;
ajaxload('demo',action);
});
});
function ajaxload(placement,action){
$.post("./demo.php", { 'action': action },
function(data) {
$("#"+placement).hide().html(data).fadeIn('slow');
});
}
</script>
<button type="button" value="hello">Hello World</button>
<button type="button" value="foobar">Foobar</button>
<p id="demo"></p>
The PHP script doesn't seem to call dis(); function..Here it is:
PHP:
if (!$_SESSION['user']) {
echo"<script type='text/javascript'>dis();</script>";
}
JS:
<script type="text/javascript">
function dis() {
$(document).ready(function() {
$("#main_text_area").attr("disabled", "disabled");
});
}
When I place just $("#main_text_area").attr("disabled", "disabled"); it disables correctly...but I need to do it on a function call...Thanks for comments.
I'd recommend, instead of disabling the textarea, outputting the content of the <textarea> as static text.
Maybe something like this:
<?php if( !$_SESSION['user'] ): ?>
<div class="text">
<?php echo $textareaContents; ?>
</div>
<?php else: ?>
<textarea id="main_text_area">
<?php echo $textareaContents; ?>
</textarea>
<?php endif; ?>
The Javascript approach you're currently taking is trivially easy to get around.
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;