I am having some trouble implementing a callback into my JavaScript that uses AJAX. First off, the script reads from a file and places into a variable:
jQuery.get('userdata/' + username + '.txt', function(data) {
var userid = data;
});
Then that variable is being used in the following function, which reads from a .json file and picks the result that only contains the value in userid
.
function loadContacts(filter) {
var contacts = (function () {
var contacts = null;
$.ajax({
'url': 'userdata/' + username + '.json',
'dataType': "json",
'success': function (data) {
contacts = data;
contacts = contacts.filter(function(i) {
return i.id == userid;
});
}
});
return contacts;
})();
// some code for (filter) here
}
The problem here is that before jQuery has had time to create userid
and read from the file specified, the loadContacts
function is already trying to read from userid
so it comes back with an unidentified variable error.
I have spent the last 2/3 hours trying to learn how to implement a callback in AJAX, but I have had no luck after trying quite a few different variations.
I understand that by implementing a callback, essentially I am delaying the loadContacts
function to wait for a success message back from jQuery.get
, so it doesn't try looking for userid
before it has been created, I just can't seem to get it to work.
Could anyone help me?
I have already tried learning from that duplicate post but I don't get it?