-1

Basically I am trying to return a list of names gotten from an Ajax request. When there is only one name, it works perfectly. However with multiple names I start seeing behavior I can't explain.

function getIDFromInput(input){
    sendToID = new Array; //An Array of "Name :Id" 
    $.ajax({
        type:"GET",
        url: "user_search.php",
        contentType:"application/x-www-form-urlencoded; charset=utf-8",
        dataType:"json",
        async:false,    
        data: "q="+input,
        success:function(data){
            if(data.success){
                var userLength = data.success.length;                   
                if(userLength == 1){ // For one user everything works fine
                    var userNum = data.success.users[0];                        
                    var userName = data.success.usersNames[userNum];                        
                    sendToID[0] = userName + " :"+userNum;

                }
                else if(userLength > 1){ // Multiple users it fails

                    for(i = 0; i < userLength; i++){

                        var userNum = data.success.users[i];
                        //this call works
                        var userName = data.success.usersNames[userNum];
                        //this call fails, even though it seems to be the same call as above
                        sendToID[i] = userName + " :"+userNum;
                    }                       
                }
                else if(userLength < 1){ // never enter here
                }
            }           
        },
        error:function(data){ //After it fails it goes into here

        }
    });
    return sendToID;
}

The JSON I am passing back for < 2, ( The one that doesn't work, is below)

{"success":{"length":2,"userNames":[{"5":"Travis Baseler"},{"6":"Ravi Bhalla"}],"users":["5","6"]}}

The JSON I am passing back the one that does work is

{"success":{"length":"1","usersNames":{"6":"Ravi Bhalla"},"users":["6"]}}

Does anyone know why the first works but the second doesn't?

6
  • 4
    You should be avoiding synchronous AJAX requests when possible Commented Aug 25, 2011 at 20:05
  • 2
    @meagar: I know I'm going out on a limb here, but I'm sure there is a reason for it being synchronous. If he didn't know anything about JS/jQuery he wouldn't even know the option exists. Commented Aug 25, 2011 at 20:08
  • Once you get the data format straightened out so it's the same for all cases, you don't need the if/else at all. You can do all three branches from the for loop. The for loop handles length of 0, length of 1 and length of > 1 all automatically. Commented Aug 25, 2011 at 20:09
  • @josh Yet, here he is using synchronous AJAX calls. Commented Aug 25, 2011 at 20:09
  • 1
    @Shane Chin: AAAAAAAUGH you're killing me man :) It must have been a copy/paste job then... Commented Aug 25, 2011 at 20:39

2 Answers 2

7

in your first example, "usernames" is an array, and in the seconds one it's an object
(notice the [] in the first example which don't exist in the second one).
see @meagar's comment which explains this better than I did.

some further points:
1. you're using numbers as object property names; this (IMO) is not recommended since it's a bit confusing.
2. you can obtain the length of the array using the .length property of an array:
var userNum = data.success.users.length
3. wouldn't it make more sense to have your objects in the format of { 'userNum': X, 'username': Y }? that way you can return just one array:
success: [ {'userNum': 5, 'username': 'Travis Baseler'}, {'userNum': 6, 'username': 'Ravi Bhalla'}]

Sign up to request clarification or add additional context in comments.

3 Comments

What he means is, usernames["6"] will work when userNames is {"6" : "Ravi..."}. But when you return an array in the form [{"5":...},{"6":...}], usernames["6"] is no longer defined. You should be outputting userNames in the form {"5":"Travis...", "6":"Ravi..."}.
Thanks a ton for the input!!! With my current scheme, what would be the correct way to access the user's name? For accessing an object wouldn't I use the "."? I will be changing my output method since above is much, much cleaner, but at this point I'm confused as to what is the correct syntax for above. data.success.usersNames.userNum still fails.
with the current datatype, I think @scrappedcola has the right answer. but your main issues here are that: a. you're returning a different data structure for different cases, which is very bad (see @meagar's comment above), and b. you're returning data in a less than efficient way. If you try my suggestion, you can just do success[i].userNum or success[i].username which is much cleaner
1

Your for loop should look like this:

for(i = 0; i < userLength; i++){
 var userNum = data.success.users[i];
   //this call works
  var userName = data.success.userNames[i][userNum];//you need to index the user in the array in the object uisng the loop then user the userNum to get your userName.
  sendToID[i] = userName + " :"+userNum;
 }  

Comments

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.