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>
</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(); }); });
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
, { type: 'POST', data: { action: 'getImageProduct
', value: valueSelect
, }, dataType: 'json', }); } }); });
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
html => string
}
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',
value: valueSelect,
},
dataType: 'json',
complete : function ( response ) {
},
success: function ( response ) {
if ( response.success ) {
image = response.html
; } else { } }, error: function ( errorThrown ) { 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',
value: valueSelect,
},
dataType: 'json',
complete : function ( response ) {
},
success: function ( response ) {
if ( response.success ) {
image = response.html;
$('#productImageResult').html( image );
} else { $('#productImageResult').html( '<span>No image available for product #id: ' + valueSelect + '</span>' ); } }, error: function ( errorThrown ) { 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'];
}
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;
default:
}
}
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 () {
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;
default:
}
$results['success'] = TRUE;
$results['html'] = $image;
echo json_encode ( $results );
die();
}
4 – The link between client and server sides. add_action
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' );