Search code examples
javascriptphpjsonencode

problem in pass php array to js function contain space in array items


i pass a php array to js function. but array items contain space. for example for name="Ali alavi".
when i use encode_json($value) to pass js function , i got error: (if my items contain space get this)

Uncaught SyntaxError: '' string literal contains an unescaped line break

this error appear only on pass encoded to js func.

my php code:($value is array contain U_name,U_family,U_username,U_role)

 $db = Db::getInstance();
$sql = "select * from users ";
$record = $db->query($sql);
$i = 1;
foreach ($record as $key => $value) {
    echo "<tr><td><a onclick=editRecord('" . json_encode($value) . "') data-toggle='modal' data-target='#userModal' href='#'><i class='icon-pencil'></i><a></td></tr>";
}

my js func:

 function editRecord(n) {
        let p = JSON.parse(n);
        console.log(p['U_name']);}

Solution

  • You should check the source code in the browser, the HTML is probably not valid. I assume this is a JavaScript error from the console?

    Something like onclick=editRecord('...') might work, but it's better to add quotes around the value like this onclick="editRecord('...')". This is probably what's causing the issue, because there is a space in the value.

    If you do add the quotes, there is an issue with the JSON which will also contain quotes. Something like this onclick="editRecord('{"name":"value"}')", which is also not valid.

    If you replace the double quotes with &quot; it will work, but you might also have other special characters in the JSON, so something like htmlspecialchars will work better. Like this:

    $db = Db::getInstance();
    $sql = "select * from users ";
    $record = $db->query($sql);
    $i = 1;
    foreach ($record as $key => $value) {
        echo "<tr><td><a onclick=\"editRecord('" . htmlspecialchars(json_encode($value)) . "')\" data-toggle='modal' data-target='#userModal' href='#'><i class='icon-pencil'></i><a></td></tr>";
    }