tresstylez
tresstylez

Reputation: 1839

Why is AJAX/JSON response undefined when used in Bootstrap typeahead function?

I created a function that makes a jquery AJAX call that returns a JSON string. On its own, it works fine -- and I can see the JSON string output when I output the string to the console (console.log).

function getJSONCustomers()
{
var response =  $.ajax({
    type: "GET",
    url: "getCustomers.php",
    dataType: "json",
    async: false,
    cache: false
  }).responseText;
  return response;  
};

However, when I set a variable to contain the output of that function call:

var mydata = getJSONCustomers();

, then try to use it within my Twitter-Bootstrap TypeAhead function (autocomplete for forms):

data = mydata;
console.log(data);

I get an 'undefined' error in my console.

Below is a snippet of this code:

$(document).ready(function() {

var mydata = getJSONCustomers();

$('#Customer').typeahead({
    source: function (query, process) {
        customers = [];
        map = {};

        data = mydata;
        console.log(data);

 // multiple .typeahead functions follow......
});

Interesting here, is that if I set the data variable to be the hardcoded JSON string returned from the AJAX function, everything works fine:

data = [{"CustNameShort": "CUS1", "CustNameLong": "Customer One"}]

How can I use the JSON string within my typeahead function?

Upvotes: 3

Views: 23949

Answers (2)

Felix Kling
Felix Kling

Reputation: 816482

.responseText returns a string. You have to parse the string first to be able to work with the array:

var mydata = JSON.parse(getJSONCustomers());

That being said, you should avoid making synchronous calls. Have a look at How do I return the response from an asynchronous call? to get an idea about how to work with callbacks/promises.

Upvotes: 8

Dzulqarnain Nasir
Dzulqarnain Nasir

Reputation: 2300

The problem is that the Ajax request hasn't had the chance to complete before typeahead is initialised, so typeahead is initialised with an uninitialised mydata variable. Also, as of jQuery 1.8+ async: false has been deprecated and you need to use the complete/success/error callbacks.

Try this:

function getJSONCustomers(callback) {
    $.ajax({
        type: "GET",
        url: "getCustomers.php",
        dataType: "json",
        cache: false,
        success: callback
    });
};

And then you could do something like:

getJSONCustomers(function(mydata) {
    // mydata contains data retrieved by the getJSONCustomers code
    $('#Customer').typeahead({
        source: function (query, process) {
            customers = [];
            map = {};
            console.log(mydata);

 // multiple .typeahead functions follow......
    });
});

So your code completes the Ajax call before initialising the typeahead plugin.

Upvotes: 0

Related Questions