How to store javascript code without it executing? - javascript

I'm trying to have adsense javascript code added to a designated div location using jquery but it seems javascript code does not sit well inside a jquery variable. It executes. I've tried using php's htmlentities to encode it for storage, but I can't get it to decode naturally. What should I do? Do I need a javascript based replacement for htmlentities_decode?
This is how far I've gotten, and .html() is not automatically decoding the htmlentities encoded html.
var html_1 = "<?php echo htmlentities('<script>adsense ad code here</script>'); ?>";
if (html_1)
{
jQuery('#id_wpt_adblock_1').html(html_1);
}

It seems like you could just put the javascript code in its own function, then just execute that function whenever you need it. That sounds so obvious that you must have eliminated that option already, but why?

<script> tags are automatically executed when they are added to the DOM. So, when the string is added via html(), the <script> is added to the DOM, and than ran.
The issue here, is the <script> tags in the string. When the browser sees 'em, it may try to run the script. Try to change the string to this:
var html_1 = "<?php echo '<scr"+"ipt>adsense ad code here</scr"+"ipt>'; ?>";
This should output:
var html_1 = "<scr"+"ipt>adsense ad code here</scr"+"ipt>";
Which should work.
EDIT: You said this string is in a variable, try using str_replace to replace the tags.
var html_1 = "<?php echo str_replace(array('<script>','</script>'), array('<scr"+"ipt>', '</scr"+"ipt>'), $_SESSION['wpt_ad_content_1']); ?>";

document.write('<script src="your_script.js"><\/script>')</script>

Related

Double Nested PHP and Javascript with jQuery

I've run into a bit of a design problem. I have a webpage with a button. The page is written in php. The php outputs HTML that uses jQuery to initialize a button. When I click that button, a jquery dialog appears. The contents of the dialog are created from an object in PHP. and passed from a php object, but require formatting in Javascript, which is also passed from the php object.
A simplified version of the code would look like this:
$obj = new Custom_Object();
echo <<<EOD
<input type="button" id="button1">
<script>
$("#button1")
.button()
.click(function(){
var dialog = $("<div>" + {$obj->print()} + "</div>");
dialog.dialog();});
</script>
EOD;
with $obj->print() looking something like:
$return = "<p>Some HTML</p>";
$return .= "<script>Some Javascript to format the 'Some HTML' paragraph</script>";
return str_replace(array("\r", "\n"), '', $return);
My questions: (1) Is there some obviously better way of writing this code that just isn't occurring to me; and (2) how does the browser deal with the fact that there are two sets of \script\ tags nested inside of each other? (For some reason the code doesn't work and I am guessing that this is what is causing it, but I am not sure).
Answer to question 1:
You could just write your normal HTML and then insert the PHP values inside of it, without using a heredoc, like so:
<?php $obj = new Custom_Object(); ?>
<input type="button" id="button1">
<script>
$("#button1")
.button()
.click(function(){
var dialog = $("<div>"+<?php {$obj->print()} ?>+"</div>");
dialog.dialog();
});
</script>
Answer to question 2:
The second script tag is not being nested inside of the first, it just seems like it. The second script tag is actually being inserted in a completely different place in the DOM by jQuery after your code is interpreted.
If you think it may be getting interpreted incorrectly, you should try wrapping your JavaScript in CDATA tags and escaping quotes properly inside of the string generated by PHP.
You can achieve a lot more stability by simply "closing" your php tag and re-opening it later in the document.
So for instance, you could have:
<?php
$obj = new Object();
?>
<input type="button" id="button1">
<script>
$("#button1").button().click(function(){
var dialog = $("<div><?php $obj->print(); ?></div>");
dialog.dialog();
});
</script>
Just remember that what ever you output from $obj->print(); will need to have double-quotation marks escaped
Most modern browsers are able to work very well with more than 1 tag.
I'd also advise that you set the script type by changing your opening tag to .

Display Javascript/Html/PHP as text

