I’ve seen various answers to this question but I’m having trouble mapping them to my situation. What I think might be the answer on some of them, seem to be old ways of coding or unfamiliar enough to me that I cannot understand how to implement them to my situation.
I’ve got PHP generating a records.json file which my app needs to query for the logic of several methods.
function queryRecords(recordId, requiredField) {
$.ajax("javascript/records.json", {
dataType: "json",
success: callBack,
error: function (jqXhr, textStatus, errorMessage) {
alert("AJAX error: unable to retrieve records from records.jsonnn" + errorMessage);
}
});
}
function callBack(response) {
$.each(response, function(index, records) {
if (records["MediaItemID"] == recordId) {
$.each(records, function(key, value) {
if (key == requiredField) {
return value;
}
});
}
});
}
queryRecords("14", "MediaItemName");
Each time I need to query the records, I need to pass recordId and requiredField to get the value of that record’s field (as per the loops in the callBack method). However it seems I am limited with this approach because I cannot pass these values as parameters in success. If I output to the console within success, I see the value, but I need access to the value outside of success and this is how far I’ve gotten. I’ve seen so many pages about this, my head hurts. Please can you help?
2
Answers
I tested the code suggested in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function just to see if I could access the value outside of the Promise, and it failed as it has always been doing...
It returns 'please'.
Either I'm not understanding the solutions provided, or what I'm trying to achieve is not being understood. I'm happy to accept that this is a "me" problem.
The answer would've been simple if it was just a case of setting async to false in the ajax query, but that's deprecated.
The answer is: I give up, but only because it's probably unwise for multiple methods to rely on multiple ajax calls for their logic.
So instead, I'm going to import the records from the json file into an array so I'll always have access to the data without this headache.
Try like,
A sample implementation,