skip to Main Content

I’m trying to send an ajax result as a json but google inspector is showing a parse error

ajax

jQuery(document).ready(function($){

    var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
    var page = 1; // What page we are on.
    var ppp = 3; // Post per page

    $("#misha_loadmore").on("click",function(){ // When btn is pressed.
        $("#misha_loadmore").attr("disabled",true); // Disable the button, temp.
        $.ajax({
            type: 'POST',
            cache : false,
            url: ajaxUrl,
            data:{
            "action":"more_post_ajax",
            "offset": (page * ppp) + 1,
            "ppp": ppp},
            dataType: 'json',
            success: function(data){
                page++;
                console.log(data);
                //$(".post-grid-container").append(posts); // CHANGE THIS!
                $("#misha_loadmore").attr("disabled",false);
            },
            error: function(error) {
                console.log('error:', error);
            }
        });
   });
});

PHP

function more_post_ajax(){
    $offset = $_POST["offset"];
    $ppp = $_POST["ppp"];
    //header("Content-Type: text/html");

    $args = array(
        'post_type'      => 'oportunity',
        'posts_per_page' => $ppp,
        //'offset'         => $offset
    );

    $loop = new WP_Query($args);

    if ($loop->have_posts()){
        $return = array();

        while ($loop->have_posts()) { 
            $loop->the_post(); 
            
            $return[]=array(
                'points' => get_field('points'),
                'start_date' => get_field('start_date', false, false),
                'image' => the_post_thumbnail(),
                'link' => get_permalink(get_the_ID()),
                'title' => the_title()
            );
        }
        wp_send_json($return);
    }
}

This is part of the message I receive:

readyState: 4
status: 200
statusText: "parsererror"
responseText: "[{"points":"1450","image":null,"link":"https://test.io/oportunity/headline-2/"},{"points":"1450","image":null,"link":"https://test.io/oportunity/headline-3/"},{"points":"1450","image":null,"link":"https://test.io/oportunity/headline-4/"}]"

2

Answers


  1. Chosen as BEST ANSWER

    I'll let this here, in case it's useful for anyone. I changed the json format to html.

    PHP

    function more_post_ajax(){
        $offset = $_POST["offset"];
        $ppp = $_POST["ppp"];
        header("Content-Type: text/html");
    
        $args = array(
            'post_type'      => 'oportunity',
            'posts_per_page' => $ppp,
            'offset'         => $offset
        );
    
        $loop = new WP_Query($args);
        ob_start();
    
        if ($loop->have_posts()){
    
            while ($loop->have_posts()) { 
                $loop->the_post(); 
                
                $points = get_field('points');
                $user_id = get_current_user_id();
                $balance = mycred_get_users_balance( $user_id );
                
                if( get_field('start_date', false, false) ){
                    $start_date = get_field('start_date', false, false);
                    $start_date = new DateTime($start_date);
                    $date_now = new DateTime();
                    $diff = date_diff($date_now, $start_date);  
                }
    
                
                if($points > $balance ){
                    $needpoints = true;
                }?>
                
                <div class="posts-grid">
                                <div class="post-grid-image">
                                    <?php echo the_post_thumbnail(); ?>
                                    <a class="modal-link" href="<?php echo get_permalink(get_the_ID()); ?>">
                                        <div class="img__description
                                        <?php if ($needpoints){
                                            echo "needpoints";
                                        }elseif($diff){
                                            echo "unavailable";
                                        } ?>
                                        ">
                                            <?php if ($needpoints){?>
                                                <p>You Need More Points</p>
                                            <?php }elseif( isset($start_date) ){
                                            ?>
                                                <p>Available in:</br>
                                                    <?php 
                                                    echo $diff->format("%y Year %m Month %d Day %h Hours %i Minute %s Seconds"); ?>
                                                </p>
                                            <?php }else{?>
                                                <p>View More</p>
                                            <?php }?>
    
                                        </div>
                                    </a>
                                </div>
                                <div class="post-content">
                                    <div class="post-title">
                                        <h5>Featured Point Opportunity</h5>
                                        <h5>
                                            <?php the_title(); ?>
                                        </h5>
                                    </div>
                                    <div class="post-points">
                                        <p>
                                            <?php 
                                                $current_post_id = $post->ID;
                                                echo "+" . get_field('points', $current_post_id). " pts"; 
                                            ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
            <?php  
            }
    
            $result = ob_get_contents();
              ob_end_clean();
              $return = array('content' => $result);
              wp_send_json($return);
              wp_die();
        }
    
    }
    
    add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax'); 
    add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
    

    ajax

    jQuery(document).ready(function($){
    
        var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
        var page = 1; // What page we are on.
        var ppp = 3; // Post per page
    
        $("#misha_loadmore").on("click",function(){ // When btn is pressed.
            $("#misha_loadmore").attr("disabled",true); // Disable the button, temp.
            $.ajax({
                type: 'POST',
                cache : false,
                url: ajaxUrl,
                data:{
                "action":"more_post_ajax",
                "offset": (page * ppp),
                "ppp": ppp},
                dataType: 'json',
                success: function(data){
                    page++;
                    console.log(data);
                    $(".post-grid-container").append(data.content); // CHANGE THIS!
                    $("#misha_loadmore").attr("disabled",false);
                },
                error: function(error) {
                    console.log('error:', error);
                }
            });
       });
    });
    

  2. can you try this?

    jQuery(document).ready(function($){
    
        var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
        var page = 1; // What page we are on.
        var ppp = 3; // Post per page
    
        $("#misha_loadmore").on("click",function(){ // When btn is pressed.
            $("#misha_loadmore").attr("disabled",true); // Disable the button, temp.
            $.ajax({
                type: 'POST',
                cache : false,
                url: ajaxUrl,
                contentType: 'application/json',
                data: JSON.stringify({
                  "action":"more_post_ajax",
                  "offset": (page * ppp) + 1,
                  "ppp": ppp}),
                dataType: 'json',
                success: function(data){
                    page++;
                    console.log(data);
                    //$(".post-grid-container").append(posts); // CHANGE THIS!
                    $("#misha_loadmore").attr("disabled",false);
                },
                error: function(error) {
                    console.log('error:', error);
                }
            });
       });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search