Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you make an AJAX call inside of another AJAX call in jquery?

Tags:

jquery

ajax

Below is a jquery script I am working on, I have stripped down all the non-relevant parts of it.

You can see there is an ajax call, from the results there is an if statement, the other items our stripped out but anyways the captcha one is picked from the result of the first ajax call.

I then need to make a second ajax call, this is where my trouble is, I get no errors but it doesn't seem to return a response on the second one, am I missing something?

<script type="text/javascript">
    $(document).ready(function() {
        // make ajax call
        var dataString = 'comment=' + comment;
        $.ajax({
            type: "POST",
            url: "process.php",
            data: dataString,
            dataType: "json",
            success: function(data) {
                //result from 1st ajax call returns "captcha"
                if (data.response === 'captcha') {
                    //a bunch of code is ran
                    ////////////////////////
                    //then...
                    $().bind('cbox_closed', function() {
                        var dataString2 = 'comment=' + comment + '&run=captchagood';

                        // our nested ajax call
                        // this is the part that is having trouble =(
                        $.ajax({
                            type: "POST",
                            url: "process.php",
                            data2: dataString2,
                            dataType: "json",
                            success: function(data2) {
                                if (data2.response === 'captchagood') {
                                    alert('test');
                                    $('div#loader').find('img.load-gif').remove();
                                    $('div#loader').append('<span class="success">Thanks for your comment!</span>');
                                    $('div#loader').hide().fadeIn('slow');
                                    $('span.limit').remove();
                                    $('div#comments').append(data);
                                    $('div#comments div.comment-unapproved:nth-child(1)').hide().slideDown('slow');
                                    $('input#submit-comment').unbind('click').click(function() {
                                        return false;
                                    });
                                    // success append the sanitized-comment to the page
                                    $('#comments').prepend(data.comment);
                                };
                                // end captcha status returned
                            }
                        });
                    });
                };
                return false;
            });
        });
    });
</script>
like image 827
JasonDavis Avatar asked Aug 12 '09 06:08

JasonDavis


People also ask

Can we execute run multiple AJAX requests simultaneously in jQuery?

To iterate through the response, there is a callback function attached to it. This callback function gets executed once both the Ajax requests are finished. In case where multiple Deferred objects are passed to $. when() , it takes the response returned by both calls, and constructs a new promise object.

What happens when one AJAX call is still running and you send an another AJAX call before the data of first AJAX call comes back?

Since Ajax calls are asynchronous, the application will not 'pause' until an ajax call is complete, and simply start the next call immediately. JQuery offers a handler that is called when the call is successful, and another one if an error occurs during the call.

Can jQuery and AJAX be used together?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

What is AJAX synchronous call?

Synchronous AJAX call is made when async setting of jQuery AJAX function is set to false while Asynchronous AJAX call is made when async setting of jQuery AJAX function is set to true. Default value of the async setting of jQuery AJAX function is true.


Video Answer


2 Answers

There's nothing wrong with having an ajax call inside an ajax callback. In fact, you're not even doing that, what you're doing here is:

  1. Ajax call
  2. If call is successful and returns 'captcha' then bind a function to the cbox_closed event
  3. When the cbox_closed event is triggered call the bound function which contains another ajax call

Some things to check for:
Is the sever returning successfully? (no 404, 500 error etc)
You're anticipating a json response. Does it contain data like {response:'captcha} that you're checking for?
When is the cbox_closed event triggered? Are you sure that it is happening?

like image 132
jammus Avatar answered Sep 23 '22 19:09

jammus


You've passed the 'success' callback to jQuery, but no 'error' callback. This way you're ignoring the error. Here is an example to capture the error, and optionally display it in the Firebug console.

var lastRequest = jQuery.ajax( { type:     "POST"
                               , url:      this._ajaxUrl
                               , data:     postdata
                               , dataType: "json"
                               , success:  _gotAjaxResponse
                               , error:    _gotAjaxError
                               } );

function _gotAjaxResponse( data )
{
  window.console && console.log( data );
}

function _gotAjaxError(xhr, status, error)
{
  // Show server script errors in the console.
  if( xhr.status == 500 )
  {
    var response = xhr.responseText;
    response = response.replace( /\r?\n/g, "" )
                       .replace( /(<\/)/g, "\n$1" )
                       .replace( /<[^>]+>/g, "" )
                       .replace( /^\s+/, "" )
                       .replace( /\s+$/, "" );
    window.console && console.error(response);
  }

  alert("I'm sorry...\n\n"
      + "Unfortunately an error occured while communicating with the server.\n"
      + "Please try again later.");
}
like image 42
vdboor Avatar answered Sep 21 '22 19:09

vdboor