Get php variable within javascript - php

I have run into an interesting problem. I am currently developing php page and need to access a php variable within the javascript onload.
$(document).ready(function() {
var temp = <?php $page_id ?>
}
is this valid? I know that this might seem weird and not be allowed but I am developing a page that has two popup windows. The windows are created using the same view template and there is no way to distinguish between each other. If I stored a hidden value on the page with information unique to the page like so
<input type="hidden" value="<?php $page_id ?> id="page_id" />
if there are two views open at the same time there is no way for me to get a unique page id like so
var temp = $("#page_id").val();
Because there are two views with the same input id that is not unique. Long story short, is it valid to reference a php variable in the javascript?

Long story short is it valid to
reference a php variable in the
javascript.
Short answer, yes you can...PHP is server-side language, you can use it where you want.
Note: I assume that you are doing this in a file with php extension.

Long story short is it valid to reference a php variable in the JavaScript?
You are not referencing a PHP variable in JavaScript. You are simply generating the JavaScript code dynamically through PHP, where the value of the PHP variable $page_id gets hardcoded into the JavaScript code.
If you generate your JavaScript code through PHP, and you use var temp = <?php echo $page_id ?> it will work, but I wouldn't consider it best practice for bigger projects. I prefer my JavaScript code to remain static.

Your first piece of code is valid as long as you are generating the javascript. The same wont work if you put your js code in a separate .js file. Generating dynamic js is not a good practice for several reasons, like js browser caching and reuse for example.
If you want to completely separate the js code of php, you can create a client-server communication where js will ask for a specific value from a php script through ajax and later play with it in js environment.

The only thing you need is some clarification.
As a matter of fact, you cannot pass a variable. You can pass only it's value.
Also, one cannot "pass" anything from PHP to javascript. Javascript being generated by PHP. It is like HTML. You just generate any code you want. And you can use any variables, of course, with this code generation.

Your second example will work too, but you need to echo the value of the PHP variable to the page so that JavaScript can read from it. Also use htmlspecialchars to make sure you don't end up with invalid html.
<input type="hidden" value="<?php echo htmlspecialchars($page_id, ENT_QUOTES) ?>" id="page_id" />

You will find your answer in this question.

Related

Find and store all innerhtml of div to php variable

I’m trying to store the content of a div to a variable.
Example:
<div class="anything">
<p>We don't know the content of this div</p>
</div>
I want to search for <div class="anything"> and store everything between opening and the end tag.
We also want to avoid using absolute pathnames, so that it only searches the current HTML/PHP file for this div where the code is present.
Is this possible with PHP, or is this only possible with JavaScript ?
PHP is not that intelligent. He doesn't even know what he says.
PHP is a server-side language. It has absolutely NO clue about what the DOM (ie. what is displayed in your browser's window) is when it delivers a page. Yeah I know, PHP rendered the DOM, so how could it not know what's in there?
Simply put, let's say that PHP doesn't have a memory of what he renders. He just knows that at one particular moment, he is delivering strings of characters, but that's all. He kind of doesn't get the big picture. The big picture goes to the client and is called the DOM. The server (PHP) forgets it immediately as he's rendering it.
Like a red fish.
To do that, you need JavaScript (which is on the client's computer, and therefore has complete access to the rendered DOM), or if you want PHP to do this, you have to retrieve an full-rendered page first.
So the only way to do what you want to do in PHP is to get your page printed, and only then you can retrieve it with an http request and parse it with, in your case, a library such as simpleHtmlDom.
Quick example on how to parse a rendered page with simpleHtmlDom:
Let's say you know that your page will be available at http://mypage.com/mypage.php
$html = file_get_html('http://mypage.com/mypage.php');
foreach($html->find('div.anything') as $element)
echo $element->src . '<br>';
you probably need a combination of those.
In your Javascript:
var content = document.getElementsByClassName("anything")[0].innerHTML();
document.getElementByID('formfield').value(content);
document.getElementByID('hiddenForm').submit();
In your HTML/PHP File:
<form id="hiddenForm" action="path/to/your/script">
<input type="hidden" name="formfield" value="" />
</form>
In the script you defined in the form action:
if(!empty($_POST)){
$content = $_POST['formfield'];
// DO something with the content;
}
Alternatively you could send the data via AJAX but I guess you are new to this stuff so you should start slowly :)
Cheers!
steve
You could use JS to take the .innerHTML from the elements you wan and store them in .value of some input fields of a form and then use a submit button to run the PHP form handling as normal. Use .readOnly to make the input fields uneditle.

Use of PHP code inside Javascript code

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.

Placing javascript/jquery functions in a universally accessible page

I am trying to clean up my pages, and one of the major ways that I am doing so is to put JavaScript and JQuery functions into a file called 'scripts.js' that is automatically accessed upon page load.
I've run into a problem with functions that use php to call from the page itself. For example, the following function doesn't work, and in fact 'kills' the script for all pages (so now things that were supposed to be hidden are not, and things are not loading properly). I've narrowed it down to the fact that I use to call a variable. I would really like to be able to keep functions using PHP in this universal file as opposed to clogging up the HTML template pages, any thoughts on either how to make this work, or if not how else I may be able to call the values needed? They are always extracted to the page before rendering if that helps.
function positiveSelect()
{
var size = <?php echo $idea[0]["size"]; ?> * 1;
if (size > 5)
return true;
else
return false;
}
if you can't retrive your data form the DOM itself you can store values with the corresponding object:
<div data-size=20>
and then retrive it with:
$(element).data("size");
or if you have global data you want to store you can create a value "container" in the head of you html document like this:
<script type="text/x-json" class="global-data">{"value1":"1","value2":"2"}</script>
and then read the content of that element and parse it with JSON.parse
If this function is that specific to a certain page, you might want to add a second js script that just gets loaded on that page.
An alternative would be to echo out a js variable in that php page and have your code call that function with that variable as a parameter.
You can give the javascript a ".php" extension and call it in the script in the same exact way:
<script type="javascript" src="path/to/scripts.php"></script>
You could just name the generate scripts file scripts.php or scripts.js.php; then the PHP preprocessor will process the file and the PHP statements will be evaluated.
When mixing php or any server side language with javascript you need to be aware that the php gets executed only once when the javascript file is created on the client side.
This is probably why you are getting unexpected results. As you move from page to page the php snippet in your global scripts.js will not get updated.

Is echoing Javascript code condtionally based on server-side logic considered harmful?

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?

Dynamically create HTML via PHP or jQuery ajax? Which is faster or better method?

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!

Categories