Image may be NSFW.
Clik here to view.
Sometimes the most obvious solution isn't the one that comes to you first.
wp_localize_script() is a wonderful little slice of Wordpress code that allows you to easily add PHP-created info into an accessible JavaScript object.
On an admin form I needed to trigger a JavaScript object on successful completion. My method was to create an option field which was updated on successful form completion, with the same option field being called by wp_localize_script() .
However, the JavaScript object created by wp_localize_script() was only ever updated after the form had been sumitted twice. Why? It took me a couple of hours to work it out but as the wp_localize_script() was called in the class constructor then any form action would always happen afterwards.
So now I'm thinking, What about using AJAX? But the best and most simple answer was to use cookies.
After form completion I set a cookie with a name of “_multi_cov” and the name of the form as its value:
setcookie("_multi_cov", $option_name);
The first part of the JavaScript checks to see if the "_multi_cov"cookie is set, if so run the object method:
if (document.cookie.indexOf("_multi_cov") !== -1) { OptionForm.multiFormName(); }
Now in the multiFormName() method it is necessary to filter out the name of the form from the cookie:
var key, cookieMonster, mySplitResult, lastSplitResult; function removeArrayElement(element, index, array) { return (element !== "_multi_cov"); } cookieMonster = document.cookie; mySplitResult = cookieMonster.split(";"); for (x = 0, l = mySplitResult.length; x < l; x += 1) { if (mySplitResult[x].indexOf("_multi_cov") !== -1) { lastSplitResult = mySplitResult[x].split("="); key = lastSplitResult.filter(removeArrayElement).toString(); } // end if } // end for
In the key variable is the name of the form.
I also deleted the cookie at the end of the JavaScript method:
document.cookie = "_multi_cov" + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
The problem was that I was so in love with wp_localize_script() that it blinkered me to exploring a more appropriate alternative. In future I'll use wp_localize_script() for complex arrays and an alternative cookie solution for simple strings.