How to modify a php string variable in javascript - php

I am using php4 and jquery, I have got a php string variable $content which stores a string as shown below.
<html>
<head></head>
<table>
<tr>
<td>comments:</td>
<td>Good</td>
.....
...n rows
</table>
</html>
So, Now i want to change the color of all occurrences of text "Good" to red. So How to write a jquery function which takes a php string $content variable and changes the color of each "Good" word, (adds a style color:red) and returns it.

Pure PHP solution:
echo str_replace('Good', '<span style="color:red">Good</span>', $content);

You cannot access PHP variables in Javascript. Also, javascript works on the client side and PHP works on the server side.
I am unsure of the exact usage for this, but, here's my take on doing this:
// in javascript code
var x = "<?php echo $content; ?>"; // do take care of stripping quotes (")
x.replace("Good", "<span style='color:red'>Good</span>");
I guess that should do it.
Just to explain a bit more, on the server, PHP will dump the contents of the variable $content to the variable x in JS. On the client side, when JS is executed, it will pick this up and do the replacement.

$("td").each(function(){
$(this).html($(this).html().replace(/Good/, '<span style="color:#f00">Good</span>'));
});
This will look through each cell and find if there is a text value of "Good" and wrap a span around it

$content .= '<span class="red">';
$content .= {your existing code here}
$content .= '</span>';
After it you create a CSS Rule:
.red{ color:red; }
As you see you don't need jQuery at all.

Related

Render html to page from database PHP [duplicate]

How would one go about showing PHP code on user end. Sort of like w3School does?
Having lets say a grey area div, and then showing the code in there without activating it?
You can use html entities <?php in the html it will be rendered as <?php
You can use htmlspecialchars to encode your code to use html entities.
Use <pre> or <code> tags to wrap your code.
Take a look at http://php.net/manual/en/function.highlight-string.php to further see how you can make the code look pretty.
Since passing a large block of code to highlight_string() can be messy, you may want to look at output buffering in combination with highlight_string to output colorized php code.
Something like:
<?php
ob_start();
?>
phpinfo();
echo "this echo statement isn't executed";
<?php
$code = ob_get_clean();
highlight_string($code);
?>
Simply you can use following code to display php code on webpage.
highlight_string("<?php print('This is php code.'); ?>");
It will give output like
<?php print('This is php code.'); ?>
The first step is to not wrap that code in PHP tags. So instead of this:
<?
var sample = "code";
?>
You would have this:
var sample = "code";
It's not the code itself which triggers the server-side compile from the PHP engine, it's the tags which indicate to that engine what blocks of the file are code and what are not. Anything that's not code is essentially treated as a string and output to the page as-is for the browser to interpret.
Once you're outputting the code, it's then a matter of formatting it. The old standard is to wrap it in pre tags to get rid of HTML-ish formatting:
<pre>
var sample = "code";
</pre>
You can also apply CSS style to the pre tags (or any other tags you want to use for displaying code, such as div) as you see fit.
There are also very useful code syntax highlighting plugins and tools to make the code a lot "prettier". Google-code-prettify often comes highly recommended.
Typically this is done by showing code within <pre> or <code> tags.
You can use this template........
######################################################################
echo "<h2><br>Source Code of ".basename((string)__FILE__) . "</h2><hr>";
show_source(__FILE__);
echo "<hr>";
echo "<h2>Output of ".basename((string)__FILE__) . "<hr></h2>";
#######################################################################
It will show the source code and output following.
use the header function of php, this will rea
<?php
header("content-type: text/plain");
?>
The PHP code will just be a string that you can echo or print onto the page, no different than any other data you want PHP to display for you. If you want to keep the formatting (ex. the indentation), put it inside a <pre><code> block.
Ex:
$php_code = '<?php $foo = bar; ?>';
echo "<pre><code>$php_code</code></pre>";

How to prepare PHP variable for Javascript array() use?

Let's say that we have input field or textarea where user can put anything. This means that user can put there:
text
white spaces
multilines
HTML tags
single and double quotes
slashes
and whatnot...
My current code does this: <?php $data = addslashes($content_of_input); ?>
and soon after that...
<?php
$php_generate_javascriptArray .='
javascriptArray[0] ="'.$data.'";
';
?>
<script>
javascriptArray = [];
<?php echo $php_generate_javascriptArray; ?>
</script>
Adding slashes unfortunately isn't enough - Javascript breaks when user puts for instance multiple lines or HTML links into that. Is there any way to prevent that and still ALLOW Javascript array to contain LINK, MULTIPLE LINES, HTML TAGS? I'm looking for some universal filters.
json_encode will convert a PHP data structure (or string, or number) to the appropriate JavaScript data structure while making it safe for injecting into a script element in an HTML document (by escaping slashes).
<script>
var data = <?php echo json_encode($data); ?> ;
</script>
Use PHP function urlencode(...)
or base64_encode(...) of need of more advanced protection.
I normal use urlencode and on Javascript side use unescape for decode the URL format data.

replace text on your page php something like element.innerhtml

