Just wondering if this is okay to do? I have to store some PHP variable values into LocalStorage.if($res->status == success){            echo '<script>alert(alrighty sparky! lets get you in...);</script>';            echo '<script>localStorage.setItem(token, JSON.stringify({token: '.$res->token.' }))</script>';            echo '<script>localStorage.setItem(username, JSON.stringify({username: '.$data->username.' }))</script>';            echo '<script>localStorage.setItem(id, JSON.stringify({id: '.$data->id.' }))</script>';            $boarding_url =  base_url() . 'index.php/boarding/teddies';            redirect($boarding_url);        }
PHP+JS Code Combining
javascript;php;jquery;codeigniter
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->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 '<script>localStorage.setItem(id, '.json_encode($data->id).')</script>';Also note that you don't need to repeat <script> tag each time:echo '<script type=text/javascript>';// Write all lines here, don't forget semicolon at the end of each oneecho 'localStorage.setItem(id, '.json_encode($data->id).');';echo '</script>';