I ran into an issue recently. I have a system where users can post stuff. One of the fields is the title field. So to save user input safely I use htmlspecialchars on the user submitted title and send it to a function that then saves to the database (after using mysql_real_escape)
Now on the client's side I use json get to fetch this title
$.getJSON("PHPFILE", function(json) {
// let's say json.title is the title we need so...
var title = json.title;
}
Now the thing is this user given title value can contain anything, even html tags (for reference let's say it now contains
<script>alert('');</script>Some Text!
so since I use jquery I thought of clearing those using the .text() function
var cleanTitle = $(title).text();
alert(cleanTitle);
However this immediately throws an error. In chrome it says
Uncaught Error: Syntax error, unrecognized expression ...
So I verified if this title variable is a string. And it is indeed a string. (Btw for some reason if this variable contains only numbers there is no error)
Using the following however gives me the text but the tags aren't removed
var cleanTitle = $.parseHTML(title);
cleanTitle = $(cleanTitle).text();
alert(cleanTitle);
This outputs
<script>alert('')</script>Some Text!
How can I remove all html tags? Any suggestions? I am planning to use this title text to set Browser title. Thanks.
document.title = $('<div />').append( $('<div />').html( title ).text() ).text();
Appending the string twice should fix the htmlentities issues.
Since you are using MySQL as engine to store that kind of data, you are clearly using PHP scripting. Suggestion: use PHP's strip_tag() and you are cutting "workload" for jQuery/Javascript by letting PHP do the work.
Related
I am saving user fed text entered in a text box into the database and then retrieving the entered text using ajax(using JavaScript and not jQuery).
All special characters are getting inserted well in mysql but it is not able to retrieve the data containing special characters. Greater than (>) symbol is getting retrieved successfully but & and < is causing the whole page to load without any result.
Code for inserting data:
for($i=0;$i<$No_of_Inp_Fields; $i++)
{
$Desc = $_POST['txtdesc'.($i).''];
$inquery="INSERT INTO DETAILS VALUES ('$Desc')";
$sSql = mysql_query($inquery);
}
Code for retrieving the data
$queryPopIP=mysql_query("select Desc from DETAILS where Nm='$tag'");
$resPopIP=mysql_fetch_array($queryPopIP);
$DesPop=$resPop[0];
This is sent as a response using php
Code for displaying the data(using javascript)
var desIP=serverResponse.split('_');
document.getElementById('popdiv2').innerHTML="<b>"+desIP[1];
No jQuery... add the text as a text node. It'll preserve the angle brackets or other special characters.
document.getElementById('someElement').appendChild( document.createTextNode('<b>sushi</b>') );
I think this what you are asking? Honestly still not a 100% clear.
If that's not it, you probably need to call htmlentities on your data (if you are using PHP) when you are displaying the values of your data.
EDIT
Since it looks like $DesPop is what you send through AJAX, do this in your PHP
$DesPop = htmlentities($resPop[0]);
I am using javascript and php and need to pass some HTML in the JSON variable (PHP->JS).
Unfortunately, due to some environmental constraints I am limited in the jQuery I can use. Using things such as jQuery.parseJSON(str) and $.parseJSON(str) throw unexpected token errors.
Therefor I need a purely javascript approach to handling html in a JSON variable. Currently, the HTML string is just printed as a string on the page, though I need it to take effect as HTML.
My JS code is as follows:
document.getElementById("activeDescription").innerHTML = response['description'];
and the results ends up just being text on the HTML page as follows:
<p>helloworld</p>
whereas I expect just
helloword
to be displayed on the HTML page. On alert(response['description']) I receive
<p><span class="
EDIT
When I use
jQuery.parseJSON('{"name":"John"}');
everything is peachy but this code
jQuery.parseJSON(response['description']);
gives me an "Uncaught SyntaxError: Unexpected token & " error
Most probably a encoding problem. You can fix by decoding the characters.
In javascript:
var div = document.createElement('div');
div.innerHTML = encoded;
var decoded = div.firstChild.nodeValue;
In PHP, look at this link: http://www.php.net/manual/en/function.htmlentities.php
How can I get the raw code of a comment in ExpressionEngine (frontend)?
The thing is this: If a comment contains Code or HTML like [quote]-Tags, the ee-native {comment}-Tag renders this as <blockquote>Life is like a box of… … but how can I get the raw code like [quote]Life is like a box of…?
I'm currently working on a Quote-Feature (frontend/JavaScript) for native EE comments. Till now I've worked with jQuery.text() or .html() … but both ways you get no tag (.text()) or html-tags (.html()).
Isn't there a way to get the raw comment code (for example into a data-attribute or script-tag) to later use with JavaScript?
Edit (1): I've tried SQL — is this the only/best way to do this?
<blockquote data-raw="{exp:query sql="SELECT exp_comments.comment AS comment_raw FROM exp_comments WHERE exp_comments.comment_id = {comment_id} "}{comment_raw}{/exp:query}">
{comment}
</blockquote>
Edit (2): The SQL works fine, but if there is a " inside the raw comment code, the whole thing breaks because the browser thinks this is the closing quote of the «data-raw»-attribute :-/ Is there a Way to 'mask' all characters? (" and ' and < and > etc.)
Edit (3): I now use a <script>-Tag to insert the {comment_raw}-code, this way the characters do not disturb.
You'd probably be better off retrieving the raw comment via an ajax call rather than adding a query for every single comment on the page. You'd avoid the performance hit and wouldn't need to worry about storing large strings in data attributes. I'd probably do something like this:
Create a new 'get_comment' template containing the {exp:query} tag with WHERE comment_id = '{segment_X}'
When a user hits the reply/quote button use jQuery.get() to send a request to your get_comment template, passing in the comment_id based on a data-commentid attribute on the reply button.
Update your input's value with the .get() response.
The following script has been created to test if the value of a db field has changed and if so then reload the page and if not, alert the user that the change has not happened.
The alert is just to see what is being returned by the .post function.
The auto_refresh works fine as i need it to check every 5 seconds, when the if() condition is set to '==' the page alert shows and if it is set to '!=' the page continually reloads.
jQuery.post is getting the db field data but it doesn't seem to be able to compare the 2 values correctly.
any help would be greatly appreciated, thanks
var auto_refresh = setInterval(function(){
$.post("/index.php/listen", function(data) {
if($('#slide').html() != data)
{
window.location.reload()
}
else
{
alert('its the same'+ data);
}
});
}, 5000);
EDITED
Rather than trying to parse raw data, why not pass HTML from the $.post() like:
<p>4</p>
Then the jQuery inserts the the replaces the p tag with the new version from the $.post()
because the html is passed on there is no white space and the comparison can be made correctly.
I don't think it is very safe to compare the new value with an html. Some browsers might add spaces or unwanted chars. I'd try to save the old value in an input of type hidden and use the .val() or, event better, in a variable. It depends of your scenario.
If $('#slide').html() == data
then that means that the conditional failed, it was not equal, so it showed the alert.
The problem is that the data variable might come back with a few extra white spaces. If I were you, I'd try to parse a small section of the data variable, and a small section of the html in slider and compare those values.
Like if slider has something within a p tag or an input value, compare it to the data to see if it has that same value returned in that p tag or input value, then replace all the whitespaces with an empty string just to be safe.
Btw, try not to use alerts since you can't really know for sure if there is an extra whitespace. Try to use something like "debugger" if using IE with visual studios, or console.log when using chrome or firefox.
You are comparing two html strings: one is serialized from the DOM, and another is from a server response.
There's no guarantee that the two strings will ever be the same! Think about it: the same rendered html can have many string differences. E.g. click and click are both the same HTML, but different strings.
You can take two different approaches here:
You can create some kind of canonicalization routine that guarantees that two html fragments you consider "the same" will have the same string form. Run both html fragments through this routine, then compare.
You can manage versions more explicitly.
Include some kind of version indicator:
You can use the ETAG header (which means you can take advantage of http caching mechanisms).
You can include some kind of version number in the html itself (maybe in a data-version attribute), and compare those.
You can keep the html string from your server separately and compare against that.
I have html data like text including image src.when I alert using jquery it works fine. Entire html is displayed in alert box.And then I want to send that entire html data and text and something's id using query string of JQuery like:
$.post('something.php','socialprofileid='+socialprofileid+
'&txtMsg='+msg+'&postedHtmlMsg='+HtmlMsgresult)
But I need that entire html data including text and id in php page like get html data, text, id in JQuery alert box
I try to use window.btoa function(base64 encoded format) for HtmlMsgresult. After doing base64 encoded format in javascript, when I try to send in php page, it doesn't get any print in php page.
Another thing is there any solution Text and htmldata(html text and img src) are combined and then it is done the base64 encode.And then it is send in php page using query string like:
if(txtmsg='') {
var result=window.btoa(htmldata);
} else {
var content=text+htmldata;
var result=window.btoa(content);
}
$.post('something.php','socialprofileid='+socialprofileid+'&result='+result)
Is it possible to do that?
And then I want to insert into database in something.php and then in another page I want to fetch the htmldata and text which are encoded by base64 using jquery. Then it is converted by base64_decode function.
But within text and htmldata, How to extract text , htmltext, htmlimgsrc differently from the database table.
If u know about these type of problems, please reply me
I need your hand
Thank you
$.post('something.php',
{socialprofileid:socialprofileid,
txtMsg:msg,
postedHtmlMsg:HtmlMsgresult});
jQuery will apply encodeURIComponent by itself. And yes, you need encodeURIComponent applied to the values of the parameters if you want to encode the data by yourself. Read the following topic When are you supposed to use escape instead of encodeURI / encodeURIComponent?
ps: you do not have to do anything in the php script, the data will be decoded automatically by the server. Access $_POST['socialprofileid'], $_POST['txtMsg'] and so on in php.
In php, you can get the post parameters with the $_POST variable.
<?
echo $_POST['socialprofileid'], PHP_EOL;
echo $_POST['txtMsg'], PHP_EOL;
echo $_POST['postedHtmlMsg'], PHP_EOL;
?>