Html text to JQuery with line break - php

following example:
I got a php function which generates me some text with "\n\r" at the end
The output is generated in a html div, which is hidden
JQuery takes the text of the div with innerText
Writes it in a other div
That's what i do in the moment.
The line break in php has no effect to the "end div".
How can i get the line break at the end div?
Regards
EDIT: With a <br> in my php function an alert works fine. So the failure is at point 4.
var text = document.getElementById("statistiktextdiv").innerText;
$jq( "#statistiktext" ).text(text);
<div id="statistiktext"></div>
function showsomething(){
for($i = 0; $i < count($statistik); $i++){
echo $something[$i]['number'] . "<br>";
}
}
?>
<div id="statistiktextdiv" style="visibility: hidden;"><?php showsomething(); ?></div>

You can use the javascript String.replace method to change the \n\r to a <br> tag so the browser will render it.
alteredText = originalText.replace( '\n\r', '<br>' );
You can see that the console and alert windows treat these special characters the way a text editor does, but they are not rendered as breaks in html.
originalText = "line 1\n\r\line 2";
alteredText = originalText.replace( '\n\r', '<br>' );
console.log( originalText );
console.log( '---------' );
console.log( alteredText );
$('body').append( originalText );
$('body').append( '<hr>' );
$('body').append( alteredText );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Something interessting:
When i write the text from JS to an textarea, its working!
So the problem seems to be the <div>.
I tryed with a random tag like <random>, it's not working.
Any ideas what is wrong?

Related

Echo empty space as html char

