Pure JavaScript Basic AJAX Call In WordPress Custom Plugin Development

Solution:1

Use following code

Main Plugin File:

<?php
/*
Plugin Name: WP Testing Plugin
Plugin URI: http://www.wordpress.org/WP-Testing-Plugin
Description: A Detailed Description About This Plugin.
Author: Muhammad Hassan
Version: 0.1
Author URI: http://www.wordpress.org
*/

// Calling All PHP File To Load
include('my_functions.php');

/*____________WP Testing Plugin Admin/Script_____________*/
function wp_testingPlugin_admin() {
    echo '
        <form id="searchForm">
            <input name="WhatToSearch" type="text" />
            <input type="submit" value="Search"/>
            <input type="reset" value="Reset"/>
            <div id="showReturnData"></div>
        </form>
    ';
}
/*__________________________________________________________________*/

/*____________WP Testing Plugin Option_____________*/
//Adding "WP Testing Plugin" Menu To WordPress -> Tools
function wp_testingPlugin() {
    //  add_management_page( $page_title, $menu_title, $capability, $menu_slug, $function);                  Menu Under Tools
    add_management_page("WP Testing Plugin By Hassan", "WP Testing Plugin", 'activate_plugins', "WP-Testing-Plugin", "wp_testingPlugin_admin");
}
add_action('admin_menu', 'wp_testingPlugin');
/*__________________________________________________________________*/
?>

my_functions.php

<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
      wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ).'my_javascript.js', array('jquery') );
      wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
/****************************************************************************/
// Run Search Function
/****************************************************************************/
/* Register This Function When This File Is Loaded To Call By WordPress AJAX */
add_action('wp_ajax_nopriv_SearchFunction', 'ajaxSearchFunction'); // For Web Visitors
add_action('wp_ajax_SearchFunction', 'ajaxSearchFunction'); // For Admin User
function ajaxSearchFunction(){
    if($_POST['WhatToSearch'] == ""){
        $WhatToSearch = "Nothing";
    } else {
        $WhatToSearch = $_POST['WhatToSearch'];
    }
    echo "<div class='success'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToSearch.".</div>";
}
?>

my_javascript.js

jQuery(document).ready(function() {
jQuery('#searchForm').on("submit",function(e) {
var incomingData = jQuery('#searchForm').serializeArray();
incomingData.push({name: 'action', value: 'SearchFunction'});
alert(JSON.stringify(incomingData));
jQuery.ajax({
type: 'post',
url: my_ajax_object.ajax_url,
data: incomingData,
success: function(response) {
jQuery('#showReturnData').html(response);
},
error: function(response) {
jQuery('#showReturnData').html('<div">Error</div>');
},
});
return false; // For Not To Reload Page
});
});

Thanks for reading this. If you like this basic example then Vote up the question and answer to help others too.

Solution:2

The process for making an AJAX call begins on the client side so, once the page has already been displayed, on the client site we have only got the HTML elements of the browser so, these elements will be our starting point. An AJAX call almost always begins with the HTML elements of the browser.

On the screen we have got a select field like this, and additionaly, we have an HTML element that will contain the image of the product but now, this last HTML element is empty.

Take a look to its code

<label for="ProductNameID">Select your Product</label>
<select id="ProductNameID" name="ProductName">
    <option value="0">No product selected</option>
    <option value="2143">King size Table</option>
    <option value="2144">Big Table</option>
    <option value="3551">Medium Table</option>
    <option value="2145">Small Table</option>
    <option value="2847">Tiny Table</option>
    //... the rest of products.
</select>
<span id="productImageResult" ></span>

2 – The javascript function (jQuery)

As we have saw, the jQuery function has always got 4 sections. So our jQuery function to construct the AJAX call will begin taking the value of the select field but, taking into account that if we want that the image changes acording on the value of this field, we must take/check the value of the field each time that it changes. Perhaps, in the first section we could write a jQuery function that controls the change event for the field whose id attribute is ProductNameID.

