object_1 contains 2 fields, field_1 and field_2; they contain first name and last name. object_2 contains 2 fields, field_8 which is a connection to object_1 (field_1), and field_3 which contains freetext:
object_1 could contain "MICKEY" "MOUSE",
object_2 could contain "MICKEY" "is a mouse" - with MICKEY being the connecting record.
The below code retrieves all records from object_1 and object_2 using an Ajax GET. It then determines if the connecting record ID is identical to the connected record ID (if (notes.records[x].field_8_raw[0].id==names.records[y].id)) and if so displays the last name from object_1.
So the code's output would be "MICKEY" "MOUSE" "is a mouse" with MOUSE retrieved by matching the connecting record ID with the connected record ID.
The connecting record ID can be found through records[x].field_8_raw[0].id as documented elsewhere on this forum; this can then be used to find the connected record.
I used an async GET to make sure the first GET would finish before the 2nd GET would start.
cheers
Bart
// Show first name and note, and retrieve the last name from the connected record
$(document).on('knack-view-render.view_4', function (event, view, data) {
// Add a button to execute the action
$("#view_4").prepend("<button id='shownotesandnames'>Show Notes and Names</button>");
// Add the function to the button
document.getElementById('shownotesandnames').addEventListener('click', function () {
$.ajax({
url: "https://api.knackhq.com/v1/objects/object_2/records",
cache: false,
async: false,
type: "GET",
headers: {"X-Knack-Application-Id" : "YOUR APP ID HERE",
"X-Knack-REST-API-Key" : "API KEY HERE"
},
success: function(notes)
{
$.ajax({
url: "https://api.knackhq.com/v1/objects/object_1/records",
cache: false,
async: false,
type: "GET",
headers: {"X-Knack-Application-Id" : "YOUR APP ID HERE",
"X-Knack-REST-API-Key" : "API KEY HERE"
},
success: function(names)
{
document.write("<p> *** Now matching records *** </p>");
// Loop through the notes and names to see if a connectionID from notes matches a name ID.
// If so, print the first name from notes table, the surname from names table, and note from notes table.
for (var x=0; x<notes.records.length; x++) {
for (var y=0; y<names.records.length; y++)
{
if (notes.records[x].field_8_raw[0].id==names.records[y].id)
document.write("<p>" + notes.records[x].field_8 + " " + names.records[y].field_2 + " " + notes.records[x].field_3 + "</p>");
} // for y
} // for x
document.write("<p> *** DONE *** </p>");
}, // success
error: function(xhr)
{
sweetAlert("An error occured! Status: " + xhr.status + " " + xhr.statusText);
}
}); // inner ajax */
}, // outer success
error: function(xhr)
{
sweetAlert("An error occured! Status: " + xhr.status + " " + xhr.statusText);
}
}); // outer ajax
});
});