I have on frontend search box, I have implement autocomplete for it, and when I’m logged in, it works great for me.

But when I’m not logged in, I get 302 as result of ajax call, response headers have location in it, so it is trying to redirect, I do not know why. I notice a lot of posts around this issue, but none of the posts/questions didn’t help me.

My Code, that works when users are logged in, but doesn’t work when users are not logged in, please help.

jQuery

$.ajax({
    type: 'POST',
    url: MyAjax.ajaxurl,
    data: {
        action : 'myajax-submit',
        term : request.term,
        _ajax_nonce : MyAjax.ajax_nonce
    },
    dataType: "json",
    beforeSend: function(jqXHR, settings){
    },
    success: function(data, textStatus, jqXHR){
        response(data);
    },
    error: function(jqXHR, textStatus, errorThrown){
        response([{
            'value':'Error retriveing data',
            'id':1
        }]);
    },
    complete: function(jqXHR, textStatus){
    },
    statusCode: {                    
    }
});

php

add_action('wp_ajax_myajax-submit', 'myajax_submit');


add_action('wp_ajax_nopriv_myajax-submit', 'myajax_submit');
 
    function myajax_submit() {
        global $wpdb;
    
        //check_ajax_referer('myajax_nonce', '_ajax_nonce');
    
        if (isset($_POST["term"])) {
            $q = strtolower($_POST["term"]);

            .....
    
            $json_response = array();
    
            ...
    
            header("Cache-Control: no-cache, must-revalidate");
            header("Pragma: no-cache");
            header("Content-type: text/x-json");
            
            print json_encode($json_response);
            
            die();
        }
}

2 Answers
2

Sounds like you have an issue with another plugin or function that is trying to prevent non logged in or non admin users access to the wp-admin area so it is redirecting from wp-admin/admin-ajax.php and giving you your 302 response.

You need to find the code that is doing this and add a conditional not to redirect if the DOING_AJAX constant is defined.

Leave a Reply

Your email address will not be published. Required fields are marked *