0

My ajax request return 0 with my function dont echo anything, with it echo that admin-ajax.php on the console Network, display what i wont, but in my php, dont return anything:

avatar-creator.php:

function ajaxcontact_enqueuescripts(){
    $title_nonce = wp_create_nonce( 'element_id' );

    wp_enqueue_script('ajax-script',  plugin_dir_url( __FILE__) . 'includes/js/avatarlist.js', array('jquery'), null, true);

    wp_localize_script( 'ajax-script', 'frontend_ajax_object', array(
    'ajax_url' => admin_url( 'admin-ajax.php' ),
    'nonce'    => $title_nonce, // It is common practice to comma after
) ); 
}
add_action('wp_enqueue_scripts', 'ajaxcontact_enqueuescripts');

avatar-creator-shortcode.php

<?php


function display_post($atts){
        if( ! isset( $atts['category_id'] ) ){
        return 'Missing category';
    }else{

        $current_url=plugin_dir_url( __FILE__ );

        $atts = shortcode_atts( array(
            'title' => 'Avatar Creator Assets List',
            'category_id' =>'',
            'posts_per_page'=> 20,
        ), $atts);

        $paged = get_query_var('paged') ? get_query_var('paged') : 1;

        $args = array(
            'cat' => $atts['category_id'],
            'post_type' => 'avatar_creator',
            'posts_per_page' => $atts['posts_per_page'],
            'paged' => $paged,
            );


            $the_query = new WP_Query( $args );

            if ( $the_query->have_posts() ) : 

                $display ='<div id="hair" class="assets_list">';
                $display.='<div class="inside_div">';

                while ( $the_query->have_posts() ) : $the_query->the_post();

                    /*Variables*/
                    $id=get_the_ID();
                    $premium_date = get_post_meta( $id, 'premium_date', true );
                    $excerpt = get_the_excerpt();
                    $title= get_the_title();
                    $thumbnail = get_the_post_thumbnail();

                    $datetime1 = new DateTime($premium_date);
                    $datetime2 = new DateTime(now);
                    $interval = $datetime2->diff($datetime1);


                    /* Display code*/
                    $display.='<div id="'.$id.'" class="img_display" title="'. $excerpt .'">';


                    /*PRemium Date*/

                    if(! $premium_date == null){

                        if( $datetime2 < $datetime1 && $interval->format('%a')<>'0' ){

                                $display.='<div class="destaque_count"><span>'. $interval->format('%R%a days') .'</span></div>';    

                            } 
                        if ($datetime2 < $datetime1 && $interval->format('%a')=='0') {

                                $timeminutes1 = $datetime1->format('H:i:s');
                                $timeminutes2 = $datetime2->format('H:i:s');

                                $expire  = strtotime($timeminutes1) - strtotime($timeminutes2);

                                $timeleft=date('H:i:s',$expire);

                                $display.='<div class="destaque_count"><span>'. $timeleft .'</span></div>';
                        }
                    }

                    /* */


                    $display.= $thumbnail;
                    $display.='</div>';

                endwhile;
                $display.='</div></div>';       

                else:
                    $display='<h2>Sorry... </h2>';
                    $display.="<p style='font-size: 23px;font-stretch: semi-expanded;'>Don't found any post with this category id:  ";
                    $display.='<span style="color: red;">'.$atts['category_id'].'</span>';
                    $display.=' please check again!</p>';

                endif;
                wp_reset_postdata();

                if ( $the_query->max_num_pages > 1 && is_page() ){

                    $range = 4;
                    $pages=$the_query->max_num_pages;

                    $showitems = ($range * 2)+1;  

                    global $paged;

                    if(empty($paged)) $paged = 1;

                    if($pages == '')
                     {
                         global $wp_query;
                         $pages = $wp_query->max_num_pages;
                         if(!$pages)
                         {
                             $pages = 1;
                         }
                     }   

                     if(1 != $pages)
                     {
                         $display .= "<div class='pagination'>";
                         if($paged > 2 && $paged > $range+1 && $showitems < $pages) $display.= "<a href='".get_pagenum_link(1)."'>&laquo; First</a>";
                         if($paged > 1 && $showitems < $pages) $display.= "<a href='".get_pagenum_link($paged - 1)."'>&lsaquo; Previous</a>";
                         $display.='<div class="pages_number">';
                         for ($i=1; $i <= $pages; $i++)
                         {
                             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
                             {

                                $display.= ($paged == $i)? "<span class='selected_page pages_num'>".$i."</span>":"<a href='".get_pagenum_link($i)."' class='pages_num'>".$i."</a>";

                             }
                         }
                         $display.='</div><span class="counter_pages">Page '.$paged.' of '.$pages.'</span>';
                         if ($paged < $pages && $showitems < $pages) $display.= "<a href=".get_pagenum_link($paged + 1).">Next &rsaquo;</a>";  
                         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) $display.= "<a href='".get_pagenum_link($pages)."'>Last &raquo;</a>";
                         $display.= "</div>";
                     }

                } 



                return $display;
    }
}




add_action( 'wp_ajax_my_ajax_request', 'get_ajax');
add_action("wp_ajax_nopriv_my_ajax_request", "my_must_login");
function get_ajax(){

    $ajax_request = $_POST["element_id"];


}


function my_must_login() {
    echo "You must log in to vote";
    die();
}






function dwwp_list_shortcode( $atts, $content = null ){
    ob_start();
    $output = display_post($atts);


    // if( ! empty($ajax_request) ){
        // 
        // var_dump($ajax_request);
    // 
    // }

    return $output;
}
add_shortcode('list_avatar_creator', 'dwwp_list_shortcode' );

avatarlist.js

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

    $(".img_display").click(function(){
        $(".img_display").not(this).removeClass("active-element");
        $(this).toggleClass("active-element");
        element_id = $(this).attr("id");        
         $.ajax({
            url: frontend_ajax_object.ajax_url,
            type: 'POST',
            dataType: 'json',
            data: {
                _ajax_nonce: frontend_ajax_object.nonce,
                action : 'my_ajax_request',
                element_id: element_id

            },success: function ( response){
                $('#test').html(element_id);
            }
        });
    });

});

My code is running in frontend.

  • 2
    the function get_ajax does nothing. you have to add a output to return and a exit to not display the default response 0. – mmm Apr 28 '17 at 11:50
  • 1
    have you considered a REST API endpoint instead? It's much easier to implement and use – Tom J Nowell Apr 28 '17 at 12:39
  • But when i echo the function get_ajax, the values goes to admin-ajax.php and I can't get. – Filipe Fernandes Apr 28 '17 at 14:55
  • @FilipeFernandes What do you mean by 'goes to admin-ajax.php'? If you mean the value is printed on 'admin-ajax.php', then that's the way this feature works. – Jack Johansson Apr 28 '17 at 16:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.