Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a single Ajax call work fine, but consecutive Ajax calls fail?

Setup:

I have a Datatable, whose each row is clickable. When a row is clicked, an ajax call is made which returns some data. Sometimes the ajax call takes a little time, depending on the amount of data being returned. It is all working fine.

Problem:

The problem occurs when the rows are clicked quickly, one after the other. In short, before the previous ajax call returns, if the row is clicked (i.e. a new ajax call is made), I get an error.

Uncaught TypeError: Property 'callback' of object [object Window] is not a function 

(The ajax call returns a JSONP data)

It looks like somehow the ajax calls are getting mingled (?), but I am not sure of this. Can anyone please tell me why does this happen?

Please let me know if any more information is required to clarify the issue.

Thanks

EDIT 1:

Here is some ajax code:

            $.ajax({
                type: "GET",
                url: 'http://' + myserver + ':8080/someurl/' + my_param,
                contentType: "application/json",
                dataType: "jsonp",
                jsonpCallback: 'callback',
                success: function(data) {
                // Inside here, I am doing some Datatables stuff.
                var myTable = $('#my_table').dataTable( {
                        "bJQueryUI" : true,
                        "bSort" : false,
                        "bFilter" : false,
                        "bPaginate": true,
                        "bProcessing": true,
                        "bScrollCollapse": true,
                        "bInfo": false,
                        "bDestroy": true,
                        "aaData": samples,
                        "sEmptyTable": "No sample listings avaiable",
                        "iDisplayLength": number,
                        "bLengthChange": false,
                        "bAutoWidth": false,
                        .
                        .
                        .
                    }

EDIT 2:

Here is the class which is assigning the callback its name. If the default callback is null, then it assigns a default value, "callback". But looks like somehow the default callback is always null and hence it always assigns "callback".

public class MappingJacksonJsonpConverter extends MappingJacksonHttpMessageConverter {

    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException,
            HttpMessageNotWritableException {

        JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
        JsonGenerator jsonGenerator = this.getObjectMapper()
                .getJsonFactory()
                .createJsonGenerator(outputMessage.getBody(), encoding);
        try {
            String jsonPadding = "callback";
            if (object instanceof JsonObject) {
                String jsonCallback = ((JsonObject) object).getJsonCallback();
                if (jsonCallback != null) {
                    jsonPadding = jsonCallback;
                }
            }
            jsonGenerator.writeRaw(jsonPadding);
            jsonGenerator.writeRaw("(");
            this.getObjectMapper().writeValue(jsonGenerator, object);
            jsonGenerator.writeRaw(")");
            jsonGenerator.flush();
        } catch (JsonProcessingException ex) {
            throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
        }
    }
}

And the above class is being referenced in mvc-servlet.xml as follows:

    <mvc:message-converters>
        <bean
            class="citygrid.feedmanager.web.converter.MappingJacksonJsonpConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/x-javascript</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
like image 900
Bhushan Avatar asked Jul 16 '12 07:07

Bhushan


People also ask

What is a jQuery Ajax fail?

The jQuery ajax fail is an ajax event which is only called if the request fails. The AJAX fail is a global event that triggered on the document to call handler function, which may be listening. The ajax fail can be performed with the help of the ajaxError () function. The jQuery ajaxError () function is a built-in function in jQuery.

How to run function on Ajax request fail in JavaScript?

We can use the fail () callback function as well on the JavaScript promise object ( the jqXHR object return by the $.ajax () function) to run the specific function on the ajax request fail. $ (document).ajaxError (function (event, xhr, options, exc)); function (event, xhr, options) – This is not an optional parameter.

Why can't I control the Order of AJAX calls?

There is a requirement to make multiple AJAX calls parallelly to fetch the required data and each successive call depends on the data fetched in its prior call. Since AJAX is asynchronous, one cannot control the order of the calls to be executed. Because of this behavior, there is an inconsistency in the data that will be bound to the UI.

What is the next step in an AJAX call?

So, once the information has been obtained at the server level, the next step in the Ajax call is to send a response back to the client, which in this case would include the data obtained from the third-party web service.


2 Answers

The problem is in how jQuery works with callback with JSONP. Here's the idea:

  1. JSONP is fired;
  2. Callback is set;
  3. JSONP returns;
  4. Callback is fired;
  5. Callback is deleted;

Now everything works fine if you don't define custom jsonpCallback (by default jQuery assigns unique callback to each JSONP request). Now what happens if you do and you fire two JSONP request at the same time?

  1. JSONP1 is fired;
  2. Callback with name callback is set.
  3. JSONP2 is fired;
  4. Callback callback is overriden by JSONP2;
  5. JSONP1 returns;
  6. Callback callback is fired for JSONP1;
  7. JSONP1 deletes callback;
  8. JSONP2 returns;
  9. JSONP2 tries to fire callback, but that is already deleted;
  10. TypeError is thrown.

Simple solution is not to override jsonpCallback option.

like image 175
freakish Avatar answered Oct 16 '22 21:10

freakish


As Alex Ball have suggested you need to put your AJAX requests in queue, so that they are executed one by one. It is very simple as shown here in a post in stackoverflow (yes it works for JSON-P also).

The second thing is error message Property 'callback' of object [object Window] is not a function is just because you dont have a global function named callback. Just define it like :

window.callback= function(responseText) {
    //alert(responseText);
};

Hope this helps.

like image 39
tusar Avatar answered Oct 16 '22 21:10

tusar