Try to revisit the URL in javascript

109 Views Asked by At

I want to visit certain REST URI.

$.ajax({
    type: "POST",
    url: url + "result/" + ticket_id,
    success: function(data) {
        setTimeout(function(){pollResponse(url,data.id);}, 3000);
    }
});

This works. It visits the URI, and the views function does its job. So on success it moves on to the new URI.

function pollResponse(url, id)
{
    $.getJSON(url + "status/" + id, {},
        function(data) {
            if (data.report == null)
            {
                console.log(data.status_response);
                setTimeout(function(){pollResponse(url, id);}, 3000);
            }
            else
                console.alert('DONE!');
        }
    );
};

If the URI does not return report as part of the data (or being empty), then we will ask again in 3 seconds.

But after it prints the log in the console, the response stops with [200] OK. It doesn't ask the server any more.

All I did with my Python's views function is

from cornice import Service
status = Service(name='status',
                    path=root+'/status/{some_id}',
                    description=status_desc)
@status.get()
def get_status(request):
   // do something

   if (...):
      return {'report': ''}
   else:
      return {'report': 'NOT EMPTY')
2

There are 2 best solutions below

2
Ricardo Souza On BEST ANSWER

You may have a parsing issue in the result or a cross domain issue. Try changing your code to use the ajax function directly:

$.ajax({
    url: url + "status/" + id,
    dataType: 'json',
    data: {},
    success: function(data) {
        if (data.report == null)
        {
            console.log(data.status_response);
            setTimeout(function(){pollResponse(url, id);}, 3000);
        }
        else
            console.alert('DONE!');
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.error(textStatus);
        console.error(errorThrown);
        console.log(jqXHR.responseText);
    }
);

This way you can see if the response is causing an error. If there is a parsing error, you can get the data through jqXHR.responseText on the error function and see what is wrong.

The shortcut functions for AJAX in jQuery error silently on many cases. This is why i rarely use them.

2
Chris Clower On

Looks like the setTimeout in the polling function should be:

setTimeout(function(){pollResponse(url, data.id);}, 3000);

Instead of:

setTimeout(function(){pollResponse(url, id);}, 3000);