hello i have been searching for some php code that is something like element.innerHTML in javascript but i can't find it. i need it for some code that for example goes from 1-60 in 60 seconds
but if i do that with echo it just places everything under each other and that should not happen. i need something that just replaces the text. i also don't want to reload my page every second and i don't have the ability to write to files ( i can read them). and please don't tell me that i should do it in javascript.
so can someone tell me how to do this?
You can use PHP to spit out javascript that does the replacing. There won't be a pure PHP solution to this since PHP is server-side and doesn't have access to the rendering of the page on the client side.
Suppose the text you need to change is in a <div> tag named 'replaceMe'. You will want to use the ob_flush() functions in PHP to force out the javascript at the time you need it to display. The PHP to initialize that is
if (ob_get_level() == 0) ob_start();
Then, each time you need to update, you have something like this in your PHP code that adds to the body of the page:
echo '<script type="text/javascript" language="javascript">';
echo "document.getElementById('replaceMe').innerHTML = 'Text for this iteration';";
echo '</script>';
flush(); ob_flush();
Of course if you want to make it easier for yourself, you can make a PHP function to print all this out given an argument containing the text to replace.
Then at the end you need to have
ob_end_flush();
to replace some text try str_replace http://de3.php.net/manual/de/function.str-replace.php
or case insensitive str_ireplace

How to clear all elements in a page with PHP?

Is there any way to clear all html elements in a php page?
For example I have 100 html elements in my page, is there anyway to remove them?
As we know with javascript we have innerHTML but in PHP what?
clear all html elements in a php page
That doesn't make sense. HTML elements only exist in the DOM after PHP has executed and sent an HTML document to the browser. Server-side, where PHP executes, there are no elements to remove.
If you're trying to manipulate the HTML you've already output, you need to capture it with output buffering (see ob_start, ob_get_contents and ob_end_clean) but if your goal is to "clear all html elements", presumably so you can output a different set of elements, you simply need to not output anything in the first case. If this sounds like what you're trying to accomplish, you need to look into simple conditional statements like if/else.
as we know with javascript we have innerHTML but in php what ?
There is no PHP-equivalent because PHP doesn't have access to the client-side DOM. It is purely a server-side technology, and the output of your PHP script is the input to the browser. The DOM and its elements are generated long after your PHP script has executed. If you have an XHTML fragment in a string, and you want to parse/manipulate it, you can use xpath.
If your question is "clear html elements in a php file", the answer is: strip_tags().
$string = '<p>hello</p>';
echo strip_tags($string);
Try this:
<?php
if(//why you want to clear the elements){
echo "<script language=\"javascript\">";
?>
//Append all elements in <div id="body">
var body = document.getElementById("body");
body.innerHTML ="";
<?php
echo "</script>";
#Output your new element
echo "New elements.";
}
?>
Try this, it should definitely work.
<?php
echo "<script>document.write('');</script>";
?>

Best way to incorporate javascript in php?

This is the way I am currently doing it.
<?php
//show footer
echo "<script type='text/javascript'>\n";
echo "alert('Congrats');\n";
echo "</script>";
?>
Is there a better way than just to echo it?
Just put your JavaScript code outside PHP tags:
<?php
// your PHP code goes here
?>
// your javascript function out of the PHP tag.
function f() {
alert('congrats');
}
of course
?>
alert('Congrats');
<?
If you really have to execute the js by printing it from the PHP, it would at least be cleaner if you had your js functionality stored in functions in some file and then called them by printing the calls.
I recommend reserving PHP files just for PHP code and keeping your frontend code (HTML/CSS/javascript) in separate template files.
Last time I checked, mixing the presentation layer & backend code into same file was popular about 12 years ago.
Your file hierarchy for a project could look like this:
- my_project
- lib
- PHP files here
- templates
- HTML templates here
- public <- this is your document root for web server
- index.php <- just a dispatcher
- js
- images
- css
Use HEREDOCS, or break out of PHP mode into "html" mode. If the Javascript is entirely static, or has a few parts that need to have some PHP value included, drop into html mode ('?>' out of php). This will allow any decent text editor to realize that you're doing HTML and Javascript, and syntax highlight as appropriate. The following are all equivalent, but decide for yourself which is more readable:
'pure php':
<?php
echo '<script>';
echo ' var x = [' . $somePHPvar . '];';
echo ' alert(x);';
echo '<script>';
?>
'heredoc' syntax:
<?php
echo <<<EOF
<script>
var x = [{$somePHPvar}];
alert(x);
</script>
EOF;
?>
'html mode':
<?php ?>
<script>
var x = [<?php echo $somePHPVar ?>];
alert(x);
</script>
plusses/minuses for each:
pure php: you can stay in PHP mode, and your echo + $vars will be highlighted as PHP code, but the html/javascript you're echoing will be treated as plain text and colored as such (ie: all the same color)
heredoc syntax: You stay in PHP mode, but gain the benefit of not having to escape any quotes (' and ") in your code, so any html will look cleaner. Most editors will recognize PHP vars in the heredoc block and color them appropriately, but the rest of the text will be treated as text, so javascript/html look the same. Also, you cannot insert function calls into the text. You have to do those BEFORE starting the heredoc and store the results in a var, which can be inserted. The HEREDOC can also be use to assign long text blocks into a variable directly.
'html mode': The editor will see/recognize your html, javascript, AND php and color them appropriately. But this is at the cost of having to sprinkle php open/close tags anywhere you need to fill in some value dynamically. On the plus side, you can directly insert function call results (htmlspecialchars(), urlecncode(), html_strip_tags(), etc...) without having to store the values in an intermediate var. It also makes for harder-to-maintain code as your PHP is now sprinkled randomly throughough the html/javascript code.
It all boils down to what's easiest for the particular code you're working on.
You can use the model-view-controller pattern for outputting JavaScript.
You can have a "view" file where most of your JS is stored:
myJavascript.js.php:
alert('hello bob');
alert('hello <?php echo $name; ?>');
alert('whats up?');
Your controller, jsController.php:
$name = "Jane";

Categories