0

This question already has an answer here:

On this site, it usually takes around 5-7 seconds for admin-ajax.php to process and return the response for when the user clicks on the plus icon on project hover. I'm not sure if this is a WordPress issue or a coding issue. I've given one example of how I'm calling ajax on the site below. Can someone take a look and let me know if I'm even calling ajax correctly? I read that admin-ajax.php should be used for all Ajax requests on WordPress. Is there anything else I can do to speed up admin-ajax.php?

Here is the code I'm using for when the user hovers over one of the projects (squares) and clicks on the plus icon.

    (function($) {

        // Function to allow an event to fire after all images are loaded
        $.fn.imagesLoaded = function () {

            $imgs = this.find('img[src!=""]');
            // if there's no images, just return an already resolved promise
            if (!$imgs.length) {return $.Deferred.resolve().promise();}

            // for each image, add a deferred object to the array which resolves when the image is loaded
            var dfds = [];
            $imgs.each(function(){

                var dfd = $.Deferred();
                dfds.push(dfd);
                var img = new Image();
                img.onload = function(){dfd.resolve();}
                img.src = this.src;

            });

            // return a master promise object which will resolve when all the deferred objects have resolved
            // IE - when all the images are loaded
            return $.when.apply($,dfds);

        }

        // Function for additional styling
        function projectStyles() {

            // Check the first slide input
            $('#slider input:first').attr('checked', 'checked');

            $('#project-wrapper').addClass('activated');

            // Make the articles grey again after activation
            $('article.project').addClass('grayscale grayscale-fade').css('opacity', '0.4');

            // CSS effects
            $('.post-container').addClass('fadeInUp');
            $('.close-button').addClass('fadeInDown');

            // Remove pesky, sticky 'hover' class
            $('article.project').removeClass('hover');
        }

        // Open the project container
        function openProject() {

            var post_id = $(this).data('id'), // data-id attribute for .post-link
                ajaxURL = site.ajaxurl; // Ajax URL localized from functions.php

            // Add a loading icon
            $('<span class="loading-icon"></span>').insertBefore(this);

            // Add the 'active' class to make sure the div stays dark while loading
            $(this).closest('article.project').addClass('active');

            // Make all the articles grey when an article is clicked
            $('article.project').addClass('grayscale grayscale-fade').css('opacity', '0.4');

            // Remove the corner ribbon
            $('article').removeClass('current');
            $('.corner-ribbon').remove();

            // Get the response from the Ajax function
            $.ajax({
                type: 'POST',
                url: ajaxURL,
                context: this,
                data: {'action': 'load-content', post_id: post_id },
                success: function(response) {

                    // Add a corner ribbon to note the current activated project
                    $(this).closest('article.project').removeClass('active').addClass('current');
                    $('<div class="corner-ribbon">Current</div>').prependTo('article.current');

                    // Wait until all images are loaded
                    $('#project-container').html(response).imagesLoaded().then(function() {

                        // Remove the loading icon
                        $('.loading-icon').remove();

                        // If the user has scrolled...
                        if ($(window).scrollTop() != 0) {

                            // First scroll the page to the top
                            $('html, body').animate({
                                scrollTop : 0
                            },400, function() {

                                // Make the max-height of the container exact for a smoother transition
                                function matchContainerHeight() {
                                    var containerHeight = $('#project-container').outerHeight();
                                    $('#project-wrapper.activated').css('max-height', containerHeight);
                                }
                                setTimeout(matchContainerHeight, 100);
                                $(window).on('resize', matchContainerHeight);

                                projectStyles();

                            });

                        // If the user has not scrolled...
                        } else {

                            // Make the max-height of the container exact for a smoother transition
                            function matchContainerHeight() {
                                var containerHeight = $('#project-container').outerHeight();
                                $('#project-wrapper.activated').css('max-height', containerHeight);
                            }
                            setTimeout(matchContainerHeight, 100);
                            $(window).on('resize', matchContainerHeight);

                            projectStyles();

                        }

                        return false;
                    });
                }
            });
        }

        // User event
        $('#content').on('click', '.post-link', function(e) {
            e.preventDefault();

            var projectTitle = $(this).data('title'), // data-title attribute for .post-link
                projectSlug = $(this).data('slug'), // data-slug attribute for .post-link

            // Calls openProject() in context of 'this' (.post-link)
            openProject.call(this);

            $('head').find('title').text(projectTitle + ' | Keebs');
        });

    })(jQuery);

