AJAX in WordPress Plugins


WordPress Guide

This article, aimed at plugin developers, describes how to add Ajax to a plugin.

Step 1:

Create a javascript file call my_query.js to handle you request and save it on js(js/my_query.js) folder of your plugin.

// JavaScript Document
function myfunction(id)
{
 var ajaxval = id;
 $.ajax({
    type: 'POST',
    url:  ajaxvoteajax.ajaxurl,
    data: {
      'action': 'my_action',
      'val': ajaxval
      },
    context: document.body,
    success: function(data, textStatus, XMLHttpRequest){
      var data = data; 
       $('#model').html(data);    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    alert(errorThrown);
    },
    complete: function(XMLHttpRequest, status) {
          }
 });
}

Note: Replace action parameter by your action. In this example I used “my_action” as the action.

Step 2:

With external files, we must enqueue them in PHP so they are included on the page

<?php add_action('wp_enqueue_scripts', 'my_enqueue'); function my_enqueue() { wp_enqueue_script('myenqueue', plugins_url('/js/my_query.js',__FILE__), array('jquery')); wp_localize_script( 'myenqueue', 'ajaxmy_enqueuejax', array( 'ajaxurl'…

View original post 102 more words