jQuery(document).ready( function($) {
    var valueCheck;
    $('#ProductNameID').on( 'change', function () { valueSelect = $(this).val();  // other sections in a few seconds }); });

With the value of this variable called valueSelect now, we’re goint to develop the second section of the jQuery function. To do this, we have to add a standard jQuery $.ajax() function call that contains the dataValues, in our example valueSelect, the name of the action that the remote execution of WP has to run and, of course, the remote URL that will start the remote execution of the WP in the Server Side.

jQuery(document).ready( function($) {
    var valueCheck;
    $('#ProductNameID').on( 'change', function () {
         valueSelect = $(this).val();
         if ( parseInt ( valueSelect ) > 0 ) {
		$.ajax( 
                     ajaxurl, // The remote URL address that starts the remote execution of WP { type: 'POST',  // you can choose among any of HTTP request methods data: { action: 'getImageProduct', // The name of the WP action value: valueSelect,  // The dataValues  // if you need it, other dataValues as elements of the object data }, dataType: 'json', // we inform that we are going to receive PHP results as a JSON array  // ... other parameters for configuring the AJAX call if you need it  // Here the third section }); } }); });

Now, we have to develop the third section where we’ll get the JSON array of results sent by the remote PHP called function by the remote execution of the WP. And we’re goint to suppose the this remote PHP funcion sent us and array with this structure.

array {
    success => boolean // [ TRUE, FALSE ], 
    html    => string  // something like: <img scr="etc...." >
}

So, the third section will be like this

jQuery(document).ready( function($) {
    var valueCheck;
    $('#ProductNameID').on( 'change', function () {
         valueSelect = $(this).val();
         if ( parseInt ( valueSelect ) > 0 ) {
		$.ajax( ajaxurl, {
			type: 'POST',
			data: { action: 'getImageProduct', // The name of the WP action
				value:	valueSelect,       // the dataVAlues
			},
			dataType: 'json',
			complete : function ( response ) {   // to develop always
                        }, 
			success: function ( response ) {     // to develop in case of correct AJAX call
                             if ( response.success ) {
                                  image = response.html;  // Here we get the results of the PHP remote function  // The code for other results in the JSON object response  // Here will write the Last section } else {  // code in case of image error } }, error: function ( errorThrown ) {  // to develop in case of AJAX call error console.log( errorThrown ); }, }); } }); });

And finaly, in the last section we’ll introduce the PHP remote function results in the HTML elements of the screen so, we have to put the response.html inside the span whose id is productImageResult. See the complete code of the jQuery function.

jQuery(document).ready( function($) {
    var valueCheck;
    $('#ProductNameID').on( 'change', function () {
         valueSelect = $(this).val();
         if ( parseInt ( valueSelect ) > 0 ) {
		$.ajax( ajaxurl, {
			type: 'POST',
			data: { action: 'getImageProduct', // The name of the WP action
				value:	valueSelect,       // the dataVAlues
			},
			dataType: 'json',
			complete : function ( response ) {   // optionally to develop in any case: success or error
                        }, 
			success: function ( response ) {     // to develop in case of success
                             if ( response.success ) {
                                  image = response.html;  // Here we get the results of the PHP remote function
                                  $('#productImageResult').html( image ); } else { $('#productImageResult').html( '<span>No image available for product #id: ' + valueSelect + '</span>' ); } }, error: function ( errorThrown ) {  // to develop in case of error console.log( errorThrown ); }, }); } }); });

3 – The remote server side function

This part has also got the same structure always. In the first section the function picks up the values sent by the XMLHttpRequest and the simplest way to do it is using the $_POST PHP vars. So the first section of our remote function could be like this.

function myImagesSelector () {
     $id = $_POST['value'];
     // $color = $_POST['color'];  // you can get other var if you need it
     // etc.

     // Here the second section

}

The second section is the main task of the remote PHP function. Here is where you can develop your database request, or call to another function, or whatever. For this example, we develop a simple switch that retrieve the correct image URL associated with each one of the product #id’s.

function myImagesSelector () {
     $id    = (int) $_POST['value'];

     $image = '';
     switch ($id) {
         case 2143:
        case 2144:
              $image = '<img src="http://mysite.com/products/' . $id . '/images/' . $id . '_bordered_big.jpg" >';
              break;
         case 2145:
              $image = '<img src="http://mysite.com/products/' . $id . '/images/product_big.jpg" >';
              break;
         case 2847:
         case 3551:
              $image = '<img src="http://mysite.com/products/' . $id . '/images/' . $id . '_00.jpg" >';
              break;
         // other cases
         default:
              // No image;
     }

     // Here the third section


}

And finally we add the last section, where we echoes the results as a JSON array, adding if the remote procedure is OK.

function myImagesSelector () {

     // third section in case of error
     if ( isset ( $_POST['value'] ) ) {
          $results['success'] = FALSE;
          $results['html']    = '';
          echo json_encode ( $results );
          die();
     }

     $id    = (int) $_POST['value'];
     $image = '';
     switch ($id) {
         case 2143:
         case 2144:
              $image = '<img src="http://mysite.com/products/' . $id . '/images/' . $id . '_bordered_big.jpg" >';
              break;
         case 2145:
              $image = '<img src="http://mysite.com/products/' . $id . '/images/product_big.jpg" >';
              break;
         case 2847:
         case 3551:
              $image = '<img src="http://mysite.com/products/' . $id . '/images/' . $id . '_00.jpg" >';
              break;
         // other cases
         default:
              // No image;
     }

     // Third section in case of success
     $results['success'] = TRUE;
     $results['html']    = $image;
     echo json_encode ( $results );
     die();

}

In the case of WP, if we want to use its AJAX API for creating our calls, we have to add a final line where we explain to WP that we want to run the remote function inside a concrete action so that basically add_action( actionName, functionName ).

However, in case of AJAX requests, WP has got his own API so firstly, we have to distinguish between web user interface requests and WP admin interface requests because each one of them has got a different associated action names.

And secondly, we can’t use our actionName directly but we have to add a preffix to the actionName. See this two examples.

If our remote function name is myImagesSelector and our action name is getImageProduct, in the case of an AJAX call made from the WP admin interface we have to add this code line to construct the link:

add_action ( 'wp_ajax_' . 'getImageProduct', 'myImagesSelector' );

And in the case of an AJAX call made from the web user interface we have to add this code line

add_action ( 'wp_ajax_nopriv_' . 'getImageProduct', 'myImagesSelector' );

Of course, we can add both of lines if we want to be able to execute our remote function from both interfaces.

add_action ( 'wp_ajax_' . 'getImageProduct', 'myImagesSelector' );
add_action ( 'wp_ajax_nopriv_' . 'getImageProduct', 'myImagesSelector' );