1

My web app sends data from PHP to javascript as a JSON string.

To avoid writing the string as text in the rendered file, the architecture I thought of using is setting data on cookies with PHP, then reading with JS. It works well so far, but I was thinking if maybe users have cookies disabled, then it won't work.

So I have two questions, one, if users do disable cookies much or if it's ok to use cookies as my data-keeping method.. is there a study about cookie-disabling behaviour? I googled but couldn't find any recend data.

Second, is there another way to send data from PHP (I'm using laravel) to javascript without having to write it out on the file? (I can't make another ajax request to the server and then load the data, as it would kill user interaction, the data must return with the first request)

Thanks

sigmaxf
  • 7,998
  • 15
  • 65
  • 125

1 Answers1

3

First almost no one disables cookies. If you disable cookies, half of the websites you visit won't work anymore.

If you want to "pass data to javascript" without writing to a file (usually you never write to a file to pass data to javascript anyway) you can simply do:

<script>
   var mydata = '<?=$mydata?>';  # take care of escaping single quote of course
</script>

In this way you don't make an additional AJAX request.
If you are using Laravel's blade then:

<script>
   var mydata = '{!! $mydata !!}';  # take care of escaping single quote of course
</script>

As pointed out in comments, if you are passing json then simply remove the quote:

<script>
   var mydata = {!! $mydata !!}; 
</script>
dynamic
  • 46,985
  • 55
  • 154
  • 231
  • It's JSON (=pure javascript)! Why do you put in quotes? Just use `var mydata = ;` – m93a Aug 20 '15 at 20:18
  • Even when it's not written on the page, using javascript or a hidden div, it still outputs to the html file as text, isn't this considered a bit of a "hackish" solution os it it very normal to use? (please consider I'm loading relatively big json objects some 40-60k+) – sigmaxf Aug 20 '15 at 20:24
  • I can be wrong, but in my still raw programmer mind, loading as cookies seem a bit more elegant. – sigmaxf Aug 20 '15 at 20:24
  • @raphadko I also consider the cookie-solution much more _hackish_. – m93a Aug 20 '15 at 20:27