I have Case objects, each connected to multiple clients, and to many Draft Invoices. I'm trying to make a script that will take a single Draft Invoice and create a Final Invoice from it for each client. Having trouble with my JS variables.
I'm trying to follow this example:
$(document).on('knack-record-create.view_141', function (event, view, record) { var Class = $('#view_141-field_71').val(); var attendance_Date = record.id;var user = Knack.getUserToken(); var headers = { "Authorization": user, "X-Knack-Application-ID": app_id, "Content-Type":"application/json"}
$.ajax({
url: ‘https://api.knackhq.com/v1/scenes/scene_1/views/view_25/records/’ + Class,
type: ‘GET’,
headers: headers,
success: function (data) {
Knack.showSpinner();
var students = data.field_28_raw;
var total = Students.length;students.forEach(function (student) { var data = { field_72: attendance_Date, field_31: Class, field_65: student.id }; $.ajax({ url: 'https://api.knackhq.com/v1/scenes/scene_72/views/view_145/records/', type: 'POST', headers: headers, data: JSON.stringify(data), success: function (response) { total-- console.log('Attendance added!!!'); redirect(total, class, attendance_date); } }) }); }
});
});
Here’s my code:
//on draft invoice edit submit, create final invoice for each client
$(document).on(‘knack-record-update.view_252’, function (event, view, record) {//get current draft invoice record ID for case lookup
var draftInvoiceID = record.id;// api url for cases
var api_url = ‘https://api.knackhq.com/v1/objects/object_1/records’;// prepare filter for cases by current draft invoice record
var filters = [
{
field: ‘field_195’,
operator: ‘contains’,
value: draftInvoiceID
}
]// add filter to URL
api_url += ‘?filters=’ + encodeURIComponent(JSON.stringify(filters));// GET case for current draft invoice record
$.ajax({
url: api_url,
type: ‘GET’,
headers: {
‘X-Knack-Application-Id’: ‘XXX’
, ‘X-Knack-REST-API-Key’: ‘XXX’
},//if successful, put case data into function to create final invoices for each client success: function(caseData) { // array of clients connected to the case var clients = caseData.records[0].field_69_raw; //log each client name clients.forEach(function (client) { console.log(client.identifier); console.log(client.id); console.log(draftInvoiceID.id); console.log(record.id); }); }
});
});
Once I step inside clients.forEach(function (client) {});, I lose access to the previous variables. The code successfully logs client.id and client.identifier, but fails for draftInvoiceID.id and record.id.
I’m stuck because I don’t see how what I’m doing is different from the sample code, with variables declared outside the ajax code and then accessed by functions within it.
Thanks for your help!