Integrating JQuery AJAX in WordPress using JSON

- In this example we’ll be using a drop down menu to change content

Components
- #dropdownmenu – ID of select drop down
- .content-section – Class of content section
- do-jquery.js – JavaScript file, with JQuery code for AJAX call
- Functions.php – WordPress file involved

WordPress Configuration Steps

Create JavaScript file & enqueue it in functions.php, for JQuery code. Note 1, in this example, we’re enqueuing it on all pages. You should only enqueue it where its actually needed. Note 2, we’ve also deregistered the WP version of JQuery and use the Google hosted version. Therefore, we also can use $ , not jQuery – as in the WP hosted version. Read more about reasons to let Google host jQuery for you here.


// located in js directory under theme directory
wp_register_script( 'do-jquery', get_template_directory_uri() . '/js/do-jquery.js', array('jquery'), '1.0', true );
wp_enqueue_script('do-jquery');

A drop down menu will be added to the WP page


<form>
<select id=”dropdownmenu” name=”dropdownmenu” >
</select>
</form>
<div id=”content-section”></div>

Development Steps

The following code will go into do-jquery.js. The code below calls admin-ajax.php to process the ajax call. The action parameter that is passed in needs to match the add_action parameter in functions.php. Additional parameters can be specified in the JSON data that’s sent to functions.php. In this example, we’re passing the “typeID”, which is the value from the drop down menu.


    $("#dropdownmenu").change(function() {
        $.ajax({
        url: 'wp-admin/admin-ajax.php',
        // formulate JSON data to pass for processing
        data:{
	//action is the name of the PHP function in functions.php
           'action':'ajax_populate_content',
	//typeID is the drop down value
           'typeID':$(this).val()
           },
        dataType: 'JSON',
        success:function(data){
        $('.content-section').html("

“); $(‘.content-container’).html(data) }, error: function(errorThrown){ alert(‘error’); console.log(errorThrown); } }); });

The last piece of code will go into functions.php. In this example we’re just going to receive the typeID request, query wordpress, and encode the output.



// actions are added - we could set different rules for non privledged users and those who are logged in. In this situation, we are sending both types of requests to the same function. 

// Prefixes are wp_ajax_nopriv_ and wp_ajax_
  add_action( 'wp_ajax_nopriv_ajax_populate_content', 'JSONcontentoutput' );  
  add_action( 'wp_ajax_ajax_populate_content', 'JSONcontentoutput' );  

    function JSONcontentoutput()
	{  
    //get the data from ajax() call  
    $typeID = $_REQUEST["typeID"];
    $args = array(
        'cat' => $typeID,
        'post_status' => 'publish'
    );
   // The Query
	$the_query = new WP_Query( $args );

	// The Loop
   if ($the_query->have_posts()) : 
		while ( $the_query->have_posts() ) :
			$the_query->the_post();
			$output.='
  • ' . get_the_title() . '
  • '; endwhile; endif; $output=json_encode($output); if(is_array($output)) { print_r($output); } else { echo $output; } die; }

    Leave a Reply