Julo0sS
Julo0sS

Reputation: 2102

simple quote escape issue with pdo-php-javascript (ajax)

here is my problem :

i get a string back from my database with PDO in a php script (called in an ajax query) :

...some code
$myString = $pdoObject['field'];
...some code

The string contains one single quote : '

example :
          it's strange

later in this php script i put the string into a long string variable that i send back to my ajax query :

$wholeString = "<tr><td><span title='$myString'>Some Text</span></td></tr>";

then i send it back : json_encode($wholeString);

in my ajax query i just put the result into a jquery field :

...some code
success : function(response){
    $("#myField").html(response);
}
...some code

the TITLE thing is always cutted at the quote :

<tr><td><span title='it'>Some Text</span></td></tr>

if i try to use htmlentities or htmlspecialchars before i put $myString into $wholeString, it does not change anything... there is something i miss somewhere...

thanks for help

Upvotes: 0

Views: 118

Answers (1)

Marc B
Marc B

Reputation: 360622

You basically have an html injection problem. You need to use htmlspecialchars() to escape ALL of the html metachars in your text, which includes '

e.g.

$wholeString = "<tr><td><span title='" . htmlspecialchars($myString, ENT_QUOTES) . "'>Some Text</span></td></tr>";

As written in your code, you'd be generating:

<tr><td><span title='It's strange'>Some text etc...

which would cause the browser to parse the span tag as

<span
   title='It'    // attribute "title" with value "It"
   s             // unknown random attribute s
   strange'      // unknown random attribute "strange" with illegal single-quote

Upvotes: 2

Related Questions