0

I'm trying to return an array of some simple information from a for each loop without success. Here is the code I'm using in two different functions.

function getUser(uname, callback) {
var u = "http://itsuite.it.brighton.ac.uk/john10/ci227/a1/whois.php?username=" + uname;
return $.get(uname, {}, callback);
}

function parseUserInfo(usrname) {
getUser(usrname, function(data) {
    var x = new Array();
    $(this).find("user").each(function() {
        x['username'] = $(this).find("username").text();
        x['firstname'] = $(this).find("firstname").text();
        x['surname'] = $(this).find("surname").text();
        return x;
    }
}
}

All I'm getting when I use it like this:

var dat = parseUserInfo("guest");

Is Undefined when using the console.log(dat) so could someone tell me where I'm going wrong here?

Many Thanks! Oh Btw I have looked at other solutions on here and elsewhere but as yet cannot find anything that works for me, so please no 'this thread is a duplicate' or 'its been answered here' links coz that will put me back to square one and make asking this question pointless!

1 Answer 1

2

x is getting returned to the getUser() function. You need to define and return x outside the getUser() in parseUserInfo().

So your code should look something like this:

function parseUserInfo(usrname) {
  var x = new Array();
  getUser(usrname, function(data) {
    $(this).find("user").each(function() {
      x['username'] = $(this).find("username").text();
      x['firstname'] = $(this).find("firstname").text();
      x['surname'] = $(this).find("surname").text();
    });
  });
  return x;
}
Sign up to request clarification or add additional context in comments.

7 Comments

Correct, if you use return false instead of return x it would just break $.each loop.
Yes but how do I do that? This is what my question was about.
Unfortunately that didn't work, in your answer none of the functions are closed off properly with the ); at the end and in each point I tried putting the return x; after it, I just got returned with parseUserInfo is undefined, could you please modify the code to how it should look? - Further to this, I closed the getUser and .each functions off myself and still got same result, aside from one but returned an empty array. Console logged: []
I've solved the syntax errors by closing the functions. Try putting a console.log(data); between the 3rd and 4th line of my code. Lets see what, if any data you're getting from the $.get() request.
Undefined and [] on separate lines are all the console is giving, this is a nightmare, I don't understand how it is so hard to return an array of the data.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.