PHP+JS Code Combining Just wondering if this is okay to do? I have to store some PHP variable values into LocalStorage.

if($res-&gt;status == "success"){


            echo '&lt;script&gt;alert("alrighty sparky! lets get you in...");&lt;/script&gt;';
            echo '&lt;script&gt;localStorage.setItem("token", JSON.stringify({"token": "'.$res-&gt;token.'" }))&lt;/script&gt;';
            echo '&lt;script&gt;localStorage.setItem("username", JSON.stringify({"username": "'.$data-&gt;username.'" }))&lt;/script&gt;';
            echo '&lt;script&gt;localStorage.setItem("id", JSON.stringify({"id": "'.$data-&gt;id.'" }))&lt;/script&gt;';


            $boarding_url =  base_url() . 'index.php/boarding/teddies';
            redirect($boarding_url);
        }
No, it doesn't work like that because you're not escaping your PHP strings to be a safe JavaScript string. What you're doing is encoding them as JSON but if - for example - $res-&gt;token contains \ then it will produce a broken JavaScript string and JSON.stringify() won't fix it.

Correct code must use json_encode() for this purpose.

echo '&lt;script&gt;localStorage.setItem("id", "'.json_encode($data-&gt;id).'")&lt;/script&gt;';


Also note that you don't need to repeat &lt;script&gt; tag each time:

echo '&lt;script type="text/javascript"&gt;';
// Write all lines here, don't forget semicolon at the end of each one
echo 'localStorage.setItem("id", "'.json_encode($data-&gt;id).'");';
echo '&lt;/script&gt;';