views:

34

answers:

1

Ok. I need to do something like this:

1) Make a GET ajax request and remember the HTML response in a variable. 2) Inside this first ajax request (in the callback function) I need to make a second POST ajax request and append the HTML response to the remembered HTML response from the first request. 3) Replace a div with the HTML from the variable.

This is how I'm going about it:

    var firstHtml;

    $.ajax({
        url: 'page.php',
        success: function(data) {
            firstHtml = data;
            $.ajax({
                type: 'POST',
                url: 'page2.php',
                data: 'param1=a&param2=b',
                success: function(htmlResponse){
                    // the firstHtml var is NULL here... why?
                    var finalHtml = firstHtml + htmlResponse;
                    $('#div').html(finalHtml);              
                }
            });
        }


    });

But as you can see from the comment it doesn't work. The variable firstHtml is suddenly NULL inside the second AJAX request.

+1  A: 

Try this:

$.ajax({
    url: 'page.php',
    success: function(result1) {
        $.ajax({
            type: 'POST',
            url: 'page2.php',
            context: { firstResult: result1 }, 
            data: { param1: 'a', param2: 'b' },
            success: function(secondResult) {
                var finalHtml = this.firstResult + secondResult;
                $('#div').html(finalHtml);
            }
        });
    }
});
Darin Dimitrov
It's still NULL.
Richard Knop
Seems it works: checkout [this demo](http://jsfiddle.net/KtGkr/1/)
Darin Dimitrov