How can a class be added to a div via php? - php

I have this h tag below,
<h3 id="reply-title">
& I needed to add a class to it remotely.
(This h3 tag is located in comment-template.php. (line 1554) of WordPress core file in case you are wondering why I can't just hard code the class to it.)
I've done this with one line jQuery (add class on .load) but now, I am concerned since if javascript is turned off, the class won't be added.
I have very little knowledge of php and I am wondering if this can be done in php. I've done some research on google & I couldn't find any reference.
Any php expert who can provide some insight?

This is in general a bad practice, but you can do that like this:
echo "<script>$('#reply-title').addClass('class')</script>";
But I repeat: This is a bad practice. The Javascript must be in .js files, and the PHP in .php files.
However, if the Javascript is disabled, I think you can't do what you want.
Hope this helps.

Related

PHP automatic footnote and endnote generator

This is more of a general information question involving endnotes than a "check my code" one. That's because I can find almost no (useful) information on the subject and don't have the skills to create this myself. But I still think it's useful to create a general brainstorm session / forum thread on the net about this.
The issue: I've written about 60 articles, a dozen of them book-length or near book-length on a site that has been manually designed with HTML5, CSS3, jquery and PHP - the latter two mainly with pre-existing code. I'm very happy with it except for one thing: endnotes! It takes forever to update them.
An average article has 120 endnotes (up to 550). It happens frequently, especially during the writing/proofreading process, that I need to add more information or want an additional endnote. That means anywhere from 2 to 30 minutes of copy-pasting "[113]s", "[114]s" around. It's hopelessly inefficient.
Ordinarily I dislike the uninspirational Wiki CMS platforms, but they have one huge benefit: cite.php plugins. Like this one:
https://www.mediawiki.org/wiki/Special:ExtensionDistributor?extdist_name=Cite&extdist_version=REL1_26&extdist_submit=
Once you have this, you just put an URL between <ref> </ref> and an endnotes gets automatically generated below a {{reflist}} tag. It's explained here:
https://en.wikipedia.org/wiki/Help:Footnotes
Footnotes are created using the Cite.php software extension. This
extension adds the HTML-like elements <ref>...</ref>, <references />
and <references>...</references>. The elements are also used in a
number of templates; for example, it is becoming more common to use
{{reflist}} rather than <references /> as it can style the reference
list.
I've checked out the plugin and it, of course, is much more than just a few lines of PHP.
My main question is if anyone is aware if this type of code has been created for custom designed websites. Or if someone has an idea how to program this manually? If it's not too hard, I might try it myself in the near future or hire a programmer.
P.S. I did study HTML5 solutions for endnotes in the past. Can't remember the details, but they were terrible. It's crucial to have one type of tag, with each one generating a new automatic endnote.
{{ }} is not standard HTML tags, but usually in some modern MVC frameworks they are used as replacement for PHP syntax like echo $foodNote which is the same as {{ $foodNote }}.
A MVC framework like Laravel use it as part of blade template.
But in the provided link you have in your question, the {{reflist}} is just referring to the content inside the tags like <ref>Content of the reference</ref>.
The provided Cite.php helper file is parsing the content inside tags like <ref>...</ref> to variable reflist inside a curly braces with the same content.
It should be not very difficult to program such thing.
Here is a simple PHP script to handle footnotes automatically. The only significant caveat is that your web page file name must end in .php or .phtml (not all web servers support .phtml). This is no problem because the web server will treat the file exactly as a .html file, except it watches for PHP tags so it can process the embedded PHP scripts.
Here is the script.
<?php
function footnote($footnote){
global $Footnotes, $FootnoteCount;
$FootnoteCount++;
$Footnotes[$FootnoteCount] = "$footnote";
print "<sup>$FootnoteCount</sup>";
}
function PrintFootnotes(){
  global $Footnotes, $FootnoteCount;
for($i = 1;$i < $FootnoteCount + 1;$i++){
  print "<sup>$i</sup>$Footnotes[$i]<br />";
  }
}
?>
You can put the script at the top of each page.
Better yet, save the script in a file named FootnoteFunctions.php. Of course, you can name it what you want or put it in a file with other functions. Just change the following include as appropriate. Next, put the following in the head of your HTML document:
<?php include("FootnoteFunctions.php"); ?>
Put this where you want the footnotes to appear at the bottom of the page:
<?php PrintFootnotes(); ?>
To create a footnote insert the following where you want the footnote number in the text (with your text between the quotes):
<?php footnote("footnote text here") ?>
That's it.
You can embellish the script as desired. For example, to pop up the footnote text as a tooltip, add title="$footnote" to the tag. You can also put a table tag, etc, in the printing function to make the footnote numbers and text line up nicely.
Here is my page explaining line by line how the script works. It also has an embellished version with the features mentioned above.
https://vocademy.net/textbooks/WebDatabase/Footnotes/PageSetup.php?Page=3&CourseDirectory=WebDatabase

custom php function to call in header

I have a Wordpress website. I am asking for help as I am not good with codes, but know a bit about the flow of functions and all.
I want to add a new PHP function that will be defined in a separate file. The function to be defined is required to serve a 728x90 banner ad on top of the header area of the site (so I guess the php function will also have CSS styling to align the ad in the center). I don't know what I am saying will be possible the way I am saying.
Alternatively, there might be a way to call a js function defined in separate file, then called in the php header to serve the banner (again center-aligned).
I am seeking help here as Stackoverflow also helped me solve problems previously.
Is there anyone who can help me get this thing done?
Once you have your PHP handler written in a separate file call it using require_once like this:
<?php
require_once('myfile.php');
// Wordpress Stuff
?>
I guess PHP have no relation with CSS/styling, you can do it with Javascript.
like this or using JQuery

jQuery code placement suggestion

I know this is going to sound like a dumb question, but as I'm learning jQuery by example, I'm finding that the placement of the scripts and functions varies a lot from example to example. Case in point, somewhere I read that the .onReady function should be placed below everything else to insure that the whole DOM is actually ready, and things of that nature.
The question is simply this, aside from obvous script tags, is there a Best Practices of where in the PHP file jquery should located? What about one-off inline scripts? Sorry for the naive nature of this, but I'd to be trying these examples in a "right" way as I figure out how to bring it all together.
This site seems to have some very insightful folks contributing, so thanks in advance for any guidance! :)
Aparently it wasn't as dumb as I thought - thank you everyone for the insights - I feel a little more clarity on what I was trying to understand in the big picture.
AFAIK, there is no .onReady
Perhaps you are referring to $(document).ready()?
The point of the .ready() is to wait for the element to be ready. In this case, the document. So nothing within that will be executed until the document is ready. As such, you can put that anywhere you want.
As for where you link to JS files, however, you want to do that at the bottom of the document for performance reasons:
http://developer.yahoo.com/performance/rules.html
Don't know about PHP, but the instruction to put every onReady code at the bottom
"to insure that the whole DOM is actually ready" is wrong!
The whole point of the ready event, is that you can place it everywhere you want and it will still work.
Example:
$('#foo').val() // undefined - the DOM isn't ready yet.
$(document).ready(function(){
$('#foo').val() // bla - the DOM is ready now.
});
<input id="foo" value="bla" />
Live DEMO
Note that $(callbackFunction) equals to the verbose syntax $(document).ready(callbackFunction);
You should read the ready docs
You should include your <script type="text/javascript"></script> before closing of <body> tag of your page. This will ensure you that all static portion of page above will be loaded before it.
The instruction ready allow you to put your javascript code everywhere. It will be executed only when the document is ready.
The syntax is the following :
$(document).ready(function() {
// Put your code here.
});
OR this one :
$(function() {
// Put your code here.
});
But to make a choice, prefer the bottom of your page, just before the closing < /body>, for performance reasons.

