Jump to content

data is 0?


samoht

Recommended Posts

hello all, 

 

I am trying to use ajax, to filter my custom post_type using a dropdown (several actually, but just working on one now). 

 

when I check the console.log for my two variables the log returns the values that I need to pass into my function check_ajax() I am using to do the filtering, but when I check the log for the data array it comes up with 0?

 

Here is my Jquery code:

//Listen for the menu's to change except the main filter_by dropdown
	var ids = ['filter_preacher_dropdown', 'filter_sort_by_dropdown', 'filter_per_page_dropdown', 
	'filter_series_dropdown', 'filter_tag_dropdown', 'filter_book_dropdown', 'filter_year_dropdown'];

	$('#' + ids.join(',#')).change(function() {

			var sermonForm = $("#sermon_filter_form");

			var myForm = $(this).closest("form");
			var meta_key = this.name; 
		    var meta_value = $(this).val();
		    var current_selection = $(this);
		    var ajaxLoader = '<div class="loading_img"></div>';
		    $(this).after(ajaxLoader);
		    $.ajax
		    (
		        {
		        	type: "POST",
		            url: ajax_object.ajax_url,     
		            data: {
				        'action': 'filter_sermons',
				        'meta_key': meta_key,
				        'meta_value': meta_value,
				    },
					dataType: 'JSON',
					success:function(data){
					
						console.log(data);
					}

		        }
		    ); 
	                                           

		
	});

and here is my function.php code:

	//ajax for sermons filter
	add_action('wp_ajax_filter_sermons', 'check_ajax'); 
	add_action('wp_ajax_nopriv_filter_sermons', 'check_ajax');
}
/**
* Sets up custom query for AJAX to filter
*
*/
function my_sermon_query($meta_key, $meta_value) {
  return new WP_Query( array( 'meta_key' => $meta_key, 'meta_value' => $meta_value, 'post_type' => 'mbsb_sermon' ) );
}

function check_ajax() {
	$mk = intval($_POST['meta_key']);
	$mv = intval($_POST['meta_value']);
	$query = my_sermon_query($mk, $mv);
	echo json_encode($query);
    die();
}

Any ideas what I am missing/doing wrong?

 

Thanks,

 

Link to comment
Share on other sites

Thanks Guru,

 

But if I use 'results' I either get undefined - or I get 0 again??

	data: {
		action: 'filter_sermons',
		meta_key: mk,
		meta_value: mv
	},
	dataType: 'JSON',
        success:function(data){
		console.log(results);
	}	

Gets me an Uncaught ReferenceError: results is not defined 

 

and

	data: {
		action: 'filter_sermons',
		meta_key: mk,
		meta_value: mv
	},
	dataType: 'JSON',
	success:function(results){
		console.log(results);
	}

gets me a 0 

 

??

Link to comment
Share on other sites

CroNix is referring to your PHP code. On line 48 of functions.php you are calling the my_sermon_query() function. This function only returns a resultset (object) not the posts themselves.

 

According to the Wordpress docs on the WP_Query() function you can use get_posts() to get the posts returned by the query. Example

	$query = my_sermon_query($mk, $mv);  // perform query
        $posts = get_posts();                // returns posts in an array
	echo json_encode($posts);            // json encode the posts array
Link to comment
Share on other sites

OK, thanks for the help understanding but I am not quite there. 

 

So the AJAX is ok?  ( I changed the php function as noted but I still get 0 on the console log )

 

If so does that mean I just need to call the function from my page as the main query? 

				$query = check_ajax();
				?>

			<?php while ( $query->have_posts() ) : $query->the_post(); ?>

that doesn't seem right, because I have no default posts until the filter by 

 

 

or do I put the while loop for the posts in the check_ajax() function? 

Link to comment
Share on other sites

I slightly rewrote the ajax and now I do get a return on the console

		$.ajax
		(
			{
				type: "POST",
				url: ajax_object.ajaxurl,       
				data: {action: 'filter_sermons', meta_key: mk, meta_value: mv, post_per_page: ppp},
				success: function(data){
					console.log(data);
				}
			}
		);

