PHP, javascript, single quote problems with IE when passing variable from ajax post to javascript fu

Posted by Mattis on Stack Overflow See other posts from Stack Overflow or by Mattis
Published on 2010-03-12T16:38:00Z Indexed on 2010/03/12 16:47 UTC
Read the original article Hit count: 5253

Filed under:

Hi! I have been trying to get this to work for a while, and I suspect there's an easy solution that I just can't find. My head feels like jelly and I would really appreciate any help.

My main page.php makes a .post() to backend.php and fetches a list of cities which it echoes in the form of:

<li onclick="script('$data');">$data</li>

The list is fetched and put onto the page via .html().

My problem occurs when $data has a single quote in it. backend.php passes the variable just fine to page.php but when i run html() it throws a javascript error (in IE, not FF obviously);

')' is expected

IE parses the single quote and messes up the script()-call. I've been trying to rebuild the echoed string in different ways, escaping the 's on the php side and/or on the javascript side - but in vain. Do I have to review the script in total?


$.post("backend.php", {q: ""+str+""}, function(data) {
    if(data.length >0) {


while ($row = $q->fetch()) {
    $city = $row['City'];
//  $city = addslashes($row['City']);
//  $city = str_replace("'","&#39;",$row['City']);
    echo "<li onclick=\"script('$city');\">".$city."</li>";

© Stack Overflow or respective owner

Related posts about php

Related posts about JavaScript