Is it possible to use $_SESSION with a Javascript file? - javascript

I have a Javascript file main.js and I need to use echo $_SESSION["username"] within it, but it doesn't work obviously. Is there any way I can do this / some kind of workaround?

You cannot execute PHP code in a .js file but there are ways to work around it. You could use an ajax call to get that variable (check out this link for ajax tips).
Depending on the information you wish to store, you could also get PHP to echo it into a specific element in your html page and then use JS to look up that element like this:
echo "<span id='usernameForJS' style='display: none;'>".$_SESSION['USERNAME']."</span>";
And then go and grab that elements inner html with JS like this:
var username = document.getElementById('usernameForJS').innerHTML;
I would advise AJAX just because then there is no need for almost redundant elements in your page. And obviously don't use the second method for anything sensitive.

There is a option I saw on css-tricks.com
https://css-tricks.com/snippets/htaccess/use-php-inside-javascript/
I have never tried on my own but commentators said it works.
There is also a explanation of how you could do this in the comments:
https://css-tricks.com/snippets/htaccess/use-php-inside-javascript/#comment-85757
But don't forget taht this is a rather "hacky" way to do it, you should consider to open that javascript file and instantiate your class/function(or whatever is in this file) from the .php-page.

Related

php hide variable from javascript [duplicate]

I created now a Javascript Code that get the php variable into javascript code, my issue that the php variable is important and I don't want any can see this variable is there is any way to do that by the way I tried to use obfuscator but it doesn't work because of the PHP code inside the Javascript code, let's say this is my Code,
<?php
$var = "this is impotant";
?>
<script type="text/javascript">
var javaScriptVar = "<?php echo $var; ?>";
</script>
So, is there any way to use PHP variables in Javascript code or hide the result of the PHP code?
Nobody sees the PHP code. But if you expose values into Javascript, they are not secret anymore. There is no way to deal with this. You cannot use the value in Javascript and NOT reveal it.
If you want to keep process data secret on the server, and available for the next request of that user, use a session.
People will only see the value of the variable. They wont know what it is or how important it is supposed to be. Nobody will see the variable name because the PHP code is executed BEFORE the page is sent to the client. Therefore there is no need to obfuscate the value, and you cant anyway since you need the value.
An example. if I use this PHP code in my file
<p>Hello Mr <?php echo $MY_SUPER_SECRET_VARIABLE ?></p>
the only thing people will be able to see in the source when the page loads is
<p>Hello Mr Bond</p>
The same rule applies if it is placed in Javascript
First you need to understand that Javascript is executed on the client side, every piece of code and variable are in some way accessible by someone with some programming background.
Although you can obfuscate the source code and encrypt the variable to make it harder to read, there is no 100% protection when things happen on client side.
who wants to get the value, will get it. but you can
dynamically inject them via ajax
encode (base64 etc.) the value
obfuscate the code
PHP files will be interpreted into static (like html or xml format) file, means that all variables will be replaced with certain values.What users see is static, no php code displayed but just interpreted text.

How to modify HTML from another file with JavaScript/jQuery

I need a reference of a HTML element that has an id of #searchResults
$.get('search-for-prospect', function() {
_content.find('.prospect-container').sort(function(a,b){
...stuff...
}).appendTo('#searchResults');
})
I tried using jQuery's get to get the that element, but it doesn't work as expected.
I need to get a reference of searchResults and append to it. How can I achieve that?
The only way to get HTML from another page with javascript is by making AJAX call (in fact js template engines work this way).
So you have to $.ajax the page you want, parse it as HTML and do what you want to do.
Beware: you are not editing the HTML file itself, but just its "in memory copy".
Javascript, as far as it is used as client-side technology, does not allow modifying files or in general accessing the file system. So if you're looking for some trick to write in the HTML, you're on the wrong way

How to have an action respond to javascript in PHP?

I'm currently working with a Kohana project and am trying to implement endless scrolling. I'm trying to use the method Ryan Bates shows in the following Ruby on Rails video:
https://youtu.be/PQX2fgB6y10?t=2m29s
At 3:21 he says the action won't respond to javascript and proceeds to create a js.erb file. What is the PHP equivalent to this step going forward? Where would I place the php file equivalent to his index.js.erb?
To copy what he did, just create a PHP file that generates Javascript with the content you want to append like he did with render(). You can call this file whatever you want, but following his convention, it would be index.js.php.
So for example:
$('#products').append('<?php render_elements(); ?>');
$('#pagination').replaceWith('<?php render_pagination(); ?>');
Since you're already this far in his tutorial, I assume that you have the code to render the elements you want to display already.
It may be easier however to use other AJAX methods to achieve the same thing though.

Using PHP variables in jQuery plugin initialization?

I have a jQuery image gallery plugin that I'm using extensively throughout a site for which I'm building PHP templates. In the properties for the plugin initialization, most of the values will remain the same throughout the site, aside from a few exceptions. In these instances, I'm wondering if it's ok for me to pass in a value for the property via PHP; e.g. if there is a property called "thumbnailsVisible" in certain cases I will want this set to true, and in others, false. Thus, is there anything wrong with assigning a value to a corresponding variable and including the following in the jQuery initialization within the template:
thumbnailsVisible : <?php echo $thumbnailsVisible; ?>
I realize I could also just externalize the initialization in a js file and create different versions as needed, but this would be much simpler provided there isn't anything wrong with this approach...
Also, if there's a completely different approach that would be optimal, I'd appreciate any sort of assistance. Thanks.
Yes. You can do this.
PHP is processed on the server side and only sent to client when it's processed.
You could write a php script to return the JavaScript and pass in an argument.
Eg.
<?php
$thumbnailVisible = isset($_GET['showthumb']) ? $_GET['showthumb'] : 'false';
?>
$.func({
thumbnailsVisible: <?php echo $thumbnailVisible; ?>
});
If it doesn't work correctly, try specify the content-type using header().
header('Content-type: application/javascript');
Place this at the top of the PHP script.
Yes, you could do that , actually i come across cases like that very often and i usually do the same .
You can check the code here :
(Although that is based on codeIgniter)

Including external javascript which doesn't honor closure usage

I have to include an external javascript file as part of a Drupal project I'm working on.
Unfortunately, this external file doesn't make correct use of closures, for example:
(function($) {
function test() {...}
})(jQuery);
function test2() {
console.log($('#xyz').val());
}
Which leads to a '$ is undefined' error whenever test2() is executed.
I know that Drupal makes sensible use of closures to allow harmonious coexistence of libraries, which is very useful, but in this case it'll be a nightmare to get the team responsible for said external JS file to make the necessary changes (and will also involve trying to explain to the "experts" responsible).
Is there any way that I can give this external file access to use $ as a pointer to jQuery?
Ideally I'd like some solution which doesn't involve a huge workaround at my end, but can still make use of the external version.
Failing that, I'll just take a local copy, and fix accordingly.
Thanks!
Just assign a global.
window.$ = jQuery
You will either need to take a copy and modify it to suit, or use PHP to grab the file and output it, for example if you pointed the javascript src to a local php file, in that php file you could do something like
$js = file_get_contents("externaljsfile");
echo ";(function($) {";
echo $js;
echo "})(jQuery);";
There is a way i heard of, of using imported javascript which may possibly work (javascript macro's?), however i've never read up on them (if they even exist) and they wouldn;t be supported by enough browsers to be a viable solution anyway

Categories

Resources