Problem with jQuery getJSON request success function

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Problem with jQuery getJSON request success function

Post 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? :(
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Re: Problem with jQuery getJSON request success function

Post 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');
        });
        
    });
Post Reply