tags:

views:

75

answers:

2

Hello All,

I have a function that I'm trying to retrieve values using $.ajax and push the returned data into an array called output. Problem is the success function will not allow me to push the results into the array. see below for code.

              var getValues = function(el)
                         {
                            var value = ($(el).val());

                            if(value == '' || $(el).attr('disabled'))
                            {
                                return [];
                            }

                            var string = 'value=' + value;

                            var output = [];

                            $.ajax({
                              type: "GET",
                              url: 'shocklookup_callback.php',
                              dataType: "string",
                              data: string,
                              success: function(data) {

                                }
                            });


                            //output.push({ text : value + 'test', value : value + 'test1'} );
                            return output;

                        };

Any ideas of what I can put in the success function to be able to push the data into the output array? Also I need to be able to return the output array to the original function getValues.

If this doesn't' make a whole lot of sense please let me know and I'll try to explain better.

Thanks,

  • Dane
A: 

In your current setup the output variable will return an empty array no matter what you do because the ajax call is Asynchronous. To change this behavior add the following parameter to your .ajax():

async: false

Now your function won't go to the "return output;" statement before the ajax-call completes.

EDIT: As to how you could populate the javascript depends on how the data returned from the ajax-call loks.

Hope this helps you.

Falle1234
Thanks Falle1234!So now it's not erroring out, but it seems to be undefined. Below is the data being returned from the ajax call.{ text : 'Feroza', value : 'Feroza' },{ text : 'Four Track', value : 'Four Track' },{ text : 'Rocky', value : 'Rocky' }I then added this is the success function:success: function(data) { output.push(data); }which returns undefined.Thanks! - Dane
teamdane
The data that you are receiving looks a lot like Json to me. If it is Json data you should consider using the "json" datatype instead of "string". This will return a javascript array instead of a plain string.Then depending on whether or not you have an data in the output-array beforehand you could use: output.join(data)
Falle1234
Thanks for the help! Got it workin finally!
teamdane
A: 

AJAX is asynchronous (by default). $.ajax() will be called, but the response will not be available until some time later. During this period, your code will continue to execute.

By the time your AJAX call has received its response, your getValues function will have long since completed, and returned output (which will be an empty array). Where you are trying to do output.push(...), the AJAX response is not available yet.

The way around this is to move your code into the callback function (success), and continue execution of your code once the response is received.

What you might currently have as:

$('yourInput').click(function () {
  var output = getValues(this);

  for (var i=0;i<output.length;i++) {
    // do something
  };
});

Will be restructed as follows:

$('yourInput').click(function () {
  var output = getValues(this, function () {
    for (var i=0;i<output.length;i++) {
       // do something
     };
  });
});

With the following modifications required in getValues()

var getValues = function(el, callback)
{

if (value == '' || $(el).attr('disabled')) {
 callback([]);
} else {
  $.ajax({
    type: "GET",
    url: 'shocklookup_callback.php',
    dataType: "string",
    data: string,
    success: function(data) {
      callback([{ text : data.text + 'test', value : data.value + 'test1'}]);
    }
  });
};

Your { text : value + 'test', value : value + 'test1'} doesn't really make sense; those variables aren't defined, but you get the gist (hopefully).

EDIT:

With your AJAX response being:

{ text : 'Feroza', value : 'Feroza' }, { text : 'Four Track', value : 'Four Track' }, { text : 'Rocky', value : 'Rocky' } 

You're making it hard work for yourself. You should transform this response into valid JSON; as follows:

[{ "text" : "Feroza", "value" : "Feroza" }, { "text" : "Four Track", "value" : "Four Track" }, { "text" : "Rocky", "value" : "Rocky" }]

Note the quotes around the member name. (Whilst unquoted names are perfectly valid Javascript, it's actually invalid JSON.)

Now in the success callback, data is already an array of these values.

success: function (data) {
    callback(data);
}

Data is effectively defined as follows:

var data = [{ "text" : "Feroza", "value" : "Feroza" }, { "text" : "Four Track", "value" : "Four Track" }, { "text" : "Rocky", "value" : "Rocky" }];

and so can be operated an as follows:

var firstObject = data[0];
var firstObjectsText = data[0].text;

etc etc.

Hope this helps :)

Matt
Thanks Matt!I should have deleted the part above, the vars are defined elsewhere. What is happening is every time a combo box is changed the getValues function is called which grabs the values. On the Success function the following is returned: { text : 'Feroza', value : 'Feroza' }, { text : 'Four Track', value : 'Four Track' }, { text : 'Rocky', value : 'Rocky' }. This needs to be pushed into the output array, which is where I'm having the trouble. I've added output.push(data); to the success function but output is still coming up undefined.Thanks again, - Dane
teamdane