jQuery load function escapes data - php

I have a strange problem with the load function from jQuery. It escapes HTML content that jQuery gets back from the load function. I load HTML output from a PHP file into a div. I use this function:
function XXX(file,divName,functionToCall)
{
$("#" + divName).load(file,null,function()
{
functionToCall();
});
};
The HTML output of the PHP file:
<div onClick="xxx(0,'xxx')" id="xxx"></div>
Jquery converts it into:
<div onClick="xxx(0,\'xxx\')" id="xxx"></div>
Because of this convention I can't use the onClick function, it isn't valid any more. I can't figure out what I 'm doing wrong, does some one know what causes this problem and how to solve this in a good way? I already read other related question on Stack overflow, but I couldn't find an answer how to avoid escaping.

I guess your problem isn't in a PHP block. Here are some rules you need to follow:
For PHP use these rules:
When to escape the char ' :
When you want to use ' in a ' ' block. For example: echo 'test: \' this workes ';
When you don't need to escape the char ' :
When you want to use ' in a “ ” block. For example: echo “test: '
this workes “;
For HTML use these rules:
If you aren’t in a PHP block, then you don't need to escape data. The data you wrote here will directly be outputted. When you want to make a onClick, just use this template: onClick”functionName('stringValue');”
Maybe it's because of the editor:
Some editors will give \' an other color, don't let the colors distract you. It doesn't mean it's correct! Use a file editor with less features ( like notepad ) and open the PHP file where you were talking about. Check again if there are no \'s on places where they shouldn't be.
The problem isn't JQuery in this case. Trust me, look at the PHP file. Did you maybe escaped data outside a PHP block?

This has something to do with you PHP implementation not javascript. When PHP outputs your html it's set to escape quotes.

Related

Creating dynamic elements with Javascript event using echo in PHP?

It's simple if the code is written in Javascript (between the <script> and </script>, but I'm encountering a problem like this (render dynamic content using echo in PHP):
echo "<label onclick='showContent(\"".$content."\")'>Click me</label>"
and I also tried this:
echo '<label onclick="showContent("'.$content.'")">Click me</label>'
The problem is that $content can contain many characters like " (double quote), ' (single quote)... Generally, it contains HTML code.
If it is a normal sentence, the code above will work well, it renders a label of 'Click me' and I can click it to run the function showContent(), but if it contains HTML code, it can render the label however I can't run the function showContent() when I click on it. I think there is some problem with quotes here. I tried replacing all the single and double quotes in $content with " or \" and ' or \' but it still doesn't work, even in some cases, the label of 'Click me' can't be rendered properly, instead of that it shows me almost the code behind.
I'm really stuck at this (already for hours), please give me a solution. Your help would be highly appreciated!
Thanks!
Try this:
echo '<label onclick="showContent('.$content.')">Click me</label>'

Parsing html with phpQuery : how to handle C++ code inside a pre tag?