I am trying to display code on a webpage, just as text, for the user to view. The code snippet is obtained from a database, input using a form, and put in a div using PHP. Jquery is then used to replicate the html of that div in another element. The code from the database will never be executed; I am basically just making notes.
Code example: alert('Hello'); (could be PHP or html)
What is the best way of displaying this as text, in my browser?
Filter it somehow using PHP as it is input using a form.
Use of HTML tags (pre, xmp tags, CDDATA).
Convert special characters with some javascript function.
combination of the above.
Example of use below.
PHP
$inputQuery="SELECT x FROM y";
$input = mysqli_query($dbc,$inputQuery);
$row = mysqli_fetch_array($input);
//no issues above, just used to clarify the issue. If $input is javascript code, the below doesn't work.
echo'
<div id="inputCode">'.$row["x"].'</div>';
JAVASCRIPT/JQUERY
var inputCode = $("#inputCode").html();
$( "#displayInputCode").html(inputCode);
Use htmlentities() to convert all the HTML special characters to entities, so they won't be executed:
echo'
<div id="inputCode">'.htmlentities($row["x"]).'</div>';
For HTML you can use htmlentities() which would protect against malicious data like <script> tags that include bad stuff; and for PHP you're already fine since echo'ing PHP code does not execute it (and browsers doesn't execute PHP code either).
Example code :
echo '<div id="inputCode">'.htmlentities($row["x"]).'</div>';

Trying to parse webpage using php

I am trying to parse a webpage and print out a table which is on the webpage. I am using php_simple_html dom parser. However, when I try to parse the table off the webpage, all the javascript commands to output the table get turned into comments within the php:
<html>
<script type="text/javascript" src="jquery.js"></script>
<?php
include 'crawling/simple_html_dom.php';
$html = file_get_html('http://uiucfreefood.com/');
$ret = $html->find('body', 0)->find('div', 10)->find('table',0); //gets to the table tag
echo $ret; // nothing is echoed out because the original webpage uses jscript commands to write the table to the page but these commands get turned to comments for some reason.
?>
</html>
When I inspect the element of the page where I am echoing the parsed information I am able to see that the table tag with all the info is in there but the jscript commands have been turned into comments. Is there a way for me to just grab the info and echo it out myself? I tried adding another ->find('tbody'); at the end of the parse command but it doesn't do anything. Any advice is appreciated. Thanks.
EDIT: You can try this code out yourself if you download the simple_html_dom.php and include it in your php file. Source: http://sourceforge.net/projects/simplehtmldom/files/
EDIT: Just noticed something really important. The javascript commands are commented out in the original webpage also. Instead, the original webpage is using a javascript function to print out the table which I do not have defined. Writing that function myself should fix the issue.
EDIT: yup, that worked.
Try using file_get_content instead of get HTML and see if that works. Honestly, depending on your needs, you should code your own parser. It is not that hard to write a parser for the table scan and display.
You will just need the following;
$array = split("<table>", $content);
$boolPlaceHolder = false;
and you can then set the placeholder to true when you encounter this way you can scan through the chars of the content and grab the table.
Hope this helps.

Assigning the value of "<script src=" directly to another element

Is it possible to assign a value of <script src="http://domain.com/external.php"></script> directly to another variable, like the following (not using JQuery, but simple Javascript):
<script>
document.getElementById('ID').innerHTML=<script src="http://domain.com/external.php"></script>;
</script>
maybe doing something like this is better
script=document.createElement('script');
script.src='http://whatever.js';
document.getElementsByTagName('head')[0].appendChild(script);
If you're trying to append the script inside the DOM as a string, you have to do something like this :
var script = '<script src="http://domain.com/external.php"></scr'+'ipt>';
document.getElementById('ID').innerHTML = script;
the closing script tag will cause issues in parsing when inserted as a string because it closes the current script, concatenation will solve that.

Insert JavaScript code from JavaScript

i need gets a html code by jsonp like method, and display this on a div element. This works with simple html like an images, text, etc. But now the code can content a JavaScript tags and need insert this on a div, but the javascript, don't runs, i resume it with a example:
var div = document.getElementById('mydiv');
div.innerHTML = '<scipt type="text/javascript"> console.log('I run!'); </script>';
this don't works, too i probe:
var otherdiv = document.createElement('div');
otherdiv.innerHTML = '<scipt type="text/javascript"> console.log('I run!'); </script>';
div.appendChild(otherdiv);
But don't works too.
How I can insert the code in away that the JavaScript runs?
The most straightforward way is to extract all JavaScript and eval it.
You can extract JavaScript with a regular expressions like:
var match = html.match(new RegExp("<script[^>]*>(.+)</script>"));
console.log(match);
This is a far from optimal way of executing JavaScript, very error prone and possibly unsafe. I would strongly advise against it.
You should use a script loader like LAB, yep/nope, or Frame.js. The browser has built-in restrictions, script loading is the best practice for including scripts on a page.
You also would have to escape the single quotes.
console.log(\'I run!\');

Categories

Resources