I have an ajax function that connects to a php file. I’m trying to pass arguments (‘tax_query’) collected on the page to a query running on php. How can I create an array (or maybe just a string) in javascript and pass that as an argument to the function inside php. Everything is working except that I have query arguments in the php file hard coded where I want them to be dynamic based on what I pass through the ajax request.
Here is my jQuery function that grabs data from user selections, saves the variables and connects to php via ajax
(function($) {
function getFilters () {
var filters = {}
$('.checked').each(function () {
filters[this.dataset.filter] = this.dataset.value
})
return filters
}
$(".dropdown-menu li a").click(function (event) {
var $this = $(this)
var $dropdown = $this.parents('.dropdown')
var html = $this.text() + ' <span class="caret"></span>'
$dropdown.find(".btn").html(html);
$dropdown.find('a').removeClass('checked');
$this.addClass('checked');
var filters = getFilters();
//var level = filters["level"];
var level = filters.level;
var location = filters.location;
var specialty = filters.specialty;
alert("Level: "+level+" Location: "+location+" Specialty: "+specialty);
console.log(getFilters());
event.preventDefault();
alert("made it up to ajax");
$.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "html", // add data type
data: { action : 'get_ajax_posts' },
success: function( response ) {
console.log( response );
$( '.posts-area' ).html( response );
}
});
})
})(jQuery);
here is my php function that runs a Wordpress post query and returns back to jquery.
function get_ajax_posts() {
// Query Arguments
$args = array(
'post_type' => 'the-talent',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'level',
'field' => 'term_id',
'terms' => array( '25' ),// needs to be 3 and up? maybe use if statements?
),
array(
'taxonomy' => 'location',
'field' => 'term_id',
'terms' => array( '20' ),
),
array(
'taxonomy' => 'specialty',
'field' => 'term_id',
'terms' => array( '4' ),
),
),
);
// 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">
<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
;
}
} else {
$response .= get_template_part('none');
}
//echo $response;
exit; // leave ajax call
}
// 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');