Like this:
<script>
setSomeStuffUp();
<?php if ($otherStuffNeedsToBeDone === true) { ?>
doSomeOtherStuff();
<?php } ?>
breakSomeStuffDown();
</script>
Came across something like this at work- done with templating (Smarty), so it looks a bit cleaner- but not by much! Also echoes some template variables used for things such as jQuery selectors, and other little unpleasant-looking bits.
What's the proper way to do this? Load the data that needs to be used for logic in the JS as JSON via AJAX? HTML data attributes?
Something about it just smells bad, bad, bad.
Thanks everyone.
It is bad practice to use language X to generate code in language Y.
Try "decoupling" the two languages, for example, like this:
<script type="text/javascript">
var data = {
id: "<?php echo $id ?>",
...
};
$(document).ready(function(){
$("#" + data.id).on("click", function(){
/*do something*/
});
});
</script>
This way, PHP only cares about populating the data structure and JavaScript only cares about consuming the data structure.
Echoing configuration variables and some javascript initialization code from server doesn't sound too bad in general, but if such js-injection-from-server pieces are all over the place then you're right, it's ugly, at least because such code is difficult to manage.
Just try to centralize any kinds of initialization and do the rest in statically-defined client-side JavaScript logic.
UPD. #Oscar Jara is talking about the same thing and provided a good illustration. But often even such cases can be avoided if server-side logic provides data for JavaScript processing via HTML (after all, that's what HTML is for).
Here's a trivial example that you can often encounter. Say you want to output a gallery that will be enhanced into a carousel via JavaScript.
Server generated HTML:
<ul id="myGallery">
<li><img src="img1.jpg /></li>
<li><img src="img2.jpg /></li>
<li><img src="img3.jpg /></li>
...
</ul>
And then you have your static JavaScript code initialize the carousel when DOM is ready:
// when DOM ready...
AwesomeCarousel.init($('#myGallery'));
Here the data prepared by the server is this piece of HTML with a list of images, no need to generate JavaScript explicitly loading every image. You can pass arbitrary data via the data-* attributes.
Personally, I use PHP in JS in many instances. Sometimes it is to populate a variable with JSON data, a page id, or something of that nature. As far as I am concerned, PHP is designed to write the code that appears on the page, and JS is designed to interact with the user once the content is there.
I do get what you are saying, in that there are probably cleaner ways of doing this. You mentioned AJAX, which would probably be cleaner and would definitely help the flow of the document being output. The only issue is that you have to make a second request to the server for some very simple and meanial variable. A few milliseconds isn't huge, but in the a production website, you probably don't want to be making that additional request and bogging down server resources.
In response to what the cleanest way to do it would be, if it was that big of a deal... I would create a separate JS file with that code and then use the server to include that individual file if needed. Again, I don't do this, but I think it would look the cleanest in the template.
If you want to get really out-there, you can have the HTML page request a .js file, coupled with their session-id or some other indicator of who they are, operate the .js call as a PHP call, dynamically build the JS based on what their session requires and then output it back to the browser as a .js filetype.
But that's a lot of work.
If you'd like something that smells less, have PHP dump either a JSON-string at the end of your file:
var cfg_string = "{\"username\":\"Norguard\", \"new_messages\":[......]}"; // client
$cfg_obj = array(); // whole lot o'PHP
$json_encoded_cfg = json_encode($cfg_obj);
echo "var cfg_string = {$json_encoded_cfg};" //server-side
And then parse it, in the client for added safety...
...or just outright create a map in the template:
$cfg_string = "var dataMap = {";
foreach ($cfg_obj as $key => $val) {
// print key:val all pretty-like,
// handle commas (ie: no trailing comma at the end), indent with tabs or spaces
// if you want, count the number of items so that the object closes ({})
// without any newline operator, if there are no config settings
}
echo $cfg_string;
Both of these are clean and unobtrusive and keep everything separate.
The config data/text can go right above whatever your init/loading code is going to be, and be passed in as a parameter to that init-logic.
If all you're doing is passing data from the server-side language to the JavaScript code, then that's fine. Plenty of CMS packages out there do it.
I don't really see the need to conditionally generate JavaScript code on the server side. Maybe there's a use case for it but JavaScript is a language itself, so why not just put the logic in the JavaScript code?
Related
main page; index.php
There are two iframe in main page as
iframe name= topifrm
iframe name= content
I want to click on link "Education", then the following action should happen:
load topindex.php page to the topifrm and at the same time
load education.php page to the content
or
if you kindly please send me how do I access to php variable, say "$edu_id" in education.php from topindex.php page..
I have to say that there a lot of problems in what you are requesting. For a first, don't use IFrames. They were used like that ages ago and thankfully, things like ajax arrived.
The other problem is :
if you kindly please send me how do I access to php variable, say
"$edu_id" in education.php from topindex.php page..
Have in mind that PHP scripts are executed on the server and not in the browser. For that reason, whatever you see in the browser is a strict html file. To make it clear, you can't have access to the php variables from the browser. But it's not the end! Because many people do what you're trying to do but in a better way.
Let say you index.php that return this:
<html>
<head><title></title></body>
<body>
<div id="menu">
<ul>
<li><a data-phpid="education">Education</a></li>
</ul>
</div>
<div id="container"></div>
</body>
</html>
You'll need some javascript because without javascript, it's not really possible to do it correctly with iframes. With iframes, you can't really just get "data" or catch exceptions if the page fails to load.
I'll be using jQuery as everyone uses it and it might be easier to understand because it's not a so bad library. Put this is a script tags after you linked jquery and it should work.
$(function () {
// this will get executed when document is ready
$('#container').load("/secondframe.php");
$('#menu a').click(function() {
var pageid = $(this).data('phpid');
$("#container").load("/secondframe.php?phpid=" + pageid);
});
});
That said, it should work, in your php script you'll be checking for $_GET['pageid'] to get the id you just sent as "get" params.
But If I were you, I wouldn't use load but instead serialize everything to json, pass the json to a Javacript object to generate html on the browser instead of rendering html on the server. Leave php as it will never give you anything good but only nightmares.
Learn javascript! Learn it well don't use jQuery (jquery will prevent you from understanding how to write code in javascript). Learn python to write application server, learn ruby and don't restrict yourself to rails. And learn a lisp because real programmer program with lambda calculus!
Since I know many consider the use of PHP code inside Javascript code bad practice, I wonder how to execute a javascript function provided that a certain PHP variable has a certain value.
This is the way I currently write the code:
<script type="text/javascript">
function execute_this() {
some code;
}
<?php
if(!empty($_SESSION['authorized'])) :
?>
execute_this();
<?php
endif;
?>
</script>
Any ideas how to avoid using PHP inside Javascript in this particular example?
If you don't want to include any PHP code inside the javascript code but want to know the value of a php variable, you have to integrate a communication between the server side (PHP) and the client (JS)
For example you could use a ajax request to call a small php snippet that provides the value in its reply. With that value you can go on in you java script code.
In my opinion you should decide if its worth the effort.
Edit:
In regard to the edited question: If it is important that the JS function is never ever called if the PHP session value isn't present I would stay with the PHP code but would do it that way:
<?php
if(!empty($_SESSION['authorized'])) :
?>
<script type="text/javascript">
function execute_this() {
some code;
}
execute_this();
</script>
<?php
endif;
?>
If you evaluate the value of the session variable in javascript, you have to make sure that nothing bad happens to your code if the provided value was manipulated.
It's a matter of code style. The time your project grows, you will find it increasingly difficult to maintain it or to extend its functionality. A better solution would be to initialize all needed variables in the beginning of the file and to externalize the main JavaScript functionality.
Example PHP:
<script type="text/javascript">
MYCONFIG = {
authorized: '<?php echo $_SESSION['authorized']; ?>',
foo: 'something else'
}
$(document).trigger('init'); // fire init event, you can call it as you like
</script>
Example JS with jQuery (note that i use the custom trigger 'init', you can call it however you like):
$(document).on('init', function() {
function execute_this() {
document.write(MYCONFIG.foo);
}
if(MYCONFIG.authorized) {
execute_this();
}
})
This should be in an external JS file and does not need any PHP tags.
You have to store the php variables somewhere in the html code and then access it.
For example:
<input type="hidden" id="hidval" value=<?php echo $_SESSION['authorized'] ?>/>
then in your js:
var somevar=document.getElementById(hidval).value;
if(somevar==what you want){
execute_this();
}
I think you have some basic design issues, and we are only seeing the tip of the iceberg and can't fully help you.
There is nothing inherently wrong with calling a php function this way, but you have several issues:
1) you cannot separate your js file & allow for caching or cdn
2) while MVC is certainly not "mandatory", it is definitely a good idea to try to separate this type of logic from your "view" - your rendered output
3) I suspect elsewhere you have a massive security hole - if you are setting certain parameters based on whether or not they are "authorized" in their session, this means you are most likely sending back info on which to base a permissions decision in your php code somewhere. Never do that from the page - all data should be "neutral" on the page itself, because you have no control over it.
Give this a read if you are not clear why I say that: http://www.codebyjeff.com/blog/2012/12/web-form-security-avoiding-common-mistakes
There are three possible ways to do it.
Use hidden field and add necessary variable value inside each fields and get those using jQuery.
User jQuery Session plugin and access php session variable.
make a ajax call to php and get response in json format and access response.
I've built an online community in Drupal with a homepage that is kind of like the Facebook wall. You see the 25 most recent posts, with the two most recent comments below those posts. There is also a textarea right below those comments so that you can quickly post a new comment on a particular post.
These Facebook-style posts have a lot of functionality built into them via JavaScript. Clicking a "view all comments" link directly below a post makes an AJAX call that grabs all the comments for that post and displays them right below it. You can also mark posts as helpful, as the solution to your question, edit comments inline, etc. All of these actions require AJAX requests, which means that the JavaScript making the request needs to know essential information such as the Node ID (the unique identifier of the post), the comment ID (unique identifier of the comment), etc.
My initial implementation had these pieces of essential data sprinkled all over the posts, making it more complicated to write the JS that needed to find it. So my second implementation simply output all this data into a JSON-compatible string in the main wrapping element of each post. While this made it much easier for the JS to find the data it needed, writing JSON as a string is a pain (escaping quotes, no line breaks).
So now I have a third idea, and I'm looking for feedback on it prior to implementation. The idea is to create a single global JS Array for all these posts that contains within it objects that hold the data for each post. Each element in that array would hold the necessary data needed for the AJAX calls. So it would look something like this:
Facebook-style post template
<div class="post" data-postindex="<?php echo $post->index; ?>">
<!-- lots of other HTML for the post -->
</div>
<script type="text/javascript">
globalPostArray.push({
nid: <?php echo $post->nid; ?>,
authorID: <?php $post->authorID; ?>,
//etc. etc. etc.
});
</script>
The result of the above code is that when a link gets clicked that requires an AJAX request, the JS would simply traverse the DOM upwards from that link until it finds the main .post element. It would then grab the value of data-postindex in order to know which element in globalPostArray holds the data it needs.
Thoughts? I feel like there must be some standard, accepted way of accomplishing something like this.
I've never heard of a standard way to "pass" information between PHP and Javascript, as they are a server-side and client-side language, respectively. I would personally use a hybrid of your second and third solutions.
Store the post id in a data-postindex attribute (data attributes are newish, and the "right" way to store small amounts of data). But I would still just use a JSON array for the rest, as storing lots of data in data-attributes (and escaping them!) is potentially problematic. PHP has a json_encode function that takes care of all the escaping and such for you - just build a PHP array (say, $postdata) like you normally would, and then throw this in your post template:
<script type="text/javascript">
globalPostArray.push(<?php echo json_encode($postdata) ?>);
</script>
Where $postdata is something like the following:
$postdata = array(
'nid' => 5,
'authorId' => 45
...etc...
);
It should be easy enough to generate such an array from your existing code.
I wrote a blog post a while back about my implementation of this kind of thing, but it sounds like all you need is a pointer at json_encode.
The most reliable way to pass any PHP variable to JavaScript is json_encode.
<script type="text/javascript">
var something = <?php echo json_encode($var); ?>;
</script>
You can't pass closures and resources, but otherwise anything's game for being passed.
I would store the data inside the element:
<div class="post" data-postindex="<?php echo $post->index; ?>"
data-nid="<?php echo $post->nid; ?>"
data-authorID="<?php echo $post->authorID; ?>">
...or storing a complete JSON-string in 1 data-attribute:
<div data-data="<?php echo htmlentities(json_encode($somedata));?>">
My answer is about the same as the other guys but more detailed. I usually do it like this and i think is the best approach: (of course you can grab the data using ajax, but depends on the context)
somefile.html
<html>
<head>..</head>
<body>
html code
<script>
window.my_data = <?php echo json_encode($my_php_var); ?>
</script>
</body>
</html>
somefile.js
$(function() {
window.myitem = new myClass(window.my_data);
});
var MyClass = function(init_data) {...}
Hi I just want to know what the best practice is for dynamically creating html. I can do it in two ways
Direct PHP
<div id='id-here'>
<?php
$user->id = $_GET['id'];
$user->displayUserInformation( );
?>
</div>
jQuery ajax(js script called on page load)
$.ajax({
type: 'GET',
url: 'inc/user_information.php',
data: 'user_id=user_id', //assuming user_id value was already set.
success: function(html)
{
$('#user_information').empty().html(html);
}
});
Note: This code doesn't exist and is purely for showing what I mean^^ I also know jQuery load, but prefer to use jQuery ajax for complex stuff.
Thanks!
The PHP method is certainly more reliable, as it doesn't require javascript in the client. For information that isn't expected during a page's lifetime, or indeed a user's session it also makes a lot more sense. I don't imagine the information on a user is likely to change that much during a page view.
However, if there is some data that's expected to change, say a post count or something, then use PHP to set the initial value, then use ajax to update it only when the value actually changes.
I wouldn't worry about which is faster... the difference would probably be negligible. But bear in mind that some users do have JavaScript turned off... if you want to support those users, it's worthwhile taking the extra effort to do it in PHP.
My rule is that if it can be done on the server, do it there. Then you can be absolutely sure of the results for all users.
u get it all wrong, first one is not a 'dynamically created html", user sent a request, PHP process it, and return the HTML, and your browser render it
2nd one is your browser already load HTML, and u try to use jquery to simulate another request of the same process of the 1st one
In your examples, if you show user info like this, method 1 will not require another data fetching from the server as in example 2 (2 HTTP requests total, 1 for original webpage, 1 for the ajax), so it is faster.
usually, generating static data inside a page like this (in example 1) is different from AJAX, where content is provided to the user, and only update with the new data using AJAX without updating the whole page's content.
Maybe what you mean is: should the data be provided together with the original webpage, or should it be left empty, and then use AJAX to fetch the data to display it. It would be better usually to provided data at first, instead of letting the user wait for another trip to the server to see the data.
I believe that loading from PHP as static loading would be better and more reliable. However loading from AJAX will push the results one time, not as static loading, data will be loaded in portions...
Along the same lines, which is faster within a php file. This is more for SEO and "best practice" than for actual user experience. I'm using wordpress, and I'm working within php files. Most of it is php, but I have four lines of html within the file. All are exactly the same. I could loop through the four lines with php, or copy and paste the four lines of html. I don't expect to ever change the code, so php doesn't seem to present any other benefits.
Here's my code:
HTML version (well mostly)
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
OR the php:
for($i=0;$i++;$i<4){ ?> //start loop, 4x
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" />
//Image path using php
<?php } ?> // end loop
THANKS ALL!
Let say that I have many Javascript inside pages. At this moment is pretty easy to initialize variable by simply using some Print/Echo statement to initialize JavaScript value.
Example: var x = <?php echo('This is a value');?>
I first thought that I could pass all variables value by parameter of function BUT it's impossible because we have a lot of values (we have a multilanguage website and all text are from the server (BD)).
Example : initializeValues(<?php echo('Value1,Value2,Value3,Value...');?>);//JS Method that can be external of the page
More problem come when we want to take off all JavaScript from pages to move everything on external JavaScript file. What would be the good way to initialize all those variables? If I bind the JavaScript methods by using OnLoad of the document I won't be able to use Print/Echo method to populate all values.
Any good pattern to resolve this task?
A very popular pattern is the use of the JSON format. There are libraries to produce it, and Javascript directly consumes it.
With php you can create an associative array then using json_encode you can serialize it for output on the page between some script tags.
for some examples on doing that you can look at http://www.php.net/manual/en/function.json-encode.php
Here's how I do it:
<?php
$foo = array('bar' => 'gork');
?>
<input id='foo' type='hidden' value='<?= json_encode($foo); ?>' />
Then client side (I'm using Prototype) :
var foo = $F('foo').jsonParse();
alert(foo.bar);
var x = <?php echo('This is a value');?>
Er, no, that would end up as:
var x = This is a value
(syntax error.) You want:
var x = <?php echo json_encode('This is a value', JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT);?>
The HEX_TAG escaping in PHP 5.3 avoids problems with the </ sequence appearing in a <script> block. The AMP and QUOT encoding is needed to ensure there are no problem " and & characters when you're putting code in an attribute value delimited by " or a non-CDATA XHTML script block. If you're only ever using a HTML script block (or XHTML CDATA script block) you can get away without them (although they do no harm either).
json_encode will also happily encode an array of values to put in a JS variable, not just a string.
More problem come when we want to take off all JavaScript from pages to move everything on external JavaScript file.
It's a good idea to put all your static code, including code that binds onto event listeners, in an external JavaScript file. However per-page data should still stay on the page, either in appropriate attributes of the document itself (eg. class names for unobtrusive scripting) or in a simple <script type="text/javascript">var data= ...;</script> block with no other code.
best practice? passing values from server to the client-side js is too volatile for a singular best practice.
let's say you use Smarty. then, my best practice is:
<script type="text/javascript">
var limit = Number("{$limit}");
var msg = "{$msg}";
{literal}
// code using the variables
{/literal}
</script>
but I can also see this as a very sensible approach:
function to_js_vars(arrray $jsvars)
{
foreach ($jsvars as $name => $info) {
printf(
"var %s = %s("%s");\n"
, $name
, $info['type']
, $info['val']
);
}
}
where $info['type'] is one of Number, Boolean, and '' (empty string) for everything else