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 .
Related
I am trying to execute a javascript script but I am not sure how to do this. I usually work in PHP but for this specific thing I needed to implement some javascript. On my website I have a couple of buttons with different ID's. When a button gets pushed, a javascript will run. Inside the javascript the ID will be used to execute a php page. Right now I am using the button to delete a certain thing.
For instance, let's say I push the button with ID= 20. Then I would need the page to run the follow script:
$("button").click(function() {
$.get("example.php?id=(this.id)");
});
As you can see I am trying to execute the page example.php?id=20 but this is somehow not working and I have no idea how I would fix this. Is there a different way to solve this problem? Btw, I use this as button
<button id="<?php echo $id; ?>" class="btn btn-primary sweet-4" onclick="_gaq.push(['_trackEvent', 'example', 'try', 'sweet-4', 'this.id']);">Test</button>
There are some more things happening here, but the main thing I want happening is getting the ID. Thanks in advance.
JavaScript doesn't have string interpolation (unless you use a template literal, but there's no IE support), so you will have to concatentate.
$.get("example.php?id=" + this.id);
$.get("example.php?id=" + $(this).attr('id') );
Everything inside of quotes is interpreted as a String, not as a Javascript key word. It looks like you're trying to use parentheses to interpolate the string held in this.id. You can't do that in Javascript.
$.get("example.php?id=" + this.id );
I am trying to create a preview HTML division wherein I face a challenge.
When I try to get code from the textarea and print it in the HTML, I could not see the PHP code. Here's are my codes,
HTML Where the code from textarea will be printed
<pre id='pques'></pre>
jQuery code that will take value from textarea and put in the above HTML pretty print area:
jQuery(document).ready(function($) {
setInterval(function(){
$("#pques").html($("#eques").val());
}
});
Value inside the textarea with id=eques
What will be the output of the following php code?
<div class="code"><?php $num = 1; $num1 = 2; print $num . "+". $num1 ; ?> </div>
Someone kindly help me to achieve this. I want somewhat similar functionality to the stack overflow question preview stuff.
Thank you.
The simplest way to do this is to escape the angle brackets in the PHP open and closing tags as HTML entities:
<?php .. ?> becomes <?php ... ?> - PHP will not treat this as server code and will ignore it, but the browser will display < as < and > as >. This way you don't need JavaScript to do it, you can print it directly to the page. I would advise always HTML encoding any PHP code that is input on your site, and storing it with entities rather than executable code.
As you use jquery, you can achieve this as described here
This will escape the brackets as #kallum-tanton already pointed out.
I'm wondering if JavaScript has a writing format for using html elements that have both single and double quotes inside JavaScript functions. May be something like heredoc for javascript or it could be a function in jQuery.
I couldn't find a solution to my problem and will try to describe it below:
I am writing a web page on php. I have a page and there is a form in it. There is a jQuery function that appends select elements to a form. After appending, user selects some options and submit the form. (I really wanted to paste a whole code here to make it clearer, but there is a big amount of code which is not so nice, so I tried to simplify it for you, sorry for some bad code)
I have a php variable like this one (select has onchange event, showUser is a function with AJAX request):
$string = <<<EOT
<select name="sapak[]" onchange='showUser(this.value, document.getElementsByName("dereje[]")[0].value)'>
EOT;
And there are many option in between and of course closing </select>(I didn't write all the code to be shorter). A part of jQuery function that appends select to the form:
$(wrapper).append('<div> <? echo $string; ?> Del</div>');
My problem here is that in $string variable I have to use single and double quotes, and when it comes to append() function in jQuery I use quotes again. And all these give me error in browser's console Uncaught SyntaxError: Unexpected identifier, because of single quotes started at append(' , but ending at onchange=' . Is there are any smart solution for this? I thought that heredoc will be, I've googled and I think that actually there is no heredoc for javascript. May be some other formattings available?
This should work :
$(wrapper).append("<div> <? echo $string; ?> </div>");
$string = <<<EOT
<select name=\"sapak[]\" onchange=\"showUser(this.value, document.getElementsByName('dereje[]')[0].value)\">
EOT;
As #Imperative advises about character escaping
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>';
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>