I have a string 90001 90002. I need to see which html special char is represented in the empty space. (It could be an empty space - or it could be a textual line-break masquerading as a space in HTML see here. Maybe other possibilities that I'm not aware of..)
I would like to echo a string and show the empty spaces as html char (e.g. $result = "90001 90002").
I've tried using html_entities but that doesn't cover spaces. Also neither does htmlspecialchars.
How would I go about doing this?
If possible I would like a purely PHP & html solution. If necessary - CSS. And if impossible otherwise, javascript will have to do..
Just an out-of-box thinking. I had the same issue but looked into using JavaScript's encodeURIComponent() function:
$(function () {
$("div").html(function () {
return encodeURIComponent($(this).html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>90001 90002</div>
Used jQuery as I am kinda lazy. You can do the same in JavaScript this way:
<div>90001 90002</div>
<script>
var div = document.querySelector("div");
div.innerHTML = encodeURIComponent(div.innerHTML);
</script>
Just letting you know that this is better to handle in client side than in the server side.
Update 2: Getting the HTML content and updating the text of the HTML:
$(function () {
$("div").text(function () {
return $(this).html().replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>90001—90002</div>
Something like this...
<?php
$mystring = "90001 90002";
$mystring = str_replace(" "," ",$mystring);
echo $mystring;
?>
I hope it helps
function removeWhiteSpace($text)
{
$text = preg_replace('/[\t\n\r\0\x0B]/', '', $text);
$text = preg_replace('/([\s])\1+/', ' ', $text);
$text = trim($text);
return $text;
}
Editing the Answer :
if you need to do it using PHP , Use urlencode function , which would hep to resolve it
<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>
But they have set backs which is mentioned in the notes section of the documentation.
http://php.net/manual/en/function.urlencode.php
You can also use functions like htmlentities,rawurlencode in php .
if you want to use it in javascript , You can use escape function.
https://www.w3schools.com/jsref/jsref_escape.asp

How to open a link which was parsed in a div?

My site parses a spanish dictionary and lets you search for more than one word at a time. If you look up "hola" you get the first div). Some words come up with suggestions, like "casa", instead of definitions like "hola":
And what i am looking for is this:
So, i would like to: when you click on the suggestions (like CASAR in the example I posted) to print the result in a div like HOLA. Here is the code used:
$words = array('word0','word-1');
function url_decode($string){
return urldecode(utf8_decode($string));
}
$baseUrl = 'http://lema.rae.es/drae/srv/search?val=';
$cssReplace = <<<EOT
<style type="text/css">
// I changed the style
</style>
</head>
EOT;
$resultIndex = 0;
foreach($words as $word) {
if(!isset($_REQUEST[$word]))
continue;
$contents = file_get_contents($baseUrl . urldecode(utf8_decode($_REQUEST[$word])));
$contents = str_replace('</head>', $cssReplace, $contents);
$contents = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/search', $contents);
echo "<div style='
//style
", (++$resultIndex) ,"'>", $contents,
"</div>";
}
I have tried with: $contents .= '' . $word . '<br/>'; But it didn't work nor I know really where/how to use it.
Okay, I'll use jQuery for the example because it will be the easiest to get the job done specially if you are new to programming.
NOTE: I DO NOT RECOMMEND USING JQUERY -BEFORE- LEARNING JAVASCRIPT -- DO IT AT YOUR OWN RISK, BUT AT LEAST COME BACK AND LEARN JAVASCRIPT LATER
First, read up on how to download and install jquery here.
Secondly, you will want something a little like this, let's pretend this is your markup.
<div id="wrapper">
<!-- This output div will contain the output of whatever the MAIN
word being displayed is, this is where HOLA would be from your first example -->
<div id="output">
</div>
<!-- This is your suggestions box, assuming all anchor tags in here will result in
a new word being displayed in output -->
<div id="suggestions">
</div>
</div>
<!-- Le javascript -->
<script>
// Standard jQuery stuff, read about it on the jquery documentation
$(function() {
// The below line is a selector, it will select any anchor tag inside the div with 'suggestions' as identifier
$('#suggestions a').click(function(e) {
// First, stop the link going anywhere
e.preventDefault();
// Secondly, we want to replace the content from output with new content, we will use AJAX here
// which you should also read about, basically we set a php page, and send a request to it
// and display the result without refreshing your page
$.ajax({
url: 'phppage.php',
data: { word: 'casar' },
success: function(output) {
// This code here will replace the contents of the output div with the output we brought back from your php page
$('#output').html(output);
}
})
});
})
</script>
Hopefully the comments will shed some light, you need to then set up your php script which will be sent a GET request. (for example, http://some.address.com/phppage.php/?word=casar)
Then you just echo out the output from PHP
<?php
$word = $_GET['word'];
// Connect to some database, get the definitions, and store the results
$result = someDatabaseFunctionThatDoesSomething($word);
echo $result;
?>
Hope this helps, I expect you have a lot of reading to do!

Having trouble passing text from MySQL to a Javascript function using PHP

So here's the problem. I have data in a MySQL DB as text. The data is inserted via mysql_real_escape_string. I have no problem with the data being displayed to the user.
At some point I want to pass this data into a javascript function called foo.
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{$someText}')\">";
If the data in $someText has line breaks in it like:
Line 1
Line 2
Line 3
The javascript breaks because the html output is
<img src=someimage.gif onclick="foo('line1
line2
line3')">
So the question is, how can I pass $someText to my javascript foo function while preserving line breaks and carriage returns but not breaking the code?
===========================================================================================
After using json like this:
echo "<img src=someimage.gif onclick=\"foo($newData)\">";
It is outputting HTML like this:
onclick="foo("line 1<br \/>\r\nline 2");">
Which displays the image followed by \r\nline 2");">
json_encode() is the way to go:
$json = json_encode($someText); # this creates valid JS
$safe = HtmlSpecialChars($json); # this allows it to be used in an HTML attribute
echo "<img src=someimage.gif onclick=\"foo($safe)\">";
You can see a demo here: http://codepad.org/TK45YErZ
If I'm not interpreting badly you may do this:
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{".trim( preg_replace( '/\s+/', ' ',$someText ) )."}')\">";
You'll save yourself a lot of headaches by pulling the JavaScript out of the HTML:
<img id="myImage" src="someimage.gif"/>
<script type="text/javascript">
var str = <?php echo json_encode($json); ?>;
document.getElementById('myImage').addEventListener(
'click',
function() {
foo(str);
}
);
</script>
Or something similer...
Only json_encode() is enough to escape the new line
echo "<img src=someimage.gif onclick=\"foo(".json_encode($newData).")\">";

string in php vs. string in javascript

Here is a simple code I have problem with:
<label id="label1">
<?php
echo "Text inside label1";
?>
</label>
<script language="JavaScript" type="text/javascript">
var text = document.getElementById("label1").innerHTML;
alert(text); // show what's in variable 'text'
if(text == "Text inside label1")
{
alert("I am inside.");
}
else
{
alert("No.");
}
</script>
The problem is that the first alert is showing "Text inside label1"(as it should do) but the second one is showing "No.". When I tried to write text right into html (not through php), it worked fine => the second alert showed "I am inside.". I have no idea what problem is there. Could there be the problem with some differences between string types (php vs. JS) or something like this?
Thanks for any ideas
There is a space at the beginning of the text in the label (all whitespace in HTML is collapsed into one space), but not at the beginning of the string you're comparing it with.
Your PHP code:
<label id="label1">
<?php
echo "Text inside label1";
?>
</label>
...will get sent to the browser like this (PHP will strip the line break after the ?> for you):
<label id="label1">
Text inside label1</label>
...which is just like
<label id="label1"> Text inside label1</label>
(Note the space.)
So this should fix it:
<label id="label1"><?php
echo "Text inside label1";
?></label>
JavaScript has no knowledge of PHP. There is no difference of types or anything. The page that is output is the page that is output. Look at the difference between doing it statically and via PHP.
I suspect you're having an issue with the whitespace surrounding the text you're echoing.
The innerHTML in your example seems to contain a line break:
<label id="label1"> <-- Line break
<?php
echo "Text inside label1";
?> <-- PHP strips this line break
</label>
That's why text == "Text inside label1" doesn't match. Try instead:
<label id="label1"><?php echo "Text inside label1" ?></label>
The problem is, that text contains also the linebreaks and whitespace inside #label.
This works as expected:
<label id="label1"><?php
echo "Text inside label1";
?></label>
<script language="JavaScript" type="text/javascript">
var text = document.getElementById("label1").innerHTML;
alert(text); // show what's in variable 'text'
if(text == "Text inside label1")
{
alert("I am inside.");
}
else
{
alert("No.");
}
</script>
The issue with this may be that the label contains extra spaces and new line characters. The better approach maybe indexof:
var str = "Text inside label1";
if(str.indexOf(text) != -1)
{}
As said below, the problem is the spacing of a new row.
You can fix that by either doing
<label id="label1"><?php
echo "Text inside label1";
?></label>
Or you could just trim the string with jQuery.trim, or add your own prototype such as
String.prototype.trim = function () {
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
myString.trim();

echo <body> doesn't activate jquery script

So I have a url from where I extract the data with extracthtml.php:
<?php
include("simple_html_dom.php");
$html = file_get_html($url);
$body = $html->find('body', 0);
$title = $html->find('title', 0);
echo $title;
echo $body;
?>
<script src="extract.js" type="text/javascript"></script>
Then with jquery I put a box around all the p elements to see if this communication works (test, am going to add more css manipulation later). My jquery starts with:
$(document).ready(function(){
$('p').css("border", "2px solid black");
});
Im guessing document.ready is the problem, because there appears to be no boxes around the p elements.
The issue is that you are echoing the jquery line to the browser after you close the page.
Since you echo the $body first, I would guess your page ends up looking something like this:
<body>
...
</body>
<script>
jquery here
</script>
Without seeing your page output this is only a guess, but if it is correct the browser will not run any code after the </body> tag. I would advise checking the source of your output to see if this is the case.

Categories