Add JavaScript function to wordpress theme - javascript

A plugin developer who developed a comments-plugin that I use has instructed me to add the following JavaScript:
function WPACLoadMoreComments() {
window.WPACLoadMoreCount = window.WPACLoadMoreCount || 1;
var url = (new Uri(location.href)).replaceQueryParam('WPACTake', window.WPACLoadMoreCount * 20).toString();
if (WPAC.LoadComments(url, {updateUrl: false})) {
window.WPACLoadMoreCount++;
}
}
I assume he meant to put it in functions.php but the site doesn't load when I insert this code. I tried to inset it at the end, I tried to wrap it with
<?php
the function...
?>
How do I do that correctly?

You need to add the code to a javascript file and enqueue it in functions.php, or echo it via an action hook.
There's a section about including JavaScript right in the codex that's worth a read.

add below code into your functions.php file
function comment_script(){
$html = "<script type='text/javascript'>
function WPACLoadMoreComments() {
window.WPACLoadMoreCount = window.WPACLoadMoreCount || 1;
var url = (new Uri(location.href)).replaceQueryParam('WPACTake', window.WPACLoadMoreCount * 20).toString();
if (WPAC.LoadComments(url, {updateUrl: false})) {
window.WPACLoadMoreCount++;
}
}
</script>";
echo $html;
}
add_action('wp_footer','comment_script');

This is a Javascript function, not a PHP function. This means that you need to do the following:
<?php
// Your existing PHP code here
?>
<script>
function WPACLoadMoreComments() {
window.WPACLoadMoreCount = window.WPACLoadMoreCount || 1;
var url = (new Uri(location.href)).replaceQueryParam('WPACTake', window.WPACLoadMoreCount * 20).toString();
if (WPAC.LoadComments(url, {updateUrl: false})) {
window.WPACLoadMoreCount++;
}
}
</script>
<?php
//Your remaining PHP code
?>
Another possibility is to do it this way:
<?php
echo "<script>";
echo " function WPACLoadMoreComments() {";
echo " window.WPACLoadMoreCount = window.WPACLoadMoreCount || 1;";
echo "var url = (new Uri(location.href)).replaceQueryParam('WPACTake', window.WPACLoadMoreCount * 20).toString();"
echo " if (WPAC.LoadComments(url, {updateUrl: false})) {";
echo " window.WPACLoadMoreCount++;";
echo " }";
echo "}";
echo "</script>";
?>
The reason we're doing it this way is that Javascript is not executed on the server but on the user's browser (client side). Thus, there is no need to put the Javascript in <?php ?> tags, because you do not want it to be executed as PHP code. Since it will be executed by the browser, this means you need this code to appear in the HTML document loaded by the browser, and hence you should use echo or write it within <script> tags outside the <?php ?>
Performance-wise, it is always better to put Javascript code at the end of your page. This is to make sure that any possible lags, caused by the JS code while a user's browser is loading your page, do not affect the rendering of the page.

Put it in the functions.php or footer.php file somewhere outside <?php ?> and wrap it into <script type="text/javascript">Your function here...</script>

Related

How to create alert function in php?

