I have a custom loop to display projects in a grid on my Wordpress site. I'm creating filters for these projects and am getting stuck on the input search. I am getting a 400 error on my admin-ajax.php and not sure how to get this working. Can someone give me any tips? Here is my code:
PHP code for loop in functions.php
add_action('wp_ajax_my_action' , 'data_fetch');
add_action('wp_ajax_nopriv_my_action','data_fetch');
function data_fetch(){
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'projects',
'posts_per_page' => -1,
's' => esc_attr( $_POST['keyword'] ),
);
$the_query = new WP_Query($args);
if( $the_query->have_posts() ) : while ($the_query->have_posts() ) : $the_query->the_post();
?>
<div class="projects-column">
<div class="project-image">
<?php $image = get_field('image');
if( !empty($image) ): ?>
<img src="<?php echo $image['url']; ?>" class="project-image-tester" alt="<?php echo $image['alt']; ?>" />
<?php endif; ?>
<div class="project-info">
<span class="proj-name" style="font-weight: bold;"><b><?php the_title(); ?></b></span>
</div>
<div class="project-onhover">
<span class="proj-title"><p><b><?php the_title(); ?></b></p></span>
<span class="proj-details">
<p><span style="font-weight: bold;">LOCATION: </span><?php the_field('location'); ?></p>
<p><span style="font-weight: bold;">PROJECT VALUE: </span><?php the_field('project_value'); ?></p>
<p><span style="font-weight: bold;">SERVICES: </span> <?php echo wp_strip_all_tags( get_the_term_list( $post->ID, 'project_services', '', ', ', '' ) ); ?> </p></span>
</div><!--projects-on-hover-tester -->
</div><!--project-image-->
</div><!--projects-column -->
<?php
endwhile;
wp_reset_postdata();
php endif;
die();
}
JS code also in functions.php
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: wpAjax.ajaxUrl,
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#projects-container').html( data );
}
});
}
</script>
<?php
}
I localized the script earlier for another ajax request, so this is where the url is coming from:
wp_localize_script('ajax' , 'wpAjax',
array('ajaxUrl' => admin_url('admin-ajax.php'))