Page 1 of 1

Problem with jQuery getJSON request success function

Posted: Fri Feb 04, 2011 11:16 pm
by Luke
I have a $.getJSON() request that I'm doing. I need to run some code before it does the request and then some more code after. The problem is, the code that is supposed to run before is running after. Here is the code:

Code: Select all

    $(function() {
    
        $('select#type').change(function() {
            $('#post-type-fields .dynamic').hide('slow', function() { $(this).find('div.text').remove() });
            var postType = $(this).val();
            $.getJSON('<?= $this->routeUrl('post_type_followup') ?>', {type: postType}, function(data) {
                $('#post-type-fields .dynamic').hide().prepend(data.html).show('slow');
            });
        }).ajaxStart(function() {
            $('#post-type-fields').css('background', 'transparent url("/img/icons/loading.gif") no-repeat 370px 3px');
        }).ajaxStop(function() {
            $('#post-type-fields').css('background', 'none');
        });
        
    });
The first line in the "change" event hides all fields in the .dynamic div and then removes them. I need this to happen followed by the json request, followed by the json request's success method, but it's not happening that way. The first line in the "change" event is happening after the JSON request and the new fields that the json request inserts are getting removed as well. How do I get it to execute the code in the right order? :(

Re: Problem with jQuery getJSON request success function

Posted: Fri Feb 04, 2011 11:20 pm
by Luke
Alright, well the following code seems to do the trick, but I'd still like to know what's going on. Why is it executing the code in the wrong order? I know it has to have something to do with ajax requests happening asynchronously or synchronously or something like that. To be honest, I still don't know the difference. :oops:

Code: Select all

    $(function() {
    
        $('select#type').change(function() {
            var postType = $(this).val();
            $.getJSON('<?= $this->routeUrl('post_type_followup') ?>', {type: postType}, function(data) {
                $('#post-type-fields .dynamic').hide('slow', function() {
                    $(this).find('div.text').remove();
                    $(this).prepend(data.html).show('slow');
                });
            });
        }).ajaxStart(function() {
            $('#post-type-fields').css('background', 'transparent url("/img/icons/loading.gif") no-repeat 370px 3px');
        }).ajaxStop(function() {
            $('#post-type-fields').css('background', 'none');
        });
        
    });