PHP require vs grails include

I wanted to know the command which is exactly equal to php require in my GSP (Grails server pages) or in Groovy.
I know I can use <g:include/> but wanted to know is there any command which will fulfill php require in groovy/grails?
An exact equivalent really depends on the context of what require() is being used for in the PHP script.
PHP and Servlet environments operate differently. Using require() in PHP simply locates another PHP script and executes it. That imperative-style operation doesn't apply as well to the more object-oriented Java/Grails/Servlets.
There are a couple of possible equivalents, depending on what you're trying to accomplish:
<g:include/>
Includes the response of another controller/action or view in the
current response
e.g.
<g:include controller="foo" action="bar"/>
What this will do is invoke a different controller/action and insert the response into the current page. This would be similar to PHP if your require() was rendering some markup.
View templates:
If you're just trying to include common pieces of markup in several pages, these might be what you're looking for. You can create template views and use <g:render/> to include them in your GSPs. I suspect this is what you're after, but see my "Update" below for some advice about this.
#page import
e.g.
<% #page import="com.example.mypackage.MyClass" %>
This will make MyClass available to the GSP, which would be similar to require() if the require was specifying some library classes or functions to be used in other PHP scripts. However, using this pretty much screams code smell, since almost anything you'd be using this for would be more appropriate in a controller action or a service.
Update:
Seeing your other question, I'll venture you're simply trying to include a common piece of GSP/HTML in several different views, which kind of goes against what Grails provides for you with its layouts and templates.
If you're trying to "require", say, "blog-header.php" in all of your GSPs, you'd more likely want to just include the contents of the header within a layout, e.g. grails-app/views/layouts/main.gsp, and then use that layout in the views that require the header.
Maybe you should try grails 'template'.
A template is a fragment of view that can be used any time in any view, this is to promove DRY..
<g:render template="myTemplate" model="['object1':object1,'object2':object2]" />
In this case should exists a GSP called _myTemplate.gsp and in this template is working with two objects, you could do a template with only content and no treating objects if you wish.
In the above call the template is invoked in a view in the same folder with the template but you could call it from another view in other folder:
<g:render template="other/myTemplate" model="['object1':object1,'object2':object2]" />
And the pattern for the name of template is the same...
Check it out...

