I'm having a problem when i use an ajax function where it is used with this:

window.setInterval(liveDrop, 2000);

This trigger my ajax call every 2 secounds and check if is there is need to update something in the site.

The function works fine, but when i put something like this on functions.php(not only this, but as example)

 echo 'TEST';

my ajax request runned in window.setInterval start to print this 'test', and this echo teste is actually outsite the function scope on 'action:my_function' in the ajax request.

My problem is that, i receiving outsite commands in my ajax calls.

Addicional information: - i'm using wp_die(), wp_send_json_success.. etc - I'm register my functions in the right hooks( they work fine if don't have a echo 'test' or anything in admin_init_hook)

Has anyone ever seen this happen?

UPDATE:

My ajax code:

function liveDrop(){
    last_drop = parseInt($('.item-drop-area').first().data('id'));

    $.ajax({
        url: ajax_request.ajax_url,
        type: 'GET',
        data: {
            'action': 'live_drop',
            'last_item': last_drop
        },
    })
    .done(function(response) {


        if( typeof response.data.has_new_live_drop != 'undefined' && response.data.has_new_live_drop === true ){
            $('.dropped-area').prepend(response.data.item_droped);
            $('.drop-item-inserted').show('slow');

            last_drop += 1;

            $('.item-drop-area').last().remove();

        }



    });
}

window.setInterval(liveDrop, 2000);

My php function:

public function __construct( ){

        add_action('wp_ajax_live_drop', array($this, 'live_drop'));
        add_action('wp_ajax_nopriv_live_drop', array($this,'live_drop'));

    }


    public function live_drop(){

        global $wpdb;

        $table_name = $wpdb->prefix . 'sorted_items';

        $next_item = intval($_GET['last_item']) + 1;

        $new_items_check = $wpdb->get_results("SELECT id,user_id, item_id, crate_id FROM $table_name WHERE id = $next_item AND TIME_TO_SEC(TIMEDIFF(current_timestamp, date)) > 15 LIMIT 1");

        if(!empty($new_items_check)){

            $html = '';

            foreach ($new_items_check as $item) { 

                $crate_img    = get_the_post_thumbnail_url( $item->crate_id , 'medium' );
                $item_img     = get_the_post_thumbnail( $item->item_id, 'live-drop', ['class' => 'item-image-livedrop'] );
                $item_name    = get_the_title( $item->item_id );
                $user_avatar  = get_user_meta( $item->user_id, 'steam_avatar', true );
                $username     = get_user_meta( $item->user_id, 'steam_personaname', true);
                $steam_id     = get_user_meta( $item->user_id, 'steam_steamid', true);
                $profile_link = home_url() . '/member/' . $steam_id;

                $html .= '<div class="item-drop-area drop-item-inserted"  data-id="' .  $item->id .  '">';
                $html .= '<div class="item-live-droped">';
                $html .= '<a class="see-user-profile" href="' .  $profile_link . '">';
                $html .= '<img class="crate-image-livedrop" src="' . $crate_img . '" />';
                $html .= $item_img;
                $html .= '<img class="user-avatar-livedrop" src="' . $user_avatar . '"/>';
                $html .= '<p class="drop-item-name">' . $item_name . '</p>';
                $html .= '<div class="item-live-dropped-hover">';
                $html .= '<p class="user-live-drop">' .   $username . '</p>';
                $html .= '</div>';
                $html .= '</a>';
                $html .= '</div>';
                $html .= '</div>';


            }


            $data = array(
                'has_new_live_drop' => true,
                'item_droped'       => $html
            );

            wp_send_json_success( $data, 200 );

        }

        wp_send_json_error( false, 200 );

    }

This code works fine, but if i have let's say a 'echo teste' on my functions.php, this code will appear on the response of this ajax request, this is the problem, every 2 secounds he don't show up just the answer of the function, he show up with information which is outsite of function like a echo statement.

  • I don't follow, can you edit your question to include the JS and the PHP code? – Tom J Nowell Mar 14 at 21:35
  • sure, will update – Victor Bini Mar 14 at 23:04

Plugins and your theme are loaded on every request, including AJAX, so any code in them is parsed. They need to be so that any AJAX hooks are found and executed.

Most of the code isn't executed though, because it's in functions that are hooked to hooks that aren't executed during an AJAX request. Some of it is though. If you're filtering pre_get_posts() in your theme or a plugin, then you probably want that filter to be run during any queries in an AJAX request. So plugins and themes need to be loaded in their entirety to do this.

But if you're running code outside a function in your theme's functions file then that's going to be executed as soon as the theme is loaded, so it will be output on the front-end and in AJAX requests. But the thing is: you shouldn't be writing code in functions.php that isn't inside a function. Just loading functions.php shouldn't cause any output.

  • Thank you jacob for the answer, but my problem is when i try to prevent users to access the wp-admin for certain user roles i hook into the 'admin_init', and so every request bug and i can't block this wp-admin access, did you know if have a list of hooks that is started in ajax requests? – Victor Bini Mar 15 at 12:50
  • 1
    is_admin is false when AJAX requests are fired, but have you considered using the superior/easier REST API? Keep in mind that if you put code in the global scope in functions.php it will always execute, it'll execute on REST, it'll execute on Admin, it'll execute on AJAX, it'll execute on frontend, this is expected behaviour. TLDR don't echo 'test'; in the global scope, run all code on actions/hooks – Tom J Nowell Mar 15 at 14:02

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.