0

How to load a cached php array into js variable?

I have a working PHP code which gets data from two APIs and then caches the html locally. It also caches a PHP array into a file called "cache_file" with type as File.

I have a javascript snippet at the end of the PHP file which loads the PHP array into a javascript array and shows it on the console.

When I run the PHP file from browser, it loads the PHP array (uncached version) into the JS array and is visible on the JS console. But when I refresh the page, the cached version of the page loads and I don't see any output on my JS console. I infer that the array stored in cache_file does not get loaded into the JS array this time. How to solve this?

I cached the PHP array using the code described in the best answer in Caching a PHP Array.

To cache to a file:

file_put_contents("cache_file", serialize($myArray));

Then to load the cache:

$myArray = unserialize(file_get_contents("cache_file"));

I am guessing the load PHP array portion is not working since the server is not called upon when I refresh the page, since it is inside PHP code.

The JS is inside the PHP file itself, as under:

<script>
    var udemyServerData = <?=json_encode($udemyKeywords)?>; //loading php array into JS array

    var courseraServerData = <?=json_encode($courseraKeywords)?>;//loading another php array into JS array                                              

    var commonServerData = udemyServerData.concat(courseraServerData);
    var modifiedServerData = new Array();
    for (i = 0; i < udemyServerData.length; i++) { 
    modifiedServerData.push({
    "value": 'udemy',
    "text": udemyServerData[i]
    });
}
    for (i = 0; i < courseraServerData.length; i++) { 
    modifiedServerData.push({
    "value": 'coursera',
    "text": courseraServerData[i]
    });
}

    console.log(udemyServerData);
    console.log(courseraServerData);
</script>
Community
  • 1
  • 1
TNT
  • 480
  • 1
  • 4
  • 11
  • 2
    Show us the code! – Felippe Duarte Nov 24 '16 at 17:52
  • I assume from what you're saying that the PHP code delivers JS code to the client. In that case the JS code would be cached along with the rest of the page and everything ought to be fine. I suspect something else is going on. Can you show us how the JS is being delivered in the page and what the JS is doing? – Octopus Nov 24 '16 at 18:05
  • 1
    in the server side: `echo json_encode($array)`, in the js side, load the json from ajax call – ZiTAL Nov 24 '16 at 18:05
  • I have added the JS code. Any update on solving this now? @Octopus – TNT Nov 28 '16 at 19:38

0 Answers0