Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent jQuery AJAX call from waiting for previous call to complete

I've searched SO, and every question seems to be asking how to wait for an AJAX call to complete. I am asking how not to wait for an AJAX call to complete.

I have an e-commerce site that does some heavy image manipulation via PHP. The manipulation is triggered via AJAX calls.

I am trying to speed up the user experience, so I have modified the code to first have PHP render a thumbnail (the operation completes quickly), then trigger a second AJAX call that tells PHP to render the full image (which can take a few minutes).

The "Add To Cart" operation is also an AJAX call. The problem is that the "Add to Cart" call is unable to complete until the previous AJAX call is completed.

Sequence:

  1. AJAX call A requests thumbnail be generated.
  2. The success callback for call A:
    a. Displays / enables the "Add to Cart button"
    b. Triggers AJAX call B, for the full image to be generated.
  3. Clicking "Add to Cart" triggers AJAX call C, which does not complete until call B completes.

Relevant javascript:

/** Call A - make call for thumbnail generation **/
$.ajax({
    url: 'index.php?route=decorable/image/thumbnail',
    type: 'post',
    data: image_data,
    dataType: 'json',
    success: function(json) {
        if (json['success']) {
            $('#button-cart').show();
            /** Call B - make call for *full* layout generation **/
            $.ajax({
                url: 'index.php?route=decorable/image',
                type: 'post',
                data: image_data,
                dataType: 'json'
             });
    });

/** Call C - this AJAX call starts, but does not complete, until call B completes **/
$('#button-cart').click(function() {
    $.ajax({
        url: 'index.php?route=checkout/cart/add',
        type: 'post',
        data: cart_data,
        dataType: 'json',
        success: function(json) { 
            if (json['success']) {      
                $('.success').fadeIn('slow');
            }
        }
    });
});

Am I misunderstanding, or should call C be able to complete even if call B is not complete?

If you believe that the PHP is holding up the experience, then is there a good way for to me to trigger PHP to begin executing, but still send the response back for the thumbnail AJAX call?

like image 370
random_user_name Avatar asked Apr 15 '14 14:04

random_user_name


1 Answers

In my experience this was caused by PHP sessions been used, when you're sure in the code (all ajax requests) that you will not have to modify sessions then you should call:

session_write_close()

This will then allow other requests to be made simultaneously.

Further reading: http://www.php.net/manual/en/function.session-write-close.php

like image 53
Jono20201 Avatar answered Nov 14 '22 23:11

Jono20201