I am trying to create a search bar for a blog, which is working fine if i am logged in, but not when i am not logged out. As logged out user, it returns a empty array with succesed code 200. i shall really appreciated if someone can help me
here is my PHP file
`
function get_ajax_posts() {
$posts_d =array();
// Query Arguments
$args = array(
'post_type' => 'custom_posts',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => 'DESC',
'orderby' => 'date',
);
// The Query
$ajaxposts = new WP_Query($args); // changed to get_posts from wp_query, because `get_posts` returns an array
if($ajaxposts->have_posts( )){
while($ajaxposts->have_posts( )){
$ajaxposts->the_post();
array_push($posts_d, array(
'title' => get_the_title(),
'url' => get_permalink()
));
}
}
echo json_encode( $posts_d );
exit; // exit ajax call(or it will return useless information to the response)
}
// Fire AJAX action for both logged in and non-logged in users
// add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
wp_localize_script( 'hello-elementor-child-js', 'script',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
`
Here is my javascript code
`
jQuery('#s').on('keyup',function(){
$ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"
jQuery.ajax({
type: 'POST',
dataType: "json", // add data type
// url: script.ajax_url,
url: $ajaxurl,
data: { action : 'get_ajax_posts' },
success: function( response ) {
var jobs = '';
var count = 0;
var text = jQuery('#s').val().toLowerCase();
if (!arr || arr.length === 0){
var arr = jQuery(response.filter(function(value){
text = text || null;
return value.title.toLowerCase().includes(text);
}))
};
jQuery.each( arr, function( key, value ) {
if (count == 5){
return false;
} else {
jobs += '<a href="' + value.url + '"><p>' + value.title + '</p></a>';
count++;
}
} );
jQuery('#livesearch').html(jobs);
}
});
});
`
Edit:
I’ve solved the problem with wp_add_inline_script. But, Is there a way to get json object as private in a function?
2
Answers
To send ajax requests from theme files we can use wp_localize_script to globally declare our javascript variables.
You need to localize your script.
In your js file
Check and let me know whether the ajax call is working or not.
Also I have shared my working code attachment. Please check and let me know if you find any issue