Recently I was working on to create ajax request in WordPress and I have created using callback of WordPress actions.
For calling a ajax request using WordPress default file, you need to include wp-admin/admin-ajax.php
which is into wp-admin panel so you need to all that file into your theme to support ajax.
Here I Will explain you a tutorial to use an ajax call. In this tutorial, We will Show how ajax works in WordPress.
First of all, let’s see how to enqueue admin-ajax.php into your theme
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // to speed things up, you don't load these scripts in the WP back-end if( ! is_admin() ) { add_action( 'wp_enqueue_scripts', 'load_custom_scripts' ); } /* Script variables */ 'ajax_url' => admin_url('admin-ajax.php') ); //declare a URL to the file that handles the AJAX request wp_localize_script( 'general', 'ajax_params', $params ); } |
Here ajax_url is a JavaScript variable used in WordPress to pass ajax requests to that uri.Using above code, you won’t have to use PHP to print out JavaScript code, which is non-cacheable and not feasible.It will generate HTML Code into
tags like in below:1 2 3 4 5 6 7 8 | <script type="text/javascript"> /* <![CDATA[ */ var ajax_url = { ajax_params: "ajax_url":"http:\/\/abc.coml\/wp-admin\/admin-ajax.php"}; /* ]]> */ </script> |
This is just for your information, don’t include above code into any file.
Now,in your JavaScript file, paste the following code of jQuery:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $('.btn').click(function(){ var data = { action: 'ajaxDataSubmit', id: $(".cls")attr("id"); }; $.ajax({ type:"POST", url: ajax_params.ajax_url, // our PHP handler file data: data, beforeSend: function() { //loadin image or text beforeload ajax code }, success:function(results){ // do something with returned data return results; } }); }); |
In the above jQuery code, we added the code at click event of a button but you can write on any event, you want.
Including the following line of codes, you can process the ajax request and display your data. you can add below code to your theme’s functions.php or a plugin file.
1 2 3 4 5 6 7 8 9 10 | function ajaxDataSubmit(){ global $wpdb; $id = $_POST['id']; // your php code die; } add_action('wp_ajax_nopriv_ajaxDataSubmit', 'ajaxDataSubmit'); // Not logged in uNOTE: mer |
Mostly wp_ajax_nopriv prefix is used where as wp_ajax used for logged in users too.
That’s it.Now you can see yours ajax request in a browser. you are done it without any plugin. 🙂
You may also like:
To use multiple headers in WordPress
Voice Search in WordPress
To Reset the WordPress Loop
Thank you for reading.Feel free to share your thoughts! Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.