TNT
TNT

Reputation: 500

How to load a cached php array into js variable?

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>

Upvotes: 0

Views: 340

Answers (0)

Related Questions