Get cool snippets on php, css, jQuery, Magento and wordpress

Using wordpress admin ajax

Using wordpress admin ajax is very simple. You need to follow this steps accordingly.

  1. Create a function to display your form in front end. You can use short code to include your form in post/page.
  2. Make sure you must have action filed in form, with the help of action value you can access wp_ajax hook.
  3. 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}).
  4. Include your js file by wp_enque_script().
  5. 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'=&gt;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 /> &lt;form id=&quot;theForm&quot;&gt;<br /> &lt;input type=&quot;text&quot; name=&quot;name&quot;&gt;<br /> &lt;input type=&quot;hidden&quot; name=&quot;action&quot; value=&quot;the_ajax_hook1&quot;&gt;<br /> &lt;input type=&quot;submit&quot; onClick=&quot;return disp()&quot;&gt;<br /> &lt;/form&gt;<br /> &lt;div id=&quot;response&quot;&gt;Hi&lt;/div&gt;';<br /> return $frm;<br />}<br /><br />add_shortcode('ktm_ajax_call','front_end_form');<br />?&gt;<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 />

karthi s

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: