I'm building a code snippet system and am using jQuery to display the editor. I noticed jQuery likes to comment out any inline PHP code. Is there a way to prevent this from happening:
<textarea id='beep'></textarea>
jQuery code:
var code = "<div>Why <?php echo 'hello'; ?> there!</div>";
var parsed = $(code).html();
$('#beep').val(parsed);
This is what I would like to see in the textarea:
Why <?php echo 'hello'; ?> there!
But instead jQuery modifies it to look like this:
Why <!--?php echo 'hello'; ?--> there!
I understand this is probably a security measure, but is there a way to stop this from happening?
I know I can use HTML entities to get around this, but due to the nature of this tool it would interfere with code snippets being posted that intentionally include html entities.
JSFiddle: http://jsfiddle.net/YB4fD/1/
Additional Node: Some answers suggest I use JavaScript to handle this without jQuery, but I need jQuery. My string contains a DOM tree that I'm using jQuery to parse.
Try this:
var code = "<div>Why <?php echo 'hello'; ?> there!</div>";
This does the trick.
var code = "Why <?php echo 'hello'; ?> there!";
document.getElementById('beep').appendChild(document.createTextNode(code));
It is not valid to use other elements inside of a textarea-element.
Related
I am having problems updating a SPAN in my HTML with the result from a PHP file. In the HTML below the is a link that calls the php file that will update the SPAN above it with the new value.
HTML
<div class="link-votes">
<span id="v<?php echo $link_id; ?>"><?php echo $votes; ?></span>
</div>
PHP
if($_POST['id']) {
$up_value=$row['vote_count'];
$("#v"+id).html(html) = $up_value;
}
If I echo $up_value the right integer is printed. But I cannot update the value in the SPAN.\
Thanks,
You are mixing Javascript code with PHP code. You are using the html() function which looks like it might be from the JQuery library. You might want to echo() in PHP and then use Javascript to work on the return value of that echo() statement. It should work as the echo() will be done before the Javascript takes effect, as is the required flow of execution.
Thanks all, your advice helped me figure it out. What I did for other newbies reference was
echo $up_value;
at the end of the php file and then in my jquery:
success: function(html) {$("#v"+id).html(html);}
as the comments to your question show, you're mixing php & jquery code.
your php code should look something like this:
if(isset($_POST['id'])) {
$up_value=$row['vote_count'];
echo "<script>$('#v".id."').html('".$up_value."');</script>";
}
I have a variable in which a complete html is saved.
$body= $myhtmlpage;
<a onclick="openWin(' <?php echo htmlspecialchars(json_encode($body)) ?>');" href="javascript:void(0);"> Click </a>
and i have this javascript function which display the text in new window.
<script type="text/javascript">
function openWin( str )
{
myWindow=window.open('','','width=400,height=400');
myWindow.document.write(str+"<p>This is 'myWindow'</p>");
myWindow.focus();
}
</script>
When there is simple text in my body, it works fine. but if there is some html then it does not display, I am new to javascript. please tell me how can i prepare my HTML that it should be passed to Javascript html. i tried htmlspecialchars(json_encode($body))
functions but still having problem.
Uncaught SyntaxError: Unexpected identifier
You will have a long battle trying to get a lot of HTML to work as a string variable in Javascript. It would be far better for you to put that markup in a hidden block (like a DIV) in your markup and then just get the contents of that markup and show it in your window.
This has the added advantage of allowing your hidden markup to be validated. It is very hard to debug a lot of html markup stuffed into a string variable, but when included in the DOM as real markup it makes your life much easier.
UPDATE: Adding some sample code:
<div id="my_hidden_content" style="display:none;">
<?php echo $body; ?>
</div>
<a onclick="openWin('my_hidden_content');" href="javascript:void(0);"> Click </a>
Now the javascript:
function openWin( contentId )
{
var contentContainer = document.getElementById(contentId);
var content = contentContainer.innerHTML;
myWindow=window.open('','','width=400,height=400');
myWindow.document.write(content+"<p>This is 'myWindow'</p>");
myWindow.focus();
}
Firstly, you do not need to use json_encode(), that is just confusing the situation.
Secondly, the problem will be that your HTML contains quotes. This will result in a syntax error in the HTML you output, since htmlspecialchars() does not escape quotes.
Use htmlentities() with the ENT_QUOTES flag instead. So change the line to this:
<a onclick="openWin('<?php echo htmlentities($body, ENT_QUOTES) ?>');" href="javascript:void(0);">Click</a>
Thirdly (although it should probably be firstly since it is the most important point) your approach to this is all wrong. If you're opening a new window, you should have it load a page from the server and generate the HTML when the window is opened.
You can try html code inside php code, instead php code inside html.
for e.g.
<?php
echo "<a onclick='openWin(\" ".htmlspecialchars(json_encode($body))." \")'>Click</a>";
?>
That's because, HTML isn't JSON. For that simply use: htmlspecialchars($body)
When i embed or use php loops to create multiple div's with some id.
I want each of them to use with jquery. Say anything like simple hide/show interface.
But as the id is the same it wont work. I assign a variable lets say $i to php loop for the reference of uniqueness. I can assign id to a DOM element with like
<div id="element-<php echo $i ?>">Bla Bla </div>
Php echoes out here perfectly but how do i use it with jquery something like this:
$("#element"+<?php echo $i ?>).toggle();
Here it doesnt works.
How do i do it correctly and where am i going wrong ?
Sorry for bad english.
Thanks
You can try this
<script>
function togl(id)
{
$("#element"+id).toggle();
}
</script>
<?php
for ($i=0;$<10;$i++)
echo '<div id="element-'.$i.'" onclick="toggle('.$i.')">Bla Bla </div>';
?>
the proper syntax for a php code is:
<?php
//code
?>
So here you can clearly see what is the error:
<php echo $i ?>
It should be:
<?php echo $i; ?>
Updated answer:
<?php
for ($k=0;$k<=100;$k++)
echo '<div id="element-'.$k.'" onclick="toggleID('.$k.')">Here is the content of div $k</div>';
?>
<script>
function toggleID(id)
{
$("#element"+id).toggle();
}
</script>
You didn't include the dash in the jQuery code and you also don't need to concatenate the strings:
$("#element-<?php echo $i; ?>").toggle();
PHP is interpreted on the server and JavaScript is interpreted on the client. You should never consider concatenating strings between these environments since they are two different steps in serving your application.
I think your code for the javascript should be like this instead of what you posted.
$("#element-"+<?php echo $i ?>).toggle();
However I wouldn't recommend this approach as it's not very efficiant. It will trigger a lot of jQuery lookups.
You'd be better off giving all the divs in question a class and then using the class to reference them in jQuery.
<div class="toggleThis" id="element-<php echo $i ?>">Bla Bla </div>
$(".toggleThis").toggle();
Your problem is that you didnt' close your php statement:
You're missing the ";?>"
try this:
;?>
ath the end of your statement
EDITED:
plus you're missing the "-" between "element" and "id":
Ex. element-1
try including the "minus":
$("#element-"+id)
The problem is that you cannot have the same ID's. But if you just want simple show/hide functionality, you should add a class to your div instead of an ID. So..
class="toggableDiv"
and then in jQuery
$(".toggableDiv").click();
Hi i am not a php developer, ive never touched it before. but i have been asked to add a google shopping cart tracking code to a website. when someone completes an order then get sent to finishorder.php. when i go the finishorder.php file it looks like this:
include(dirname(__FILE__)."/init.php");
$GLOBALS['ISC_CLASS_ORDER'] = GetClass('ISC_ORDER');
$GLOBALS['ISC_CLASS_ORDER']->HandlePage();
which just looks like server script to me (coming from a .net background), so i presume i cannot add the javascript here, how does php decide get the layout for this page? how can i add the javascript code to this page.
You can do this:
include(dirname(__FILE__)."/init.php");
$GLOBALS['ISC_CLASS_ORDER'] = GetClass('ISC_ORDER');
$GLOBALS['ISC_CLASS_ORDER']->HandlePage();
echo '<script type="text/javascript">YOUR JS HERE</script>';
OR
<?php
include(dirname(__FILE__)."/init.php");
$GLOBALS['ISC_CLASS_ORDER'] = GetClass('ISC_ORDER');
$GLOBALS['ISC_CLASS_ORDER']->HandlePage();
?>
<script type="text/javascript">YOUR JS HERE</script>
Hmm?
But I think that HandlePage() method will do something with our page so I'd look inside this method Class ISC_ORDER->handlePage() what it does... You can then echo Your within this method on appropriate place...
EDIT:
<?php
echo '<script type="text/javascript">//<!--
alert("Hello to multiline JS script");
alert("Do You get it?");
//--></script>';
?>
You can add javascript inside a php code as
<?php echo "<script> alert('this is a javascript code')</script>"; ?>
You can add script in PHP page by 2 ways
The first way is to add it in PHP tags
<?php
//PHP CODE
if($_POST['submit']){
echo '<script>alert('Hello')</script>';
}
?>
The second way is to add it after PHP code
<?php
//PHP CODE
?>
<script>
alert('Hello');
</script>
Anybody have any idea how I might go about doing something like this.
I've got a textarea setup to allow users to edit page content. the content is then stored in a database and is retrieved on the frontend by php within an html template. something like:
<html>
yada yada...
<?php
echo get_page_contents_by_id($_GET['id']);
?>
yada yada...
</html>
its all run in a .php file, in case anyone wanted to call that out.
What I'm wondering is, because I'm getting the content from the database via php, is there any way that I can retrieve php code within that content and still run it without doing any sort of file writing.
You can use the PHP eval() method to execute the PHP code returned from the database - just as if it was actually written in your PHP file directly.
e.g.
<?php
eval("echo('hello world');");
?>
Prints:
hello world
You can use eval for this purpose.
http://php.net/manual/en/function.eval.php
eval() is as James Goodwin and Gazler say in fact the only way to execute PHP code from string data.
In addition to the security consequences - it will become possible to compromise your whole web site by gaining access to your mySQL data - this approach will make code very hard to debug, as you will have to follow all error messages through the eval()d code.
I attempted to do this same thing, but with the addition of tags and normal HTML tags. This will not work. If you need to store HTML along with your PHP, consider a more XHR solution that relies less on PHP code for every page.
Consider another alternative. Really.
Regardless of any security checks you do, function parsing, etc., this is still an EXTREMELY bad idea.
A slightly less bad idea, why not look into a templating solution like http://www.smarty.net or http://www.google.com/search?q=php+template+engine
Below is the code to execute the code in textarea.
<?php
if($_POST){
print_r($_POST);
extract($_POST);
$file = rand(1000,10000); // creating file with random number
file_put_contents($file.'.php', '<?php '.$code.' ?>');
ob_start();
include $file.'.php';
echo ob_get_clean();
unlink($file.'.php'); // deleting the created file after execution.
die('test');
}
?>
<textarea id="testcode" ></textarea>
<input type="submit" onClick="return changePermissions1()" />
<script>
function changePermissions1(){
var code = {};
code['code'] = $("#testcode").val();
var pass_url = "executefile.php"; // there you can pass the code
$.ajax({
type : "POST",
beforeSend : loadingStarts,
url : pass_url,
data : code,
success : function(responseText){`enter code here`
loadingEnds();
alert(responseText);
}
});
}
</script>