Ajax Search Posts and Ajax Load more

56
December 04, 2021, at 3:10 PM

I'm not that yet super familiar with AJAX but I'm learning.

I was able to work on loading search posts via ajax. My question is how do you implement it together with a load more posts via ajax again? Like when the posts are loaded there is a load more button that loads it via AJAX?

Do I create another callback function for the load more? or do I use callback function with search posts?

To make it more clear here is my working code:

  // Scripts for Ajax Filter Search
function my_ajax_filter_search_scripts() {
    wp_enqueue_script( 'my_ajax_filter_search', get_stylesheet_directory_uri(). '/custom-script.js', array(), null, true );
    wp_localize_script( 'my_ajax_filter_search', 'ajax_url', admin_url('admin-ajax.php') );
}
// Ajax Callback
add_action('wp_ajax_my_ajax_filter_search', 'my_ajax_filter_search_callback');
add_action('wp_ajax_nopriv_my_ajax_filter_search', 'my_ajax_filter_search_callback');
 
function my_ajax_filter_search_callback() {
 
    header("Content-Type: application/json"); 
    if(isset($_GET['search'])) {
        $search = sanitize_text_field( $_GET['search'] );
        $search_query = new WP_Query( array(
            'post_type' => 'wpcr3_review',
            'post_status' => 'publish',
            'posts_per_page' => $reviewsPerPage,
            'meta_key'       => 'wpcr3_review_rating',
            'meta_value'     =>  $rating,
            'meta_compare'   => '=',
            's' => $search
        ) );
    } else {
        $search_query = new WP_Query( $args );
    } 
    if ( $search_query->have_posts() ) {
        $result = array();
        while ( $search_query->have_posts() ) {
            $search_query->the_post();
            $cats = strip_tags( get_the_category_list(", ") );
            $result[] = array(
                "id" => get_the_ID(),
                "title" => get_the_title(),
                "content" => get_the_content(),
                "permalink" => get_permalink()
                //"poster" => wp_get_attachment_url(get_post_thumbnail_id($post->ID),'full')
            );
        }
        wp_reset_query();
        echo json_encode($result);
    } else {
        echo json_encode($result);
    }
    wp_die();
}

Here's my AJAX code

//AJAX 
var mafs = $("#my-ajax-filter-search"); 
var mafsForm = mafs.find("form"); 
mafsForm.submit(function(e){
    e.preventDefault(); 
    if(mafsForm.find("#search").val().length !== 0) {
        var search = mafsForm.find("#search").val();
        console.log(search);
    }
    var data = {
        action : "my_ajax_filter_search",
        search : search,
    }
    // we will add codes above this line later
    $.ajax({
        url : ajax_url,
        //dataType: 'json',
        data : data,
        beforeSend : function ( e ) {
            mafs.find("div#ajax_filter_search_results").empty();
            var html  = "<p class='loading'>Loading...</p>";
            mafs.find("div#ajax_filter_search_results").append(html);
        },
        success : function(response) {
            mafs.find("div#ajax_filter_search_results").empty();
            if(response) {
                //if(!jQuery.isEmptyObject(response)){
                for(var i = 0 ;  i < response.length ; i++) {
                    var html  = "<div id='review-" + response[i].id + "'>";
                    html += "      <div class='review-info'>";
                    html += "          <h4>" + response[i].title + "</h4>";
                    html += "          <p>" + response[i].content + "</p>";
                    html += "      </div>";
                    html += "</div>";
                    mafs.find("div#ajax_filter_search_results").append(html);
                }
            } else {
                var html  = "<p class='no-result'>No matching movies found. Try a different filter or search keyword</p>";
                mafs.find("div#ajax_filter_search_results").append(html);
            }
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }    
    });
});

so again, how do I integrate a load more ajax function?

READ ALSO
Is there a Postgrest API equivalent for MySQL?

Is there a Postgrest API equivalent for MySQL?

I earlier worked on postgres sql database and created some functions there which i called using postgrest api via postman

76
Run tracert command in Python but stop at &quot;request timed out&quot;

Run tracert command in Python but stop at "request timed out"

I need to tracert an IP and I am doing it like this:

62
Is there any way to perform rollback in firebase cloud functions?

Is there any way to perform rollback in firebase cloud functions?

We are running a larger backend application in NodeJS/TS on Firebase with about 180 cloud functions and Firestore as databaseFirebase has been good for our needs so far, but we are getting to a level of usage where even small amounts of down-time can cause a lot of damage

50