SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Addict whydna's Avatar
    Join Date
    Jun 2006
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    JS function, wait for ajax response in order to obtain return value

    Hi guys,

    I have a javascript function that returns a value. In order to obtain this value, it has to make an ajax call, and wait for the response.

    How do I get this to work? The code I have below (mootools framework) does not work.

    Code JavaScript:
     
    function getPhoneNumber(employeeId)
    {
        var request = new Request(
            {
                 url: [url]http://requesturl.com[/url]
                 onSuccess: function(response)   
                     {
                             //??? return response;???
                     }
            }
        );
        request.send();
    }

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Since you need to wait an undetermined amount of time to get the response from the network, ajax returns processing control to the browser immediately, so the page doesn't freeze while waiting. Your getPhoneNumber() function finishes executing long before the response comes back. It will not wait, as that would hang the browser. This is why you create a callback function to be executed.

    The function you execute when the response is received needs to do something with the response. Like, for example, show the response in an alert() box. Or maybe you want to alter the DOM and display the phone number in a form field, or a div etc...

    You might want to read a few ajax tutorials.

  3. #3
    SitePoint Addict whydna's Avatar
    Join Date
    Jun 2006
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Right. What if I need to use this ajax call to get a variable. Like I am trying to do here? I need this variable to run another function.

  4. #4
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Then you call the other function, and give it the response. You can do whatever you want.
    PHP Code:
    onSuccess: function(response)   
                     {
                             
    alert(response);
                             
    FOO(response);
                     } 

  5. #5
    SitePoint Addict whydna's Avatar
    Join Date
    Jun 2006
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, I was trying to avoid that and just have a generic get function. But I guess I'll have to do it that way. Thanks!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •