I was looking for a way to retrieve the last record that was added to an object (here: object_1) using the API. One could of course retrieve all records and then use the last one only, but this is not efficient if there are many records ? After some experimenting I found that in Knack the last added record gets index 0 and all other records are "moved". We can use this to retrieve the last record through an Ajax GET with
url="https://api.knackhq.com/v1/objects/object_1/records?page=1&rows_per_page=1
Assuming the database is not empty, this retrieves 1 record only which is the last record added. To be sure the code checks the length of the retrieved object using switch (data.records.length).
sweetAlert is a replacement for the standard alert().
Cheers
Bart
// Retrieve the last record when clicking a button and show the result $(document).on('knack-view-render.view_4', function (event, view, data) {// Add a button to execute the action $("#view_4").prepend("<button id='showlastnameadded'>Show Last Name Added</button>"); // Add the record function to the button document.getElementById('showlastnameadded').addEventListener('click', function () { Knack.showSpinner(); $.ajax({ url: "https://api.knackhq.com/v1/objects/object_1/records?page=1&rows_per_page=1", cache: false, type: "GET", headers: {"X-Knack-Application-Id" : "APP ID HERE", "X-Knack-REST-API-Key" : "API KEY HERE" }, success: function(data) { Knack.hideSpinner(); switch (data.records.length) { case 0: sweetAlert("The database is empty !"); break; case 1: sweetAlert("Last Record : " + data.records[0].field_1 + " " + data.records[0].field_2); break; default: sweetAlert("An unknown error has occurred!"); } }, error: function(xhr){ Knack.hideSpinner(); sweetAlert("An error occured! Status: " + xhr.status + " " + xhr.statusText); } }); // ajax });
});