Ajax PHP

// Return the post content to the AJAX call
function my_load_ajax_content () {

    $args = array(
        'p' => $_POST['post_id'],
        'post_type' => 'projects'
        );

    $post_query = new WP_Query( $args );
    while( $post_query->have_posts() ) : $post_query->the_post(); ?>

    <div class="post-container">
        <div id="project-left-content">
            <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
            <?php the_content(); ?>

            <?php if( get_field('client') ): ?>
                <div class="client">
                    Client(s): <?php the_field('client'); ?>
                </div>
            <?php endif; ?>

            <?php if( get_field('client') ): ?>
                <div class="project-cats">
                    <?php
                        $cat_names = wp_list_pluck( get_the_category(), 'cat_name');
                        echo join( ', ', $cat_names );
                    ?>
                </div>
             <?php endif; ?>

            <?php if( get_field('url') ): ?>
                <div class="project-link">
                    <a class="first after" href="http://<?php the_field('url'); ?>" target="_blank"><?php the_field('url'); ?></a>
                </div>
            <?php endif; ?>
        </div>
        <div id="project-right-content">

            <?php if( have_rows('slides') ): ?>

                <div id="slider">

                    <!-- Slider Setup -->
                    <?php if( have_rows('slides') ):
                        $slideNumber = 0;
                        while ( have_rows('slides') ) : the_row();
                        $slideNumber++;
                    ?>

                        <input type="radio" name="slider" id="slide<?php echo $slideNumber; ?>">

                    <?php endwhile;endif; ?>

                    <!-- Slide -->
                    <?php if( have_rows('slides') ): ?>
                        <div id="slides">
                            <div id="overflow">
                                <div class="inner">

                                    <?php if( have_rows('slides') ):
                                    while ( have_rows('slides') ) : the_row();

                                        $slideImage = get_sub_field('slide_image');
                                    ?>

                                    <article>
                                        <img src="<?php echo $slideImage; ?>" alt="<?php the_title(); ?>">
                                    </article>

                                    <?php endwhile;endif; ?>

                                </div><!-- #inner -->
                            </div><!-- #overflow -->
                        </div><!-- #slides -->

                    <?php endif; ?>

                    <!-- Controls -->
                    <?php if( have_rows('slides') ):
                        $slideNumber = 0;
                    ?>
                        <div id="active">

                            <?php while ( have_rows('slides') ) : the_row();
                                $slideNumber++;
                            ?>
                                <label for="slide<?php echo $slideNumber; ?>"></label>
                            <?php endwhile; ?>

                        </div><!-- #active -->
                    <?php endif; ?>
                </div><!-- #slider -->
            <?php endif; ?>
        </div><!-- #project-right-content -->
    </div><!-- .post-container -->

    <?php
    endwhile;
    wp_die();
}

add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' ); // when the user is logged in
add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' ); // when the user is not logged in

marked as duplicate by Nicolai, Pieter Goosen, TheDeadMedic, cybmeta, Robert hue Mar 9 '15 at 8:44

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • admin-ajax.php isn't a javascript file, please post the associated PHP code ( have you considered the WP API rest api? ) – Tom J Nowell Mar 5 '15 at 13:40
  • @Tom I added the PHP. I haven't used WP Rest API before but I'll take a look. – Desi Mar 5 '15 at 13:45
  • The specific WP stuff is a WP_Query for one post. I don't think it can be so slow; have you tried to test without ACF functions (I assume get_field, have_rows, etc, are from ACF)? – cybmeta Mar 6 '15 at 7:25
  • @cybmeta Yeah, that's what has me so confused. I haven't tried it without ACF but I'm not sure why that would make any difference. I thought maybe there was a way to cache admin-ajax.php but couldn't find a way. – Desi Mar 6 '15 at 10:50
  • Test without ACF functions can make difference. Tell us the results of the test without them. – cybmeta Mar 6 '15 at 15:35

Browse other questions tagged or ask your own question.