In the database I have some code like this one
Some text
<pre>
#include <cstdio>
int x = 1;
</pre>
Some text
When I'm trying to use phpQuery to do the parsing it fails because the <cstdio> is interpreted as a tag.
I could use htmlspecialchars but to apply it only inside pre tags I still need to do some parsing. I could use regex but it will be much more difficult (I will need to handle the possible attributes of the pre tag) and the idea of using a parser was to avoid this kind of regex thing.
What's the best way to do what I need to do ?
Remember to do encode HTML (& > and so on) before assembly
I finally went the regex way, considering only simple attributes for the pre tag (no '>' inside the attributes) :
foreach(array('pre', 'code') as $sTag)
$s = preg_replace_callback("#\<($sTag)([^\>]*?)\>(.+?)\<\/$sTag\>#si",
function($matches)
{
$matches[3] = str_replace(array('&', '<', '>'), array('&', '<', '>'), $matches[3]);
return "<{$matches[1]} {$matches[2]}>".htmlentities($matches[3], ENT_COMPAT, "UTF-8")."</{$matches[1]}>";
},
$s);
It also deals with caracters being already converted to html entities (we don't want to have it twice).
Not a perfect solution but given the data I need to apply it on it will do the work.
The error is, that your database contains HTML that contains some text which is not correctly encoded already.
So, if you want to save time and have a correct solution, then you should make sure, that the HTML in your database is correctly encoded. This means, you should make sure that everything will be correctely encoded (using htmlspecialchars()) before it is saved to your database!
Otherwise you just save garbage in your database, and you will have to write some special code to "prettify that garbage".
Any other solutions are workarounds, and those will cost you precious time in your future.
So: the best solution is to make sure, that anything you write to your database is correct.

How to add an HTML class to a PHP script

First off, I don't know much (quite nothing) about PHP. I'm more familiar with CSS.
I'm making use of Ben Ward script Tumblr2Wordpress (here's the script on GitHub) to export my Tumblr blog in XML (so I can import it in my Wordpress blog). This script reads tumblr's API, queries elements, do a bit of formatting and export the whole thing in HTML.
I need to customize it just a bit to fit my needs. For example in the following function I need the blockquote to become a specific class of blockquote:
function _doBlockQuotes_callback($matches) {
$bq = $matches[1];
# trim one level of quoting - trim whitespace-only lines
$bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
$bq = $this->runBlockGamut($bq); # recurse
$bq = preg_replace('/^/m', " ", $bq);
# These leading spaces cause problem with <pre> content,
# so we need to fix that:
$bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx', array(&$this, '_doBlockQuotes_callback2'), $bq);
return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
}
At first, I thought it will be as simple as adding the class I need inside the blockquote HTML tag, like so <blockquote class="big"> But it breaks the code.
Is there a way I could add this HTML attribute as is in the PHP script? Or do I need to define the output of this <blockquote>somewhere else?
Thanks in advance for any tips!
P.
Your guess was correct, but you need to escape the quotes with backslashes:
return "\n". $this->hashBlock("<blockquote class=\"big\">\n$bq\n</blockquote>")."\n\n";
Otherwise, PHP assumes that your string ends at the class=" quote.
You can escape double quotes ".
"<blockquote class=\"big\">"
How ever, if you're going to use single quotes '. It's unnecessary.
'<blockquote class="big">'
You need to escape the quote marks
<blockquote class=\"big\">

javascript quotes inside quotes, string literal issue

