PHP+JS Code Combining
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;';