WordPress function that makes HTML safe to be sent via AJAX request

Depending on what kind of HTML you’re expecting, there are different tools you can use: esc_html() escapes entire HTML blocks so you don’t end up with breaking characters in your JSON object literals. esc_html_e() escapes (as above) and translates the string if you’re concerned about localization in that context. wp_kses() will parse the HTML string … Read more

Update user meta using with ajax

Alright, there’s a few things that isn’t standardized WordPress so I’ve put together a minimal script which I’ll explain piece by piece. Hopefully clear things up for you by the time you get to the end. HTML Form Below is a very simple HTML form. We’re going to use javascript to listen for submission and … Read more

How to process ajax requests correctly using ajax plugins

tl;dr Both ways are okay, as long as you die() your AJAX-function somehow. I take it for granted that you handle the security well – this is important for both methods. The Long Tail It actually does not really matter which approach you use, and it depends a great deal on what your AJAX-Request does. … Read more

Custom Form with Ajax

Your attempt to send your AJAX requests to wp-admin/admin-ajax.php is correct but it will be better to create a javascript global variable using wp_localize_script() to make any data available to your script in functions.php that you can normally only get from the server side of WordPress. For example, your javascript code can be in the … Read more

Ajax for non-logged-in users

The wp_ajax_{action} hook only fires for logged in users. For logged-out users the action wp_ajax_nopriv_{action} is triggered on an ajax request – so you need to hook into that as well.

REST API endpoint for elasticpress autosuggest

After some inspecting the WP_REST_Request, it turned out, that the get_body() method was the one I’m looking for. Anyhow, this is what I ended up with: add_action( ‘rest_api_init’, function() { register_rest_route( ‘ep’, ‘/as/’, [ ‘methods’ => \WP_REST_Server::CREATABLE, ‘callback’ => ‘ep_autosuggest’, ] ); } ); function ep_autosuggest( WP_REST_Request $data ) { // Elasticsearch PHP Client $client … Read more

How to call a PHP function with Ajax when the user clicks a button

Create a child theme so you don’t mess with the code of an existing theme because next time you’ll update the theme, you may loose all your changes (see Child Themes) Here is how to pass values to your ajax request: jQuery(document).ready(function() { jQuery(“.mark-as-read”).click(function () { console.log(‘The function is hooked up’); jQuery.ajax({ type: “POST”, url: … Read more