How to make ajax request from wordpress theme template file

I’m trying to make an ajax call from a template file within my custom theme. Originally I followed another tutorial which had me put the function that ajax will run when called in the admin-ajax.php file within the admin folder. This is working but obviously not really the best place to go because it gets over written every time wordpress is updated. So I’m trying to move this into my theme folder.

here is the ajax call inside them page-talent.php file:

$.ajax({
      type: 'POST',
      url: '<?php echo admin_url('admin-ajax.php');?>',
      dataType: "html", // add data type
      data: { action : 'get_ajax_posts' , filters: filters },
      success: function( response ) {
          console.log( response );

          //alert(response);

          $( '.posts-area' ).html( response ); 
      }
  });      
})

})(jQuery);

here is the code currently inside of the admin-ajax.php file

// ------------------------------
// ------------------------------
//       talent query code
// ------------------------------
// ------------------------------

function get_ajax_posts() {

    // get filters from 3 drop down menus 
	$tax_query = $_POST['filters'];
	
	$location = $tax_query['location'];
	$specialty = $tax_query['specialty'];

	$levels = $tax_query['level'];
	// create levels array for selected level and above
	switch ($levels) {
		    case 23:
		        $level = array('23'); // Level 1 through 5
		        break;
		    case 24:
		       $level = array('24'); // Level 2 through 5
		        break;
		    case 25:
		        $level = array('25');// Level 3 through 5
		        break;
			case 26:
		        $level = array('26');// Level 4 and 5
		        break;
			case 27:
		        $level = '27';// Level 5
		        break;
		    default:
		        $level = array('23', '24', '25', '26', '27');
		}

	// Display Talent if only Level is selected
	if(isset($tax_query['level']) && empty($tax_query['location']) && empty($tax_query['specialty'])){

		// Query Arguments
	    $args = array(
	      'orderby' => 'title',
          'order' => 'ASC',
          'post_type' => 'the-talent',
          'posts_per_page'=>-1,
	      'tax_query' => array(
	          'relation' => 'AND',
	          array(
	              'taxonomy' => 'level',
	              'field'    => 'term_id',
	              'terms'    => $level,// 23 (4), 24(4), 25(7), 26(3), 27(3) // array( 25, 26, 27 )
	              
	          ),   
	       ),
	    );
	}
	// Display Talent if only Level and Location is selected
	else if(isset($tax_query['level']) && isset($tax_query['location']) && empty($tax_query['specialty'])){

		// Query Arguments
	    $args = array(
	      'orderby' => 'title',
          'order' => 'ASC',
          'post_type' => 'the-talent',
          'posts_per_page'=>-1,
	      'tax_query' => array(
	          'relation' => 'AND',
	          array(
	              'taxonomy' => 'level',
	              'field'    => 'term_id',
	              'terms'    => $level,// 23 (4), 24(4), 25(7), 26(3), 27(3) // array( 25, 26, 27 )
	              
	          ), 
	          array(
	              'taxonomy' => 'location',
	              'field'    => 'term_id',
	              'terms'    => $location,
              ),  
	      ),
	    );
	}
	// Display Talent if all three are selected
	else if(isset($tax_query['level']) && empty($tax_query['location']) && isset($tax_query['specialty'])){

		// Query Arguments
	    $args = array(
	      'orderby' => 'title',
          'order' => 'ASC',
          'post_type' => 'the-talent',
          'posts_per_page'=>-1,
	      'tax_query' => array(
	          'relation' => 'AND',
	          array(
	              'taxonomy' => 'level',
	              'field'    => 'term_id',
	              'terms'    => $level,// 23 (4), 24(4), 25(7), 26(3), 27(3) // array( 25, 26, 27 )  
	          ), 
              array(
	              'taxonomy' => 'specialty',
	              'field'    => 'term_id',
	              'terms'    => $specialty,
              ),  
	      ),
	    );
	}
	// Display Talent if Level and specialty is selected
	else if(isset($tax_query['level']) && isset($tax_query['location']) && isset($tax_query['specialty'])){

		// Query Arguments
	    $args = array(
	      'orderby' => 'title',
          'order' => 'ASC',
          'post_type' => 'the-talent',
          'posts_per_page'=>-1,
	      'tax_query' => array(
	          'relation' => 'AND',
	          array(
	              'taxonomy' => 'level',
	              'field'    => 'term_id',
	              'terms'    => $level,// 23 (4), 24(4), 25(7), 26(3), 27(3) // array( 25, 26, 27 )  
	          ), 
	          array(
	              'taxonomy' => 'location',
	              'field'    => 'term_id',
	              'terms'    => $location,
              ),
              array(
	              'taxonomy' => 'specialty',
	              'field'    => 'term_id',
	              'terms'    => $specialty,
              ),  
	      ),
	    );
	}
	// Display Talent if only Location is selected
	else if(empty($tax_query['level']) && isset($tax_query['location']) && empty($tax_query['specialty'])){

		// Query Arguments
	    $args = array(
	      'orderby' => 'title',
          'order' => 'ASC',
          'post_type' => 'the-talent',
          'posts_per_page'=>-1,
	      'tax_query' => array(
	          'relation' => 'AND', 
	          array(
	              'taxonomy' => 'location',
	              'field'    => 'term_id',
	              'terms'    => $location,
              ),  
	      ),
	    );
	}
	// Display Talent if Location and specialty is selected
	else if(empty($tax_query['level']) && isset($tax_query['location']) && isset($tax_query['specialty'])){

		// Query Arguments
	    $args = array(
	      'orderby' => 'title',
          'order' => 'ASC',
          'post_type' => 'the-talent',
          'posts_per_page'=>-1,
	      'tax_query' => array(
	          'relation' => 'AND',
	          array(
	              'taxonomy' => 'location',
	              'field'    => 'term_id',
	              'terms'    => $location,
              ),
              array(
	              'taxonomy' => 'specialty',
	              'field'    => 'term_id',
	              'terms'    => $specialty,
              ),  
	      ),
	    );
	}
	// Display Talent if only specialty is selected
	else if(empty($tax_query['level']) && empty($tax_query['location']) && isset($tax_query['specialty'])){

		// Query Arguments
	    $args = array(
	      'orderby' => 'title',
          'order' => 'ASC',
          'post_type' => 'the-talent',
          'posts_per_page'=>-1,
	      'tax_query' => array(
	          'relation' => 'AND',
              array(
	              'taxonomy' => 'specialty',
	              'field'    => 'term_id',
	              'terms'    => $specialty,
              ),  
	      ),
	    );
	}
	
	else{
		$args = null;
		//echo "else Args: ". $args;
	}

	wp_reset_query();

    // The Query
    $ajaxposts = new WP_Query( $args );

    $response = '';

    // The Query
    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
            //$response .= get_template_part('products');

            $response .= "";

            $name = get_field('name');
            $main_image = get_field('main_image');

         ?>

        <div class="col-sm-6 col-md-3 talent-col">
          <div class="talent">
            <a type="button" href="<?php the_permalink() ?>">
             <img class="img-responsive" src="<?php echo $main_image; ?>">
             <h3 class="dark"><?php echo $name; ?></h3> 
            </a>
          </div><!-- close talent -->
        </div><!-- close col -->

       <?php
     
       }// end while
    } else {
        $response .= get_template_part('none');
    }
    
    exit; // leave ajax call
}// end get_ajax_posts

// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');

Someone said to add this to my functions.php file which I did, but then how to I call it from the Ajax request?

Or another suggestion waste just create a talent-ajax.php file inside my theme folder, but then how do I link to it from the ajax call? I tried this but it didn’t work…

      $.ajax({
          type: 'POST',
          //url: '<?php //echo admin_url('admin-ajax.php');?>',
          url: '<?php echo bloginfo('template_directory')."talent-ajax.php";?>',
          dataType: "html", // add data type
          data: { action : 'get_ajax_posts' , filters: filters },
          success: function( response ) {
              console.log( response );

              //alert(response);

              $( '.posts-area' ).html( response ); 
          }
      });      
    })

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.