Passing HTML to javascript function - php

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)

Related

Loading PHP function using jQuery onclick

I am trying to hide our mailing address on our website, until someone cliks a button to "load" the address. I am doing it like follows:
Homepage.php:
<button onclick="test()"> Click </button>
<div> </div>
<script>
function test(){
$.ajax({url:"address.php", success:function(result){
$("div").text(result);}
})
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Address.php:
<?php
function php_func(){
echo '<span><?php echo $address; ?></span>';
}
php_func();
?>
This works in echoing the text onto homepage.php, but it's not loading the PHP function. Just showing the function as text as seen here:
I tried $("div").write(result);} and it won't even load.
$address is already defined elsewhere. Any tips?
You're trying to write code which outputs code which outputs the address. Why? You're already in the context of outputting something from the PHP code:
echo "something...";
If what you want to output is the value of $address then just output that:
echo "<span>$address</span>";
I suspect the reason you did it that way is because you're expecting the currently loaded page to parse and execute that PHP code. This is a fundamental misunderstanding of how these technologies work. The PHP code for that page executed once, on the server, and delivered the resulting HTML/CSS/JavaScript to the client.
The AJAX operation is making a new, separate request to another PHP resource which will execute on the server and output back to the client. In this case it's just outputting a string value, which the client-side JavaScript code will then write to an element on the page:
$("div").text(result);
(This is a good opportunity for you to use your browser's debugging tools and observe the AJAX request/result in the network tab, to see what's actually being sent/received. At no point should actual PHP code be visible to the browser. All of that is executed on the server.)
The reason this is important is because, if this is the case, then you are likely misunderstanding where $address is defined. If it's defined in the PHP script which rendered the page you're looking at, that doesn't mean it's defined in address.php. If the code you're showing us for address.php is the entirety of that page then $address is not defined.
So you'll need to define $address on that page.
After having said all of that... You might find it much easier not to involve AJAX for this at all in the first place. Just output the address to the page but style the <span> to not be visible. Then when the user clicks the button, make it visible. No need for the complexity of an entirely new HTTP request:
$('button').click(function () {
$('span').show();
});
span {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click</button>
<span>this is the address</span>
You don't use <?php echo inside strings; that's only used when you're in a section of the script that's outputting literal text, not executing PHP code.
If you're in PHP code doing echo, you use variable substitution or concatenation.
<?php
function php_func(){
echo "<span>$address</span>";
}
php_func();
?>
You'll need additional code to set the $address variable; I assume you just left that out for simplification in the question.
<?php
function php_func(){
echo '<span>' . $address .'</span>';
}
php_func();
?>
this should work, u can't use 'echo' and inside echo open 'php' tag to use again.... more another 'echo'

Javascript function to return PHP get_file_contents

I am stumped here, have asked this a few different ways. What I need to do is return the contents of a text file in PHP on click of an a tag. I thought it would be easy enough to just have the click and ID of the anchor tag in the JS and put the PHP method in the template like so. $textPath is var that points to the file in the settings. It goes to a help section and the text file authenticates the user. So the UL ends up being www.blahblah.com/help
<li><a id="help" target="_blank"><? echo file_get_contents($textPath);?> </a></li>
//Simple JS (part of another 'open' function for the menu)
$('#help').attr("href", "/help")
But it's still not working at all. Any ideas? Thanks
Highlighting a part of your code here:
<a id="help" target="_blank"><? echo file_get_contents($textPath);?> </a>
See you are using the shorthand echo tag. The opening tag should be <?= insead of <?. And since this is a shorthand echo tag, you don't need to use the echo construct.
This shall work fine:
<a id="help" target="_blank"><?=file_get_contents($textPath);?> </a>
Quoting from the PHP Manual
echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled.
I have <?=$foo?> foo.
Coming to the question, you want to return the contents of the file. Your best bet will be achieving this via AJAX.
You can output as you wish. The best way will be to make a separate php file for handling all the ajax calls and return the output as plain text. To authenticate the user, just include the auth.php file(assuming that you are using one) in the ajax.php page.
ajax.php
<php
//Below code checks if a GET request is sent
if (isset($_GET['path'])) {
echo file_get_contents($textPath);
}
?>
jQuery
$('#help').click(function(e) {
e.preventDefault(); // Prevents the default action
// Send an AJAX request
$.get("ajax.php?path", function(s) {
//s is the responsetext. It contains the response from the server
your code here
});
});

Is it possible to use PHP DOMDocument to manipulate and return an HTML snippet?

Wordpress uses a filter called "the_content" I can hook into that allows me to manipulate the section of HTML that represents the inner contents of the body tag before its rendered. (This is not a wordpress question, I'm just providing context.) That means there is no DOCTYPE declaration.
Here is a snippit of code I'm trying to work with:
<div id="x-section-1" > lots of stuff and child divs</div>
What I would like to do is find this and then append a second div immediately after it. I cannot use string replacement / regex because the internal contents of this div change often. The only thing that is constant is the #id.
DOMDocument seems like the logical choice to do this. I've tried:
#$doc->loadHTML($content);
$snippet = $doc->getElementById('x-section-1');
However, this returns an empty result. Indeed, the PHP comments in the manual for getElementById state that if DOCTYPE isn't defined null is returned.
So based on similar questions on SE I tried DOMXpath:
$dom->loadHTML($content);
$xpath = new DOMXPath($dom);
$div = $xpath->query('//div[#id="x-section-1"]');
$div = $div->item(0);
$snippet = $dom->saveXML($div);
The problem here is that it returns the entire value of '$content'
Finally, another problem I'm having regardless is that I'm getting weird character formatting. Even though I said that regex / string replacement wasn't an option, that's not entirely true. The weird formatting only happens when I use a '$dom->save' function. If I can get the value of this div then I can append my new string to the end of it, and then find and replace.
Is it possible to use DOMDocument for this? If so, how? If not, what's another approach?
Note: This questions seems to be the closest to what I'm trying to achieve. However, the difference is that question is loading a full html file, which I'm sure has a DOCTYPE.
PHP DomDocument HTML Manipulation
as you mention you want to "append a second div immediately after (x-section-1)"
so you could simply use (jQuery/Ajax) for real time Action and avoid all brain Dizziness :
<script>
$(document).ready(function(){
$("#x-section-1").after("<div id='Second_Div'> YOUR HTML CODE HERE </div>");
});
</script>
replace "YOUR HTML CODE HERE" with any html code you want ,
or add php code [here][1]
➳ Note : if you want to Add Large html code then it most be stick to each-other without "enter space" example: $("#x-section-1").html('<div id="Second_Div"><label>Users Name:</label></div> <br>'); or you can separate the lines using + like that :
$("#x-section-1").after(
'<br> <div id="Second_Div">' +
'<form action="" method="post">' +
'<label>Users Name:</label>' +
'<br><select name="Users" id="UsersSelect">' +
'<option value="$id"> testUserName </option>' +
'</ select></ form></ div>'
);
or you can fill it using php $string that contain some data like :
<?php
// your string that can contain anything you want .
$test_string = "userId is :9000 ";
?>
<script>
$(document).ready(function(){
$("#x-section-1").after(<?php print $test_string; ?>);
});
</script>
or you can fill it with both (html + php).
and if you want your new code to appear after a (clicked Button) u can use :
$("#your button ID here").click(function(){
$("#x-section-1").after("<div id='Second_Div'> YOUR HTML CODE HERE </div>");
});
and dont forget to include [Ajax/jQuery link] in the begening of your page IF there is no one :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

jQuery is Commenting out my PHP Code Snippets

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.

PHP print content as it is

I have a textarea
<textarea id=view-body ></textarea>
that gets a content when an onclick from
<a href='#' onclick='popup_view(this)' data-body ='". $rows['body'] ."' >view</a>
<script language="JavaScript">
function popup_view(e)
{
var body = e.getAttribute('data-body');
el = document.getElementById("view-body");
el.innerHTML = body;
}
</script>
I wanted the content of my textarea to be printed the way it is.
For example the onclick sends
<i>Wired</i>
my textarea printout
<i>Wired</i>
but not, and supposed to be like this
Wired
Javascript innerHTML function will convert text to html form.
You can use textContent function as shown here
http://jsfiddle.net/yWgn7/
In jquery you can use .text() function, but i am not sure about textContent compatibility.
Instead of a textarea try using a div. If I'm understanding this correctly, the textarea is showing the <i></i> and you don't want it to. Textarea doesn't handle html formatting naturally.
HTML's built in <textarea> elements doesn't allow you to style it's contents. What you need is some kind of a wysiwyg editor to do that.
You can replace your text-area with any Rich text editor
http://ckeditor.com/
You must use the htmlentities function to replace special characters with html entities.
data-body = "<? php echo htmlentities($rows[' body ']);?>"

Categories