i want insert user in db mysql, i have a controller php, im validate if user exist in db through a function, then if or not exist i want show alert function an redirect to php page, for that im using:
<?php
if(dao::existUser($user)) {
echo "<script type=\"text/javascript\">\n";
echo "alert('user exist!');\n";
echo "window.location = ('../insertUser.php');\n";
echo "</script>";
}
this function works!! but
i want to encapsulate the function in a method to later call it
example:
<?php
class Utils {
static function responseText($message, $url) {
echo "<script type=\"text/javascript\">\n";
echo "alert('"+$message+"');\n";
echo "window.location = ('"+$url+"');\n";
echo "</script>";
}
}
then, in my controller:
<?php
if(dao::existUser($user)) {
Utils::responseText("user exist",'../insertUser.php');
}
but not work, and after call responseText, my page goes blank
I don't know what is wrong ( likely a quoting issue ), but I would suggest using a HEREDOC style for this and return the text not output the HTML from the class by itself. Latter it could be hard to track where this output is coming from by looking just in the class that calls it. By doing echo Utills::.. you'll be able to easily see it's outputting something, whiteout having to look into what the class does.
So like this.
<?php
class Utils {
static function responseText($message, $url) {
return <<<HTML
<script type="text/javascript">
alert('$message');
window.location = '$url';
</script>
HTML; //nothing can go here no space ( before or after ) and not even this comment, nothing but HTML; litterally
}
}
echo Utils::responseText("user exist",'../insertUser.php');
HEREDOCs are a way of doing a text block without using any quotes, beware of the note i put in comments... In this case it makes the Javascript string so much more simple when you don't have to manage quote usage.
Another suggestion for this class if it is to be a collection of static methods, you can make it where it can't be instantiated ( created using new class() ) Like this
<?php
class Utils {
private function __construct(){} //no instantion
private function __clone(){} //no cloning
This way you don't accidentally do $U = new Utils(); $U->responseText(..) It's a little thing but it will insure all the methods of this class stay static. It's just a design thing I like to do, on singletons and static classes
UPDATE your issue is you are using the + to concat in PHP where you should be using the . The + is good for Javascript not so much for PHP
And the way you have it with " double quotes concat is unnecessary, instead of
echo "alert('"+$message+"');\n";
Try
echo "alert('$message');\n";
If i understand you properly bind javascript to php.
<?php
$script = '<script type="text/javascript">';
$script .= 'function showAlert(){';
$script .= 'alert("Hello World.");';
$script .= '}';
$script .= '</script>';
echo $script;
?>
Than after page has loaded you can call it !
<script type="text/javascript">
window.onload = function () {
showAlert();
}
</script>

How to get a file name from a directory using php and javascript

I'm trying to update an old flash gallery site of mine using php. I'm wondering how I can get a file name randomly from the folder that stores all of the flashs after the original flash has been middle mouse clicked. I'm new to php and I feel as if I have some things mixed up and I have gaps in my knowledge.
HTML
<?php include 'header.php'; ?>
<div id="flash-container">
<object id="flash-content" data="swfs/sunshine.swf" type="application/x-shockwave-flash"></object>
</div>
<?php include 'footer.php'; ?>
PHP
<?php
function random_flash($dir = 'swfs')
{
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
?>
Javascript
$(document).ready(function () {
$("#flash-content").on('click', function (e) {
$.ajax({
type: "GET"
, url: "flash.php"
, data: {
fileName: "$file"
}
}).done(function (msg) {
alert("Data Saved: " + msg);
});
if (e.which == 2) {
e.preventDefault();
flash - container.innerHTML = '<object id="flashcontent" data="' + $file + '">' + '<param name="movie" type="application/x-shockwave-flash">' + '</object>';
}
});
});
I think there are some error on your code.
If you call php, even in a javascript code ... you need to use <?php and ?>.
On your javascript code, I can see $file. Okay, but what is it ?
Should be <?php echo $file; ?> no ?
And in your JS code : flash - container.innerHTML
What is the object flash ? You can't substract object like this :) (Typo error ?)
So:
On your html web page randered, open the Console Editor and check if tehre is any error.
Open the source code of the page and check if the html/javascript seems good. If you are php error -> check the php code.
You can also and somewhere a <?php echo $file; ?> or <?php echo random_flash(); ?> to check if the value return is a file and the expected value.

Serve Javascript with PHP: Return/Echo URL/URI

EDIT: Missed the echo statement!
EDIT2: Added missing paranthesis!
EDIT3: Found the solution. See below!
What I am trying to achieve is this:
Dynamically create a Javascript-file with PHP
Serve Javascript-file as .js as embeddable Javascript on different URLs
Dynamically add Page Name and Page URL information inside the JS to be used in Javascript
Currently I do the following:
code.php
<?php header("Content-type: application/x-javascript"); ?>
/*
<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ;?>
*/
/*
<?php
$func = new Functions;
echo $func->getPageURL();
echo $func->getPageName();
?>
*/
var fred;
...
class.functions.php
<?php
class Functions {
function getPageURL() {
$isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");
$port = (isset($_SERVER["SERVER_PORT"]) && ((!$isHTTPS && $_SERVER["SERVER_PORT"] != "80") || ($isHTTPS && $_SERVER["SERVER_PORT"] != "443")));
$port = ($port) ? ':'.$_SERVER["SERVER_PORT"] : '';
$data = ($isHTTPS ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].$port.$_SERVER["REQUEST_URI"];
return $data;
}
function getPageName() {
$data = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
return $data;
}
}
Whenever someone triggers my script-embed code I route them to my code.php. Example:
<script src="//servingdomain/dynamic/123.js"></script>
Now, my code.php does a great job, but returns me this:
/*
servingdomain/dynamic/123.js
*/
/*
https://servingdomain/dynamic/123.js
index.php
*/
var fred;
...
Unfortunately my getPageURL und getPageName are not executed properly, but I am failing to understand why.
I am aiming to get this as output:
/*
servingdomain/dynamic/123.js
*/
/*
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
*/
var fred;
...
How should I takle this problem and get this working correctly either by clean code or dirty workaround ... I am aware of window.location.pathname and window.location.href in Javascript, but I need those to be passed in PHP, since I need to reuse this information to generate dynamic code in code.php.
Solution
Using $_SERVER['HTTP_REFERER'] gives correct referrer and running that through
<?php
echo $_SERVER['HTTP_REFERER'];
$func = new Functions;
echo $func->getPageTitle($_SERVER['HTTP_REFERER']);
?>
class.functions.php
function getPageTitle($url){
$str = file_get_contents($url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Output
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
<?php
$func = new Functions;
$purl = $func->getPageURL()."\n";//use ()
$pname = $func->getPageName();
echo $purl;
echo $pname;
?>
The PHP code is executed just fine, but it just doesn't have any result. You need to write out the values to the file:
<?php header("Content-type: application/x-javascript"); ?>
/*
<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ;?>
*/
/*
<?php
$func = new Functions;
$purl = $func->getPageURL;
$pname = $func->getPageName;
printf("%s\n", $purl);
printf("%s\n", $pname);
?>
*/
var fred;
...
This will write the values of those variables to the javascript file.
Note that if you want to use these values in the javascript code, you need to assign them to a javascript variable like this, outside of javascript comments:
printf("var pageName='%s'\n", $pname);
That way, you can use pageName in your javascript.
Solution
Using $_SERVER['HTTP_REFERER'] gives correct referrer
<?php
echo $_SERVER['HTTP_REFERER'];
$func = new Functions;
echo $func->getPageTitle($_SERVER['HTTP_REFERER']);
?>
Running that through this function
class.functions.php
function getPageTitle($url){
$str = file_get_contents($url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Output
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)

Re-execute a PHP script in a JavaScript function

I wrote a code to re-read a content of a file (on the server) every time the file is modified. The scenario is like this:
- The webpage is loaded
- If the file (on the server) is newer than the starting time of the page (the time when the webpage was started), the content of the file is read
- If the file is modified later, the content must be read again by PHP script
I tried this using EventSource. Here is the code for the browser:
<html>
<head>
<?php
$startTime = time();
$flag = 0;
?>
<script type="text/javascript" language="javascript">
lastFileTime = <?php echo $startTime; ?>;
var fileTime;
if(typeof(EventSource) !== "undefined") {
var source=new EventSource("getFileTime.php");
source.onmessage = function(event) {
fileTime = parseInt(event.data);
if (fileTime > lastFileTime) {
readFile();
lastFileTime = fileTime;
}
};
}
else {
alert("Sorry, your browser does not support server-sent events.");
}
function readFile() {
<?php
$fid = fopen("file.bin", "rb");
... // Read the content of the file
$flag = $flag + 1;
?>
... // Transfer the content of the file to JavaScript variables
flag = <?php echo $flag; ?>;
}
</script>
</head>
<body>
...
</body>
</html>
And here is the server-side code (getFileTime.php):
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$filetime = filemtime("file.bin");
echo "data: {$filetime}\n\n";
flush();
?>
When I start the webpage and created file.bin afterwards, readFile() is called for the first time (I checked the value flag = 1. But then, if I modified file.bin again, obviously readFile() is not called. I checked the content of the file; it's still from the previous file, and also flag is still 1. It seems that a PHP script in a JavaScript function can only be called once. How to re-execute the PHP script in a JavaScript function?
Your PHP script needs to remain active, sending new events to the client when something changes:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$lastFiletime = null;
while (true) {
$filetime = filemtime("file.bin");
if ($filetime != $lastFiletime) {
echo "data: {$filetime}\n\n";
$lastFiletime = $filetime;
flush();
}
}

Codeigniter: How to include javascript files

Hello I just started working with CodeIgniter framework. My current directory structure is
Demo(Project name)
+System
+Application
-Controllers
demo.php
+Model
-Views
view_demo.php
-Js
ajax.js
jquery.js
Please tell me how to include .js files in view_demo.php.
Thanks
Raj
You need to use the base_url() to include the javascript file in your VIEW.
So, in the view_demo.php file:
<script type="text/javascript" src="<?=base_url()?>js/jquery.js" ></script>
<script type="text/javascript" src="<?=base_url()?>js/ajax.js" ></script>
You will need the URL helper loaded. To load the helper you need to put on your demo.php controller:
$this->load->helper('url');
You can also autoload on \config\autoload.php on the helpers array.
More info about base_url(): http://www.codeigniter.com/user_guide/helpers/url_helper.html#base_url
https://codeigniter.com/user_guide/general/styleguide.html#short-open-tags
You wouldn't include JS files within the PHP, they would be output as script tags within the HTML you produce which you may be producing as output from the PHP script.
As far as I know, there is no built in CodeIginiter function to include this output like there is for CSS using the link_tag() function provided by CI. I've added a function called script_tag() to the system/helpers/html_helper.php file from CI. The function is:
if ( ! function_exists('script_tag')) {
function script_tag($src = '', $language = 'javascript', $type = 'text/javascript', $index_page = FALSE)
{
$CI =& get_instance();
$script = '<scr'.'ipt';
if (is_array($src)) {
foreach ($src as $k=>$v) {
if ($k == 'src' AND strpos($v, '://') === FALSE) {
if ($index_page === TRUE) {
$script .= ' src="'.$CI->config->site_url($v).'"';
}
else {
$script .= ' src="'.$CI->config->slash_item('base_url').$v.'"';
}
}
else {
$script .= "$k=\"$v\"";
}
}
$script .= "></scr"."ipt>\n";
}
else {
if ( strpos($src, '://') !== FALSE) {
$script .= ' src="'.$src.'" ';
}
elseif ($index_page === TRUE) {
$script .= ' src="'.$CI->config->site_url($src).'" ';
}
else {
$script .= ' src="'.$CI->config->slash_item('base_url').$src.'" ';
}
$script .= 'language="'.$language.'" type="'.$type.'"';
$script .= ' /></scr'.'ipt>'."\n";
}
return $script;
}
}
Then in your PHP code you can do:
echo script_tag('content/js/jquery-1.4.2.js');
I store my javascript in a subdirectory of my view folder so the file path is relative to the view being called and I omit the base_url().
Another technique I adopted was to define an array of scripts to include in my controller, then loop through the array in my view to include them. This allows me to include specialty js functions only when needed.
$data['scripts to load'] = array('edit.js', 'menu.js', 'contact.js');
$this->load->view('myview');
Then in the view
<?php foreach($scripts_to_load as $script):?>
<script type='text/javascript' src = 'my_js/<?php echo $script;?>'>
<?php endforeach;?>
If you have script files that get loaded on every page, you can hard code them in your footer view like is described in the other answers.
The $data variable sometimes may be lost if you have nested views and you don't pass it as an argument to the children/nested views.
I found a simple solution that is working very smoothly to me:
In your current view file you setup your script like this:
$this->scripts[] = '/js/myscript.js';
at your footer or {whatever.php} file you insert this code:
<?php
if(isset($this->scripts))
foreach($this->scripts as $script) :
?>
<script src="my_asset_path/js/<?=$script;?>"></script>
<?endforeach;?>
If you need only a pice of javascript code, you can always use anonymous functions like this:
<?php
$this->RenderScript[] = function() {
?>
<script>
console.log('myjavascript code snippet');
</script>
<?}?>
and at the bottom:
<?php
if(isset($this->RenderScript))
foreach($this->RenderScript as $script) {
$script();
}
?>
Just use the standard:
<script src="/path/to/file.js" type="text/javascript" charset="utf-8"></script>
inside your view! (Not inside the PHP tags, of course.) I don't think the CodeIgniter HTML helper has any functions that you could use as an alternative to writing out the HTML yourself.
Check out Phil Sturgeon's CodeIgniter Template Library. We use a modified version of it at work.

Categories