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.
Related
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'
Is it possible to use JS/JQuery from an external file? If so, what is the best practice?
What is the best practice to call a JQuery function inside a PHP or HTML page?
Here is file.php
echo "<table..";
echo "some code...";
echo "</table>":
<script type="javascript">
$('table').hide().fadeIn(700);
</script>
or:
echo '<script type="javascript">';
echo '$('#foo').toggle("slow");';
echo '</script>';
So, besides a best practice. is any of this possible? I can't seem to make it work from external file or directly.
also from external.js
$(document).ready(function(){ $('table').css({ // code here ... }); });
You can certainly echo jquery (or any html code) directly from PHP
echo '<script type="javascript">
$(\'#foo\').toggle("slow");
</script>';
Your issue in that one was the un-escaped quotes around #foo
I'm not really sure what you meant in the first part of your question, but since you have php I would use this option rather than trying to add jquery into an html file from another javascript file (if that's what you were trying to do)
Both internal and external javascript/jquery code should work.
Make sure you jquery script tag was include in you header/body
If external, make sure to include the external.js script tag after the jquery script tag
Make sure the document was ready first ( $(document).ready() ), and check again the selector either they are exist or not.
For more clean code, no need to echo every single line html code. Just close the php ( ?> ) and write the html as usual.
Please provide as much information as you can so that we know exactly what's the problem was.
I have a Wordpress based website, and some of the content is loaded through javascript.
For example:
jQuery(".portfolio-fs-slides").css({"display":"none"}).prepend('<div class="portfolio-fs- slide current-slide portfolio-ppreview"><div class="project-coverslide"></div><div id="content" class="content-projectc contenttextwhite"></div></div>');
What I want to do is append this shortcode: <?php echo do_shortcode('[daisy]'); ?>
But as far as I know is not really possible to append php code in javascript.
Is there any workaround to accomplish this ?
Thanks!
As #Bergi mentioned, the PHP will run serverside, and the JS will run client side. You can output JS (or parts of your JS) via PHP and have it run client side, e.g.
<script>
// extra code here
jQuery(".portfolio-fs-slides").css({"display":"none"}).prepend('<div class="portfolio-fs- slide current-slide portfolio-ppreview"><div class="project-coverslide"></div><div id="content" class="content-projectc contenttextwhite"></div></div>');
<?php echo 'we can output valid js here' ?>
// more code here
</script>
One way to think of this is that since PHP runs server side, it will always run before the JS is parsed.
Put another way, you could have a javascript line like this:
console.log(<?php echo $someVariable ?>);
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.
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>