Using wordpress admin ajax is very simple. You need to follow this steps accordingly.
- Create a function to display your form in front end. You can use short code to include your form in post/page.
- Make sure you must have action filed in form, with the help of action value you can access wp_ajax hook.
- Declare the ajax hook respective to the action name. In this example, my action name is the_ajax_hook1, so i have created the hook wp_ajax_the_Action_hook1(wp_ajax_{$action}).
- Include your js file by wp_enque_script().
- Localize your included script with the help of wp_localize_script(). That’s all..
Here is our example…
<br />/*<br />Plugin name:KTM Ajax call<br />Description: creating ajax call from front end<br />Author : Karthik<br />*/<br />//It helps to add your script.<br />wp_enqueue_script('ktm_my_script' , <br /> plugin_dir_url(__FILE__) . 'script.js' , <br /> array('jquery') <br /> );<br />//It helps to access php variable in javascript file.<br />wp_localize_script('ktm_my_script', <br /> 'the_ajax_script',<br /> array('ajaxurl'=>admin_url( 'admin-ajax.php' ) )<br /> );<br /><br />/* wp_ajax_ hook will be triggered when an ' the_ajax_hook1 ' action is set.*/<br />add_action('wp_ajax_the_ajax_hook1','ktm_ajax_callback');<br />add_action('wp_ajax_nopriv_the_ajax_hook1','ktm_ajax_callback');<br /><br />/* This is the response function to be executed when the ajax <br />request is made with the action variable */<br />function ktm_ajax_callback(){<br /> $name = $_POST['name'];<br /> echo 'Hello '.$name.'!!!';<br /> die();<br />}<br /><br />//Front end view. This can be accessed by the hook [ktm_ajax_call].<br />function front_end_form(){<br />$frm = '<br /> <form id="theForm"><br /> <input type="text" name="name"><br /> <input type="hidden" name="action" value="the_ajax_hook1"><br /> <input type="submit" onClick="return disp()"><br /> </form><br /> <div id="response">Hi</div>';<br /> return $frm;<br />}<br /><br />add_shortcode('ktm_ajax_call','front_end_form');<br />?><br /><br />
Here is our script.js
<br />function disp(){<br /> jQuery.post(<br /> the_ajax_script.ajaxurl,<br /> jQuery('#theForm').serialize(),<br /> function(data){<br /> jQuery('#response').html(data);<br /> }<br /> );<br /> return false;<br />}<br />