Postpone execution of <script> in HTML - on user's request - php

I've got a block of PHP generated JavaScript code for WYSIWYG editor which looks like this:
<script>
code contains ', " etc.
</script>
As soon as this script appears on page, specific textarea is replaced by WYSIWYG. But I want to do this only when user asks for it. The problem is, I cannot get this JavaScript into PHP variable, because the editor's PHP method replace() echos the javascript right away.
So I want to put this <script> into a variable so that I could call it later when user requests it. Is it possible?
One solution came to my mind - put this <script> into external HTML file and load this file via AJAX.

Why not just have your script echo into a JS function, like this:
<script>
function enableWYSIWYG() {
// body of your code here
}
</script>
Then have a button that calls that function to enable the editor.

In php one can use output buffering to take any function that outputs text (and even text like this ?> TEXT <?php) and store it in a variable.
You'd do something like this:
ob_start();
replace(); // or whatever the function that generates the javascript is...
$script = ob_get_contents();
ob_end_clean();
In order to be able to call this later you could then do something like this:
$script = str_replace('<script>', '<script>function showEditor() {', $script);
$script = str_replace('</script>', '}</script>', $script);
echo $script;
This is rather hackish and could end you up in a lot of trouble later on especially if the called code changes), so I wouldn't be the one to recommend it. It may be the easiest way to do this, though.

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 isn't running in php function

Where am I going wrong with my programming logic here?
I have 2 php files. File 1 includes File 2. File 1 calls a php function from File 2. Inside the php function there is a bunch of html. The html works perfectly. At the end of the function I have this javascript....
<script type="text/javascript">
alert('hello');
</script>
This javascript isn't alerting "hello".
What am I doing wrong?
Thank you in advance.
EDIT: New question because I skrewed the last one up.
In theory would the code below run properly? (yes/no)
<?php function AlertHelp(){
?><script>
alert('help');
</script><?
AlertHelp();
?>
Long shot on a wild guess here with the limited information you gave.
My assumption is that you are not "including" the file via PHP's include, require, include_once or require_once functions, but are in fact using AJAX to load in the page's content.
If this is the case, then I shall also assume you're using innerHTML to put the content on the page.
Suddenly the solution is obvious: <script> tags added by innerHTML are not parsed and run. You could probably do something like this:
// assume `result` is the variable containing the AJAX response and `elem` the element it goes in
elem.innerHTML = result; // this doesn't change
result.match(/<script[^>]*>([\s\S]*?)<\/script>/i,function(m) {eval(m[1]);});
Please note however that eval should be avoided if possible. Consider redesigning your layout to use callbacks instead.

AJAX - replace javascript in page: ajax won't replace the javascript

I'm trying to replace a bit of javascript in my page via AJAX, but for some reason, AJAX wont replace it...
When I use:
alert(document.getElementById('treintracking').innerHTML);
I can clearly see the javascript from the script piece: (this is the opening line of the javascript piece)
<script type="text/javascript" id="treintracking">
For replacing the script I use this:
document.getElementById('treintracking').innerHTML = responseText;
So, why does AJAX not want to replace the javascript?
I've tested, and the php file used to generate the replacement javascript, works fine.
I also took into account that the to-be-replaced javascript already has tags around it, so I removed those in the php file.
But it still wont replace the content...
Also, if it put somefunction() in that javascript, will it then run, or do I have to do something special?
Note: the javascript script is generated in a php file.
SOLUTION:
I am now using this external solution, I don't have a clue how it works, but it works perfectly:
http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
[I took the loading script from the page source, as it wasnt in the article itself...]
Adding JavaScript via innerHTML does not get evaluated.
If you want to add new code, just set the source to a new external JavaScript file.
So instead of using an Ajax call, you just set the src
document.getElementById('treintracking').src = "new/path.php?a=b";
Another solution [that I would avoid at all costs] is eval().
You'll probably have to embed the new javascript inside a function, which may assign new contents to other functions, and then invoke the outer function. Won't be terribly pretty.

php custom forum error

i have a form, and i want to have it be limited at 10 characters minimum. that is no problem, but what i want to do is echo the error at the top of the page, which is being included, so i cant just do:
echo '<div class="error">Error</div>';
i want to have a designated div that is empty (will be on the included header page), but when there is an error it gets filled with the error text to output. anyone know how to do this not using sessions or cookies?
This is a clear use-case for javascript. PHP is strictly a server-side language; that is, the code you write is executed on the server and not the client. Javascript, on the other hand, is run inside the user's browser. So say you create a div like so: <div id="error_msg" />. Then you can write a snippet of javascript code that looks like this:
function display_error () {
var err_msg_div = getElementById("error_msg");
err_msg_div.innerHTML = "Error";
}
You would place this code in script tags at the top of your page inside the tags. More information on javascript form validation can be found here: http://www.w3schools.com/js/js_form_validation.asp
Hope this helps.
-tjw
Edit: if this isn't exactly what you're looking for, you might want to tag this post with 'javascript' to get more people who know about js form validation to answer the question.
<div id="error_msg" /></div>
<script>
function display_error (text) {
var err_msg_div = getElementById("error_msg");
err_msg_div.innerHTML = text;
}
display error('Error: your text here..');
</script>

disabling javascript codes using php?

is there a way to disable javascript codes in a particular page using certain php codes? I need to ensure that all the javascripts used in a page should not give any result (even errors) when run.
Why don't you just not send the javascript down for those particular pages?
You could throw PHP conditionals around the Javascript so they won't display on your page:
<script type="text/javascript">
<?php if($showJavascript): ?>
// executes the following function
myJavascriptFunc();
<?php endif; ?>
function myJavascriptFunc() {
}
</script>
And to resolve any issues from my comments:
<?php var showJavascript = <?php echo ($showJavascript) ? 'true' : 'false'; ?>;
<script type="text/javascript" src="myFile.js"></script>
In the last case you should check the boolean value of showJavascript in myFile.js.
The easiest way (and the dirtiest, slowest, etc) is to turn on the output buffer at the start of the page, and, before echoing the buffer's content at the end, remove all traces of javascript, either through regular expressions, a html parser, or a combination of both.
<?php
ob_start();
// your code here
$output = ob_get_contents();
ob_end_clean();
// Purge your $output here, remove all <script> tags, onclick events, etc.
echo $output;
?>
How to purge the output has already been answered on SO many, many times.
There is no such way because PHP run on your server and JavaScript runs client-side once your server has done it's part and it's done by browser.
What you can do is make sure that your JS doesn't have errors or remove all the JavaScript.

Categories