As noted in the answer by Adriano Repetti, as you are outputing raw data into the javascript source, you could create invalid javascript. For example a quote in $res->token
could create the following syntax error:
<script>localStorage.setItem("token", JSON.stringify({"token": "token with a " (quote)" }))</script>';
The SO highlighter makes this error quite obvious.
Aslo, as pointed out by Adriano, php's json_encode()
takes care of this nicely.
However, whenever i find myself mixing js with a server side language, i endevour to keep the interleaving to an absolute minimum, to reduce confusion.
With that in mind, i would format the data in php, then output it a single place, creating an object that js can process:
if($res->status == "success"): $jsData = [ 'storageData' =>[ 'token' => $res->token, 'username' => $res->username, 'id' => $res->id ], 'redirectUrl' => base_url() . 'index.php/boarding/teddies' ]; ?> <script> var data = <?php echo json_encode($jsData);?>; for(var item in data.storageData){ localStorage.setItem(item, storageData[item]); } //redirect window.location.replace(data.redirectUrl); </script> <?php endif;
(Unfortunately the SO syntax highlighter is not so clever here..)
With regards to the redirect:
redirect($boarding_url);
Presumably this function is also outputting javascript (as a regular header redirect would be impossible at this point, as the response body has already been sent), so for clarity i included redirect in the above js block.
Additionaly, this looks like a bit of a code smell - returning a response to the browser just to set some js data then performing another request back to the server.
saving the data in session
, redirecting directly to the final destination (index.php/boarding/teddies
) and have that page retrieve its data from session would probably make more sense, but thats another question.