0

I'm trying to learn JQuery and I have a web page where I've created a function named "getUserList". All this does is performs an AJAX call to the server which returns a JSON string that looks like this: {"code":"1","message":["Alan"]} So we have message which contains an array of one item, in this case.

The function looks like this:

$.fn.getUserList = function(){
  //Call the server and get the list of users currently logged in
  var list;
  $.ajax({
    type: "GET",
    url: "/ChatEngine/ChatServlet/users/list?roomId=" + roomID, 
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      if (msg.code=="1")
      {
        console.log(msg.message);
        list = msg.message;                         
      }
      else
      {
         alert("Unable to obtain user list. code: " + msg.code + " message: " + msg.message);
      } 
    },
    error: function(err) {
      alert('Get User List Error:' + err.responseText + '  Status: ' + err.status); 
    }
  });
  return list;      
}

In another function I make the call to getUserList() like so:

var list = $(document).getUserList();<br>
for(var i = 0; i < list.length; i++) { ... }<br>

But I keep getting an error saying that list is undefined. As you can see from the function that I am returning the array and according to FireBug, the console is recording the existence of the array: enter image description here

So, why is list undefined? One other question...in order to make a function call I have to keep using the syntax: $(document).somefunctionname(); Why is it I can't just write: somefunctionname(); Why do I always need to prepend the call with $(document)? If I don't, I keep getting an error saying that the function doesn't exist, which isn't true.

Please advise.

Alan

Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
Alan
  • 822
  • 1
  • 16
  • 39

1 Answers1

1

Ok, your questions:

List is undefined because as @A.Wolf and @mamdouh points out, your call is asynchronous, that means, the program doesn't wait for the AJAX call. So, if you would want your function to wait for the result, you should write async: false; this way your AJAX call will be resolved before throwing the answer. Check https://api.jquery.com/jQuery.ajax/ for more info.

About the second question, you could just write:

<script>
function hello() {
   console.log('Hello');
}

hello();
</script>

And go. The problem is that when working with jQuery you're not extending the jQuery core if you don't use $.fn.nameFunction().

Also, check this SO question for extended info, not asked for you but related: jquery - difference between $.functionName and $.fn.FunctionName

Community
  • 1
  • 1
Federico J.
  • 15,388
  • 6
  • 32
  • 51