Jquery ajax wordpress
Before going to start we need to know about ajax.AJAX stands for Asynchronous JavaScript and XML.Ajax has become a popular web technology,we can find it in most websites.Now a days everybody is not interested to access server side script by loading.So ajax is the best method to access server side script with out loading page.We can fetch data from database and show it to the front end without page refresh using this technology.It is very fast and smooth for displaying content to front end.So most of CMS platform are using ajax with in their system.WordPress use Ajax in a very robust and easy way.Today I will show you just how you can use Ajax in WordPress very easily.If you use jquery ajax for client side you can call a jquery library for that.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
You may already know that using ajax in WordPress is slightly different than normal ajax implementation in php. So before start the implementation we need to consider two things.
If you are looking for simple ajax implementation in php , check out Form submit using jQuery Ajax in php
- The URL of the WordPress admin-ajax.php file, where the data to be sent for processing.
- The wordpress ajax action hook called wp_ajax_. You need to hook a custom function into it which will be executed during the ajax call.Here we are using the custom function named demo_action.
Then write ajax code for that.
<script> var ajax_url="<?php echo admin_url('admin-ajax.php');?>"; var data={id:1,name:"Demo",action:"demo_action"}; $.ajax({ url:ajax_url, data:data, type:'POST', success: function(response) { console.log(response); }, error: function(error){ } }) </script>
Here in ajax_url variable is holding WordPress core ajax url.
After finishing the ajax code.Then go to your function.php of the theme or plugin page.
Add the following code.From client side we are simply sending id and name query parameter with data.
add_action("wp_ajax_demo_action", "demo_action"); add_action("wp_ajax_nopriv_demo_action", "demo_action"); function demo_action() { $id=$_POST['id']; $name=$_POST['name']; echo $name; exit; //Do your stuff here }
in add_action function add the action name ,which is send from ajax.
Here we are echoing the $name variable, which will be shown to success method inside console of your browser.
That all to use ajax in WordPress.