I am trying to display text in a javascript tooltip
I keep getting unterminated string literals even though:
a) the quotes are being slashed, b) there are no line breaks
The text I am trying to display is:
"No, we can't. This is going to be terrible."
(its a quotation from an individual and I want those quotes to display in the tooltip)
My tooltip function works like this
onMouseOver="Tip('string here')"
After I run the string through my function to clean for javascript
function jschars($str) {
echo preg_replace("/\r?\n/", "\\n", addslashes($str));
}
It comes out looking like this in HTML:
onMouseOver="Tip('\"No, we can\'t. This is going to be terrible.\"')"
This gives me the error unterminated string literal for the first \ in Tip('\
I'm guessing its because im trying to put quotes directly inside the single quotes, how can I get around this for situations like this? (I have tried htmlspecial chars, such as replacing the " with & quot ; - I still get the error
It's because you're putting double-quotes inside the value of an XML (or html) element:
<div onMouseOver="Tip('\".......
the back-slash doesn't escape it from the context of xml/html. Technically, you'll need to entity-encode the string (after you javascript-escape it). Something like this:
<div onMouseOver="Tip('\"No, we can\'t. This is going to be terrible.\"')" >
Various browsers may or may not deal with that properly. A much better way to approach it would be to give the element an id (or a class, or some other way for you to select it), then add the mouse over handler from a standalone script.
Because of the structure of what you're doing:
onMouseOver="Tip('string here')"
...you have to do two things:
As Lekensteyn said, you need to use htmlspecialchars to turn any special HTML characters into character escapes. It does things like turn " into ", which means you can safely enclose the attribute in " characters.
But you're not just using this as an attribute, you're also putting it inside a string literal, which means you also need to do JavaScript escaping on the string. Otherwise, (in your case) a single ' character or backslash will mess up the string. So your jschars function also needs to (in order) A) Convert \ to \\, B) Convert ' to \'. That's the minimum, anyway, really you need a thorough "make this safe to put inside a JavaScript literal" function. From your question, I sort of had the impression you were doing this manually, but better to automate it for consistency.
Off-topic: Separately, I would recommend moving away from using attributes to attach handlers. Instead, look into attachEvent (IE) and addEventListener (W3C), or better yet look at a library like jQuery, Closure, Prototype, YUI, or any of several others that will smooth things out for you. For instance, attaching a mouseover handler to:
You can use this handler to handle the mouseover:
function handler() {
Tip('Your message here');
}
...which you then hook up like this with raw DOM stuff (obviously you'd make a utility function for this):
var div = document.getElementById('foo');
if (div.attachEvent) {
// Uses "onmouseover", not "mouseover"
div.attachEvent('onmouseover', handler);
}
else if (div.addEventListener) {
// Uses "mouseover", not "onmouseover"
div.attachEvent('mouseover', handler, false);
}
else {
// Fallback to old DOM0 stuff
div.onmouseover = handler;
}
Here's how Prototype simplifies that hook-up process:
$('foo').observe('mouseover', handler);
Here's how jQuery does:
$('#foo').mouseover(handler);
You should use htmlspecialchars() for this purpose. The problem is ", but HTML won't understand javascript quoting, so it stops at \".
function jschars($str) {
echo htmlspecialchars(preg_replace("/\r?\n/", "\\n", $str), ENT_QUOTES);
}
You could keep the string in javascript instead of HTML. eg:
<a onmouseover="Tip(this, 123)">choice</a>
Then something like:
var texts = {
123:"No, we can't. This is going to be terrible.",
...
};
function Tip(elm, txtId){
showTip(elm, texts[txtid];
}

Why mysql is not storing data after "#" character?

I have made one form in which there is rich text editor. and i m trying to store the data to database.
now i have mainly two problem..
1) As soon as the string which contents "#"(basically when i try to change the color of the font) character, then it does not store characters after "#". and it also not store "#" character also.
2) although i had tried....in javascript
html.replace("\"","'");
but it does not replace the double quotes to single quotes.
We'll need to see some code. My feeling is you're missing some essential escaping step somewhere. In particular:
As soon as the string which contents "#"(basically when i try to change the color of the font) character
Implies to me that you might be sticking strings together into a URL like this:
var url= '/something.php?content='+html;
Naturally if the html contains a # symbol, you've got problems, because in:
http://www.example.com/something.php?content=<div style="color:#123456">
the # begins a fragment identifier called #123456">, like when you put #section on the end of a URL to go to the anchor called section in the HTML file. Fragment identifiers are purely client-side and are not sent to the server, which would see:
http://www.example.com/something.php?content=<div style="color:
However this is far from the only problem with the above. Space, < and = are simly invalid in URLs, and other characters like & will also mess up parameter parsing. To encode an arbitrary string into a query parameter you must use encodeURIComponent:
var url= '/something.php?content='+encodeURIComponent(html);
which will replace # with %35 and similarly for the other out-of-band characters.
However if this is indeed what you're doing, you should in any case you should not be storing anything to the database in response to a GET request, nor relying on a GET to pass potentially-large content. Use a POST request instead.
It seems that you are doing something very strange with your database code. Can you show the actual code you use for storing the string to database?
# - character is a common way to create a comment. That is everything starting from # to end of line is discarded. However if your code to store to database is correct, that should not matter.
Javascript is not the correct place to handle quote character conversions. The right place for that is on server side.
As you have requested....
I try to replay you... I try to mention exact what I had done...
1) on the client side on the html form page I had written like this..
html = html.trim(); // in html, the data of the rich text editor will come.
document.RTEDemo.action = "submit.php?method='"+ html.replace("\"","'") + "'";
\\ i had done replace bcz i think that was some problem with double quotes.
now on submit.php , my browser url is like this...
http://localhost/nc/submit.php?method='This is very simple recipe.<br><strong style='background-color: #111111; color: #80ff00; font-size: 20px;">To make Bread Buttor you will need</strong><br><br><blockquote><ol><li>bread</li><li>buttor</li></ol></li></blockquote><span style="background-color: #00ff80;">GOOD.</span><br><br><br><blockquote><br></blockquote><br>'
2) on submit.php ........I just write simply this
echo "METHOD : ".$_GET['method'] . "<br><br>";
$method = $_GET['method'];
now my answer of upper part is like this...
METHOD : 'This is very simple recipe.
now i want to store the full detail of URL....but its only storing...
This is very simple recipe.

Categories