[gist id=”69a305053e35a10584f94d6011bba2d6″ file=”simple-ajax-example.js”]
[gist id=”69a305053e35a10584f94d6011bba2d6″ file=”simple-ajax-example.php” lines=”1-27″]
Using with a Theme
There’s two differences when using this with a theme or frontend.
In the PHP piece, you need to add also add this line:
[gist id=”69a305053e35a10584f94d6011bba2d6″ file=”simple-ajax-example.php” lines=”28-30″]
This allows visitors that aren’t logged in to run the ajax request.
wordpress ajaxurl is not defined
This is because WordPress does not define ajaxurl as a global variable on the frontend. Instead, we’ll need to define it ourselves. An easy way to do this if we’re already enqueuing our script is to use wp_localize_script to output the URL:
[gist id=”69a305053e35a10584f94d6011bba2d6″ file=”example-ajax-enqueue.php”]