'Using AJAX to test for readiness of data through polling

I have a Django application and am attempting to utilize Ajax and Redis to poll for the completion of a long calculation. The difficulty I am having is that my Ajax is "recalling itself" after the timeout period.

My intended action is for Ajax to test for the completion of a process (indicated by a Redis channel). The difficulty I am having is that the Ajax is called once upon page load, again upon page click (which is intended), but does not "re-poll" at the regular 3 second intervals to test my retrieval view for my result.

Here is the view.py:

@login_required()
def retrieveAsync(request):
    if is_ajax(request=request) and request.method == "GET":
        show_df = request.session['win_deep_show_df']
        df = []
        msg = ['you have called retrieveAsync']
        if show_df == False:
            ret_val = {
                'do_what': 'nothing',
                'msg': msg,
                'df': df,
            }
            # user has not requested the dataframe info yet...do nothing
            return JsonResponse(ret_val, status=200)
        elif show_df == True:
            redisChannel = request.session['win_deep_redis_channel']
            data_ready = (REDIS_INSTANCE.get(redisChannel + 'reco_data_ready').decode('utf-8') == 'yes')
            if data_ready is False:
                msg = "Loading data..."
                ret_val = {
                    'do_what': 'wait',
                    'msg': msg,
                    'df': df,
                }
                return JsonResponse(ret_val, status=200)
            elif data_ready is True:
                ret_dict = pickle.loads(REDIS_INSTANCE.get(redisChannel + 'ret_dict'))
                msg = "Your data is ready now..."
                ret_val = {
                    'do_what': 'complete',
                    'msg': msg,
                    'df': df,
                }
                return JsonResponse(ret_val, status=200)
    return JsonResponse({}, status=400)

Here is the html containing ajax:

       {% block javascript %}
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $.ajax({
            url: '/clashstats/win_deep/get_ajax/',
            type: 'get',
            headers: { "X-CSRFToken": csrftoken },
            success: function(ret_val) {
                if (ret_val.do_what == 'nothing') {
                    $("#message_loading_space").html(ret_val.df);
                } else {
                if (ret_val.do_what == 'wait') {
                    if (cnt < 6) {
                        $("#message_loading_space").html(ret_val.msg);
                        cnt++;
                        setTimeout(function() { ajax_request(); }, 3000); // wait 3 seconds than call ajax request again
                    }
                } else {
                if (ret_val.do_what == 'complete') {
                    $("#message_loading_space").html(ret_val.msg);
                }
                }
                }
            },
            })
            });

            function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
            }
            return cookieValue;
            }
            var csrftoken = getCookie('csrftoken');
        </script>
        {% endblock javascript %}

I can see the two ajax calls in the log (first on initial page load, second on click), and my redis logic test is functioning correctly. So it appears to be my ajax script (for which I am admittedly a novice). Any suggestions you can provide are very much appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source