0

I have an Ajax call in jQuery that returns a string of comma separated words.

Now I need to create an indexed array with the content of this string so that every word from the string has a number in the array. Later I need to use specific values from this array, e.g. the 3rd, the 4th and the 5th.

I tried the following but this returns undefined when creating the var in the end.
If I alert myArray in the success function than I still get a comma separated string so I guess I am maybe missing the indexing part ?
Can someone tell me what I am doing wrong here ?

myArray = [],
myVar = 'someText';     

$.ajax({        
    type: "post",   
    url: "ajax.php",
    cache: "false",
    data: {
        node: 'fetchStuff',
        languageFrm: languageFrm
    },
    success: function(data){
        myArray = data.split(',');
    },
    error: function(){
    }
});

myVar += myArray[2] + ' - ' + myArray[3] + ' - ' + myArray[4];
TaneMahuta
  • 367
  • 3
  • 8
  • 17
  • 1
    try to put console.log(myArray); in success. What it returns? – bksi Jun 26 '15 at 18:38
  • @bksi: Thanks - let me check. – TaneMahuta Jun 26 '15 at 18:39
  • Also you can see what data contains using firefox developer tools to examine the response – bksi Jun 26 '15 at 18:40
  • @bksi: Testing with the console it returns an array with the correct values but it is just the values, they don't have the unique numbers to refer to them (sorry, I don't know what is the correct term for them). - The result in console looks as follows: ["value1", "value2", "value3", "value4", "value5"] – TaneMahuta Jun 26 '15 at 18:41
  • 1
    see the @tylerism's answer i think this is your situation – bksi Jun 26 '15 at 18:42

1 Answers1

3

Javascript is asynchronous. Meaning it can sort of move on to the next line of code, even though the previous has not finished. You are experiencing a classic race condition. You cannot create myVar until the success of the ajax call. Try moving the myVar += myArray[2] + ' - ' + myArray[3] + ' - ' + myArray[4]; part into the success function.

tylerism
  • 659
  • 4
  • 11
  • Thanks a lot for this ! Just to check, does this match the example I provided in the comment above ? – TaneMahuta Jun 26 '15 at 18:43
  • 1
    Don't worry about the numbers, they are implicit. You should still be able to access the array with numbers. Javascript prints the array like ["value1","value2"], and you can access that array with myArr[0] to get value1 – tylerism Jun 26 '15 at 18:49
  • You were right - that was the issue. Thanks a lot - big help ! :) – TaneMahuta Jun 26 '15 at 18:52