I found a solution to my problem, which I share below. However, before I go into the solution, here is short bg on what my issue was. I have a page where I load js script to prefill a form with values previously saved as draft submissions into a bg post. I don’t have direct control on the form code printout so I need to do it with javascript.
The javascript itself needs to be dynamically built depending on the form fields present on the form, ie I need to be able to solve this for any form. So the cut a long story short, I have both dynamic javascript as well as dynamic data that needs to be queued into the page.
Till now I was printing an inline script code along with a json data object embeded in the script, and I chose to embed the json data object because the data is extensive and an ajax would require reloading a lot of data/objects into memory along with DB calls, not efficient. So building the data at the same time as the page is much faster.
The problem with the above is that browser caching can leave the form filled with old data when a recent draft was saved and the page reloaded.
So after trying multiple different routes which didn’t work for me, I finally did the following,
- Enqueue
wp_enqueue_script('plugin-handle', 'file-path',...)
a general global function which returns a localized data associated with the script handle.
$.fn.post2CF7FormData = function(nonce){
if( 0=== $(this).closest('#'+nonce).length ){
return '';
}
if( 'undefined' != typeof window[nonce] ){
return window[nonce];
}
return '';
}
- localize the data that goes with it,
wp_localize_script('plugin-handle', $nonce, $form_values);
I use a wp nonce to uniquely identify the form values because potentially the page could have multiple forms with each requiring different data, therefore allowing me to localize multiple data sets on the same handle.
- inline the form filling code,
...
var data = $form.post2CF7FormData(nonce);
//carry on with the rest of the code...
I am not bothered if the form code is cached as the code matches the cached form as well.
Hope this helps someone else out there.