but still nothing is happening on the page? 

Link to comment
Share on other sites

Still no page change? 

 

Do I have to use my_sermon_query() on the main page? or does check_ajax() take care of that? 

 

I think I am missing only a small piece - but its still stopping the works. 

 

I have a main page (small-sermons.php) that queries the WPDB for all posts with the custom post_type=mbsb_sermon

 

On that page I have included a form that allows the users to filter/search based on series, preacher, service  - which are all custom post_types themselves. 

 

So I have a JQuery/Ajax call (frontend.js) that fires when those dropdowns change so I can handle resetting the query with the new parameters by sending the results to a custom function (functions.php) check_ajax(). 

I seem to be getting the right variables in the $_POST object to create the proper query for the search - but its not updating the page with the new query??

Link to comment
Share on other sites

I realized that I had the check_ajax() function in the wrong place. So I moved it and the calls to it, and now I have the AJAX working (I think) - but the problem is what I am returning.

function check_ajax() {
	$mk = '"'.$_POST['meta_key'].'"';
	$mv = intval($_POST['meta_value']);
	$ppp = intval($_POST['posts_per_page']);
	$query = new WP_Query( array( 'meta_key' => $mk, 'meta_value' => $mv, 'post_type' => 'mbsb_sermon', 'posts_per_page' => $ppp ) );
    $posts = get_posts();                		// returns posts in an array
    echo json_encode($posts);
	die();
}

returns [] 

 

while 

   echo json_encode($query);

returns

{"query":{"meta_key":"\"preacher\"","meta_value":365,"post_type":"mbsb_sermon","posts_per_page":0},"query_vars":{"meta_key":"\"preacher\"","meta_value":365,"post_type":"mbsb_sermon","posts_per_page":10,"error":"","m":"","p":0,"post_parent":"","subpost":"","subpost_id":"","attachment":"","attachment_id":0,"name":"","static":"","pagename":"","page_id":0,"second":"","minute":"","hour":"","day":0,"monthnum":0,"year":0,"w":0,"category_name":"","tag":"","cat":"","tag_id":"","author":"","author_name":"","feed":"","tb":"","paged":0,"comments_popup":"","preview":"","s":"","sentence":"","fields":"","menu_order":"","category__in":[],"category__not_in":[],"category__and":[],"post__in":[],"post__not_in":[],"tag__in":[],"tag__not_in":[],"tag__and":[],"tag_slug__in":[],"tag_slug__and":[],"post_parent__in":[],"post_parent__not_in":[],"author__in":[],"author__not_in":[],"ignore_sticky_posts":false,"suppress_filters":false,"cache_results":true,"update_post_term_cache":true,"update_post_meta_cache":true,"nopaging":false,"comments_per_page":"50","no_found_rows":false,"order":"DESC"},"tax_query":{"queries":[],"relation":"AND"},"meta_query":{"queries":[{"key":"\"preacher\"","value":365}],"relation":"AND"},"date_query":false,"request":"SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) WHERE 1=1 AND wp_posts.post_type = 'mbsb_sermon' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future' OR wp_posts.post_status = 'draft' OR wp_posts.post_status = 'pending') AND ( (wp_postmeta.meta_key = '\\\"preacher\\\"' AND CAST(wp_postmeta.meta_value AS CHAR) = '365') ) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10","posts":[],"post_count":0,"current_post":-1,"in_the_loop":false,"comment_count":0,"current_comment":-1,"found_posts":0,"max_num_pages":0,"max_num_comment_pages":0,"is_single":false,"is_preview":false,"is_page":false,"is_archive":true,"is_date":false,"is_year":false,"is_month":false,"is_day":false,"is_time":false,"is_author":false,"is_category":false,"is_tag":false,"is_tax":false,"is_search":false,"is_feed":false,"is_comment_feed":false,"is_trackback":false,"is_home":false,"is_404":false,"is_comments_popup":false,"is_paged":false,"is_admin":true,"is_attachment":false,"is_singular":false,"is_robots":false,"is_posts_page":false,"is_post_type_archive":true,"thumbnails_cached":false}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.