Combine jQuery and Zen-Coding php ports to emulate client side programming style on server side scripts

When I write client side code, I use HTML/CSS/JavaScript and lately jQuery to both speed up coding, and use improved methods to achieve the same goal.
In my text editor I use zen-coding to speed up the writing of code, and also to avoid errors. I was looking at zen-coding as a jQuery plugin for a while, but it has a fatal flaw, that you want the HTML to be written and sent to the client plain before any javascript kicks in.
Although we can use JavaScript servers (env.js or node.js) and therefore do a lot of development server side using JavaScript and jQuery, I am not comfortable moving over yet as it is an emerging technology, and has many differences and drawbacks (and also some major advantages).
I want to continue using PHP server side, but develop in the way I am most comfortable with, and familiar with which is client side JavaScript.
Therefore - I have been looking into QueryPath which is a PHP port of jQuery that aims to take the best and most relevant parts of jQuery and re-work it to suit the server environment.
That is all great, and I have now been looking at two PHP classes capable of parsing zen-coding which when combined acts as a great templating engine and also avoids errors in my code.
The problem I am having is that neither zen-coding parsers support anywhere near a full set of zen-coding features.
So finally my questions (sorry for the rather lengthy intro)
Is there a better server side zen-coding parser I can use in my PHP code?
Is there a good (very concise and full featured) alternative templating system to using zen-coding? (which I know is not originally designed for this task)
Is there a better approach I should take to achieve my ultimate goal of narrowing the divide between the way I code client side and server side?
Is there a PHP library that implements a load of utility functions that by using will enhance the security/performance of my code without me learning all the internal workings? (like jQuery does for javascript)
NB: I am looking more for functional equivalence than syntactic similarity - although both are a plus for me.
Here is some commented test code that should illuminate what I am trying to achieve:
<?php
// first php based zen-coding parser
// http://code.google.com/p/zen-php
require_once 'ZenPHP/ZenPHP.php';
// my own wrapper function
function zp($abbr){ return ZenPHP::expand($abbr); }
// second php based zen-coding parser
// https://github.com/philipwalton/PW_Zen_Coder
require_once 'PW_Zen_Coder/PW_Zen_Coder.php';
$zc = new PW_Zen_Coder;
// my own wrapper function
function pwzc($abbr){ global $zc; return $zc->expand($abbr); }
// php port of jQuery with a new server-side flavor
// http://querypath.org/
require_once 'QueryPath/QueryPath.php';
// initialize query path with simple html document structure
qp(zp('html>head+body'))
// add a heading and paragraph to the body
->find('body')
->html(zp('h1{Zen Coding and jQuery - Server Side}+p{This has all been implemented as a php port of JavaScript libraries}'))
// add a comments link to the paragraph
->find('p')
->append(pwzc('span.comments>a[href=mailto:this#comment.com]{send a comment}'))
// decide to use some jquery - so add it to the head
->find(':root head')
->append(zp('script[type=text/javascript][src=/jquery.js]'))
// add an alert script to announce use of jQuery
->find(':root body')
->append(zp('script[type=text/javascript]{$(function(){ alert("just decided to use some jQuery") })}'))
// send it to the browser!
->writeHTML();
/* This will output the following html
<html>
<head>
<script type="text/javascript" src="/jquery.js"></script>
</head>
<body>
<h1>
Zen Coding and jQuery - Server Side
</h1>
<p>
This has all been implemented as a php port of JavaScript libraries
<span class="comments">
<a href="mailto:this#comment.com">
send a comment
</a>
</span>
</p>
<script type="text/javascript">
$(function(){ alert("just decided to use some jQuery") })
</script>
</body>
</html>
*/
?>
Any help is much appreciated
Questions 1 and 2
A template engine sort of like the ZenCoding example would be Haml. The syntax is different, but it's similarily short and quite concise in general.
If you like using ZenCoding, you could consider simply using an editor with support for it. PhpStorm for example bundles a ZenCoding plugin by default. I'm sure others (such as Vim) have plugins for this purpose as well. However, this approach will only allow you to write it: Once you've written it, the editor will expand it to the actual HTML markup.
Question 3
I think a part of this problem is that they are inherently completely different things. The client-side scripting side of things, it's typically a user-interface only. Certain programming styles and approaches are used with the browser UI. However, on the server-side, you generally have data processing, and for data processing, other types of patterns work better.
I'm a bit doubtful whether the QueryPath thinger you're using is a particularily good choice... It seems to somewhat obscure the HTML markup itself, making it harder to see what the exact result of the operations would be.
For generation of HTML markup on the server-side, I would recommend using a template engine or simply using PHP-only templates.
One approach you could use is to completely throw away server-side markup generation. Of course this is not a good idea for everything, but for complex web apps (in style of Gmail or such), you can generate the entire markup using just JavaScript. On the server, you would only use JSON to return data. This way you don't have to deal with markup on the server and can keep using jQuery or whatever on the client for the entire thing.
Question 4
Again I'm a bit doubtful about this whole thing. If you don't understand what's going on under the hood, how can you produce good code? How can you understand or debug things correctly when they go wrong or don't work as expected?
Now I don't know if you're a PHP guru or not, but personally I would suggest that you learn how things work. You don't have to write everything from scratch to do that though. Choosing a framework is a good idea, and it will do exactly what you ask: It will do many things for you, so you don't have to worry as much about security or other things.
Personally I would recommend using the Zend Framework, since it provides a wide range of components, and you can only use the parts you want - you don't have to use the whole framework at once. However, it can be a bit complex at first especially if you're not very familiar with PHP and OOP concepts, so you might have better luck initially going with some other framework.
first of all i want to say i have up-voted your answer because it is well explained and have some nice point to consider; then i want let you think about theese other point:
GOTCHAS
IMHO you are overcomplicating the whole thing ;)
between the entire PHP code needed to generate the HTML and the outputted HTML itself there is very very low difference in term of lenght of writed-code.
the code is completely unredeable for everyone who don't know the 3 libs or whatever it is.
the speed of site-load will decrease enourmously compared to the semplicity of the vanilla HTML.
what the real difference between:
h1{Zen Coding and jQuery - Server Side}+p{This has all been implemented as a php port of JavaScript libraries}
and
<h1>Zen Coding and jQuery - Server Side</h1><p>This has all been implemented as a php port of JavaScript libraries</p>
6.. as you know both zen-coding and queryPath are not intended to be used the way you are doing, at least not in a production scenario.
7.. The fact that jQuery have a good documentation and it's usefull to use doesn't mean that can be used successfully from anyone. ( the mere copy/past is not considered a coding skill IMO )
SOLUTION
it is probably the best solution for you looking at some kind of PHP Templating Engine like smarty, this will suit your needs in various way:
security/performance
narrowing the divide between the way I code client side and server side
an example would be: ( to be considered a very primitive example, smarty have more powerfull functionalities )
<!-- index.tpl -->
<html>
<head> {$scriptLink}
</head>
<body> <h1> {$h1Text} </h1>
<p> {$pText}
<span class="comments">
{$aText}
</span>
</p> {$scriptFunc}
</body>
</html>
// index.php
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign("scriptLink", "<script type=\"text/javascript\" src=\"/jquery.js\"></script>");
$smarty->assign("scriptFunc", "<script type=\"text/javascript\">$(function(){ alert(\"hello world\") });</script>");
$smarty->assign("h1Text", "Zen Coding and jQuery - Server Side");
$smarty->assign("pText", "This has all been implemented as a php port of JavaScript libraries");
$smarty->assign("aText", "send a comment");
$smarty->assign("aLink", "mailto:this#comment.com|mailCheck");
$smarty->display('index.tpl');
NOTE: the use of mailCheck, yes you should also consider eventuality some kind of variable check. smarty can do it....
hope this help. ;)
I'm not sure to understand your question, but I usually have this simple approach:
<?php
ob_start();
$config->js[] = 'js/jquery.js';
?>
<h1>
<del>Zen Coding and jQuery - Server Side</del>
<ins>HTML and PHP :-)</ins>
</h1>
<p>
This has all been implemented <del>as a php port of JavaScript libraries</del>
<ins>in php</ins>
<span class="comments">
<a href="mailto:this#comment.com">
send a comment
</a>
</span>
</p>
<script type="text/javascript">
$(function(){ alert("just decided to use some jQuery") })
</script>
<?php $content = ob_get_clean() ?>
<?php require 'layout.php' ?>
Some points:
ob_start turn on the output buffer (the output is not sent to the client but stored in an internal buffer)
$config->js[] = 'js/jquery.js'; will say to the layout to add a new script tag
Then there is the plain HTML that have to be decorated with the layout
<?php $content = ob_get_clean() ?> get the output stored in the internal buffer and assign it to a variable.
<?php require 'layout.php' ?> will include the layout with the main HTML structure and some logic to print metas, title, <link> tags, <script> tags, and so on... The layout will contain a <?php echo $content ?> to print the page content.
The point 1, 4 and 5 can be delegated to a Front Controller, so the view can be just:
<?php
$config->js[] = 'js/jquery.js';
?>
<h1>
<del>Zen Coding and jQuery - Server Side</del>
<ins>HTML and PHP :-)</ins>
</h1>
<p>
This has all been implemented <del>as a php port of JavaScript libraries</del>
<ins>in php</ins>
<span class="comments">
<a href="mailto:this#comment.com">
send a comment
</a>
</span>
</p>
<script type="text/javascript">
$(function(){ alert("just decided to use some jQuery") })
</script>
I think that you are entirely missing the point of ZenCoding. ZenCoding is meant to be integrated in your editor, not in your application. It's a way of quickly writing HTML using fewer keystrokes and with fewer errors. Your commented test code doesn't look all that usable to me. I prefer the plain HTML version.
If speed and quality of writing plain HTML is an issue for you, perhaps it's time to switch to a better editor? One with support for ZenCoding, auto-balancing HTML tags, autocompletion, snippets/templates, etcetera? I have configured Vim to do all this for me. I've been told StormPHP is also quite good.
I'm considerably biased in my answer, as I am the author of QueryPath, but I like what you are trying to do. (It's always thrilling to see my code used in a way I never anticipated.)
QueryPath has an extension mechanism. Using it, you can add methods directly to QueryPath. So you could, for example, write a simple plugin that would let you replace qp()->find()->append(zp()) with something like qp()->zp($selector, $zencode);.
You can take a look at the extensions in QueryPath/Extensions and see how they work. (QPXML.php is an easy one to grok.)
If you do end up building (and releasing) a solution, please let me know.

Categories