Is it possible to pass a php variable inside javascript? - php

I am trying to pass a php variable inside javascript bt it is not working.
Comment
Is it possible to do so or I may be incorrect somewhere...
Thanks for your response in advance! :)

First of all, you probably should change 'java' tag to 'javascript'.
Regarding your question - PHP is parsed on the server side, while Javascript runs on the client side. If you are not going to use AJAX and asynchronous calls, you could write values to the JS source, like this:
<script type="text/javascript">
var foo = <?php echo $yourData; ?>;
alert(foo);
</script>

Comment

You're dynamically generating Javascript. You will save yourself some headaches if when you need to do this you, keep it simple. Transfer the data from PHP to Javascript in the simplest way possible at the top of the page:
<script type="text/javascript" >
var $current = '<%? echo $current; %>';
</script>
As others have pointed out, you will want to encode and quote your php variable, using json_encode (in which case you probably won't need the quotes), or a simpler escape function if you know the possible values.
Now, your inline code can be simpler:
Comment
A final recommendation would be to pull this out into its own function, and use the "onclick" attribute.

Use json_encode() if your PHP has it.
This will automatically quote and escape your string and ensures that special characters are properly encoded to prevent cross-site scripting (XSS) attacks.
However, I think you will have to pass UTF-8 strings to this function.
And vol7ron has a good point – you should put a semicolon ; after your statement and put a space between that and the question mark ? for better legibility.
Comment
You can also pass booleans, ints and even entire arrays to json_encode() to pass them to JavaScript.

Related

How do I replace </script> to </scr"+"ipt>

Okay I've something looks like below from user input, known that a </script> will not working inside a document.write() function
<script type="text/javascript">document.write("<script type='text/javascript' src='"+(location.protocol == 'https:' ? 'https:' : 'http:') + "//www.domain.com/script.js'></script>");</script>
Is there anyway to replace the </script> to </scr"+"ipt> inside document.write() function?
Is there anyway to replace the </script> to </scr"+"ipt> inside document.write() function?
No.
The sequence of characters </script> is parsed as an end tag by the HTML parser before it even reaches the JavaScript parser.
You have to edit the source code before sending it to the browser.
That said, there are better ways to approach the problem then looking a location.protocol anyway. Use a scheme relative URI instead:
<script src="//www.example.com/script.js'></script>
Or redirect all HTTP traffic for the HTML document to HTTPS so that you never serve it on an insecure connection.
Your comments suggest that the question you should have asked was:
How can I place arbitrary submitted form data into a JavaScript string literal using PHP?
Use the json_encode function. If you pass it a string, it will give you a JavaScript escaped string suitable for inserting into a <script> element. (It won't be a valid JSON Text though, since that must have an object or array at the outermost level).
<script>
document.write(<?php echo json_encode($_POST['script']); ?>);
</script>
Serious security warning: Do not do this without implementing protection from CSRF attacks as allowing third parties to cause your users to submit JavaScript to your site could be a major problem.

will this have any side effect?

I wanted to pass PHP variables to Javascript without triggering any new http request (aka: inserting it directly in markup). But I wanted the content as is (without any sanitization that could change my values, even if they where markup itself). Of course I wanted to keep it safe as well.
The best way i've came up so far includes json + base64_encode + data uri schemes:
<script type="text/javascript" src="data:text/javascript;base64,<?php echo base64_encode('var thing = '.json_encode($thing)); ?>"></script>
My question is: will this have any side effect? can I safely use this?
I certainly wouldn't do this. You're introducing unnecessary compatibility problems (IE). By base64 encoding, you're bloating the size of your JSON by ~37%.
<script type="text/javascript">var thing = <?php echo json_encode($thing); ?></script>
Realistically, the only problem you might run in to is if $thing has a '</script>' in a string somewhere. (It looks like json_encode() actually escapes all forward slashes /, so this isn't a problem.) HTML parsers will ignore anything else that might look like markup in a <script> block.
You do have to watch out for text encoding if your page isn't UTF-8.

What's IE6/7 safe way to pass json_encoded data from PHP into jQuery/Javascript?

I have several situations where I need to pass multi-dimensional PHP arrays into Javascript/jQuery. The PHP function json_encode() seems to do this rather well. I've seen some examples that use $.parseJSON, but I'm not sure if this is for IE6 compatibility or some other issue. Can anyone elaborate if this is the correct format to use in JavaScript. Assume this is javascript/jQuery as part of a PHP view.
var sections = <?php echo json_encode($sections); ?>;
Or, perhaps this would be better?
var sections = <?php if (!empty($sections)) { echo json_encode($sections); } else { echo "new Array()"; } ?>;
Or, do I need $.parseJSON? It seems to throw an error.
var sections = $.parseJSON(<?php echo json_encode($sections); ?>);
Does anyone know of any IE6 issues I should be aware of? If I should use parseJSON(), is it used with single or double quotes?
Thanks in advance,
Jeff Walters
I don't know anything about IE, but as long as you aren't dealing with JSON strings in JavaScript you will not need any parseJSON function. Just putting them out into the script text should be fine.

Clean php output into javascript

Due to the nature of my project. I am pulling data from my db and outputting to javascript. Things were working just fine till I got to the main content. It has strings like (;, :, - ''). How do I ensure that these are displayed without crushing my script coz as for now nothing seems to work.
If all you have is a single string value then see answer by Tomalak Geret'kal.
If there is any chance of getting something more than a single value from your database, like an array, object, null, or anything more complex, then I would suggest using json_encode. By using something like this:
<script>
var your_JavaScript_variable = <?php echo json_encode(your_PHP_variable); ?>;
</script>
you can pass complex data structures, arrays, or even single strings from PHP to JavaScript with all of your backslash escaping done automatically.
Additionally when you use JSON for moving your data from PHP to JavaScript it will be easy to make your application get the data from your server asynchronously without page refreshes using AJAX in the future.
You can use the PHP addslashes function for inserting into Javascript, and htmlspecialchars for inserting into HTML.
You should be encoding that data into json. PHP has a handy function to do this, json_encode.
Be sure to use the JSON_HEX_QUOTE option or the quotes in your data will break your js.
Read this: http://php.net/manual/en/function.json-encode.php

using php include in jquery

What im trying to do, is use php include within a jquery append attribute. something like this:
$('a.popup[href^=#]').click(function() {
$('body').append('<div id="content" class="popup_block"><?php include( SITE_URL . 'activity/popup.php' ) ?></div>');
My script is in a php file, server side, so that i could accomplish this, but im not sure how to go about it. When it comes to html, css etc. I can combine it and php within the php file, but when it comes to javascript, its the quotes that confuses me, and when and how to use the brackets. This might sound confusing lol. Anyways, does CDATA have anything to do with it? I've never used it before, but I should atleast learn it's use.
The PHP interpreter will only look for <?php and ?> tags and try to evaluate anything in between. It doesn't care about surrounding quotes. You need to make sure though that the result of whatever PHP does is valid Javascript.
var foo = '<?php include 'foo.php'; ?>';
becomes
var foo = 'This is the content of foo.php.';
after PHP is done with it.
If there are any quotes in foo.php, it may become this:
var foo = 'This is the 'content' of foo.php.';
which is invalid Javascript syntax. You'll need to escape any character of foo.php that may cause such invalid syntax, for example with addslashes. This can be quite cumbersome though, so I'd advise to look for an alternative this to begin with.
You can encode the value using JSON, which is definitely syntax safe:
var foo = <?php echo json_encode("Some string with 'quotes'."); ?>;
Generating code in code is always tricky, try to not do it and stick to language neutral data interchange formats like JSON or XML.
If you are 100% sure you don't have any single quotes in your include, there should be no problems with how you have it.
If you want to visualize it, copy all of your generated code from the included php file and paste it right into the main page inside of the append(). See how it looks. This will give you a good idea of what the browser will end up with.

Categories