queestion in jquery

Discussion in 'jQuery' started by moheballah, Oct 7, 2009.

  1. #1
    hi,

    i have this code

    
    
    $.post(home_link + '/register/', 
    			{
    				'username': $('input[name=username]').val(),
    			}, function(data){
    				alert(data);
    			}, 'json');
    
    alert('1');
    
    HTML:
    why i get alert 1 before alert data
     
    moheballah, Oct 7, 2009 IP
  2. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #2
    I'm assuming that it is because the request is 'asynchronous' which means code will continue to execute until a response is received, when a response is received your alert(data); code will be executed. I don't use jQUery so I am not sure of how you can fix this issue or if I'm correct.. just an educated guess.
    AJAX - Asynchronous Javascript And XML
     
    camjohnson95, Oct 7, 2009 IP
  3. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #3
    moving alert('1'); to directly after the alert(data); line would probably work
     
    camjohnson95, Oct 7, 2009 IP
  4. moheballah

    moheballah Member

    Messages:
    34
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #4
    i have $.post in the meddle of code
     
    moheballah, Oct 7, 2009 IP
  5. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #5
    
    ......
    function(data) {
     alert(data);
     alert('1');
    }
    ......
    
    Code (markup):
    I would say that the function is performed once the data has been loaded. try the above. You can put as much code within that function as you want, it doesn't have to be only one line.
     
    camjohnson95, Oct 7, 2009 IP
  6. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #6
    I will try to clarify this further.
    The $post part of your script is sending data to another page on your server and waiting for a response. Because it is an asynchronous request, all other code will continue executing until a response is received (all other code being your alert('1')). Once a response is received THEN your alert(data); code will be executed...
     
    camjohnson95, Oct 7, 2009 IP
  7. moheballah

    moheballah Member

    Messages:
    34
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #7
    $.post is ajax send data in json and wait the output
    i understand now what you are mean
    thanks camjohnson95
     
    moheballah, Oct 7, 2009 IP