Skip to content Skip to sidebar Skip to footer

Javascript/jquery Variable Scope Issue With Nested .ajax() Calls

I'm having a difficult time passing the variable postData which is a serialized jQuery array object to a nested child .ajax() call. postData is passed successfully to the first .aj

Solution 1:

Try this:

$(".myForm").submit(function () 
    {
        var postData=$(this).serializeArray();
        $.ajax({ type        : "POST",
                 async       : false,
                 cache       : false,
                 url         : "./insertComment.php",
                 data        : postData,
                 success: (function(pData) 
                   {
                      // capture the posted data in a closurevar _postData = pData;
                      returnfunction() 
                             {                    
                               $.ajax({ type: "POST",
                                        async: false,
                                        cache: false,
                                        url: "./getComments.php",
                                        data: _postData,
                                        success: function(comments)
                                        {
                                            $(".Comments").html(comments);
                                        }
                                    });
                            }
                   })(postData)   // execute the outer function to produce the colsure
               });
      returnfalse;
    });

Solution 2:

Here's what I ended up doing:

$(".myForm").submit(function () {

    var postData = $(this).serializeArray(); // Gets all of the form elementsvar myID = $(this.ID).val(); // Takes only a single value from the form input named ID

    $.ajaxSetup({
        data        : "ID=" + myID // Sets the default data for all subsequent .ajax calls
    });

    $.ajax({
        type        : "POST",
        async       : false,
        cache       : false,
        url         : "./insertComment.php",
        data        : postData, // Overwrites the default form data for this one instance only, including all form elementssuccess: function() {
            $.ajax({
               type         : "POST",
               async        : false,
               cache        : false,
               url          : "./loadComments.php", // Notice there is no data: field here as we are using the default as defined abovesuccess: function(comments) {
                   $(".Comments").html(comments);
               }
            });
        }
    });
    returnfalse;
});

Post a Comment for "Javascript/jquery Variable Scope Issue With Nested .ajax() Calls"