Code to retrieve only the last record from an object

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


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().



// 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 () {
 		url: 		"",
      	cache:		false,
	    type: 		"GET",
	    headers: 	{"X-Knack-Application-Id"	: "APP ID HERE", 
                  	"X-Knack-REST-API-Key"		: "API KEY HERE"
		success: 	function(data) 
          	switch (data.records.length)
              case 0: 	sweetAlert("The database is empty !");
              case 1:   sweetAlert("Last Record : " + data.records[0].field_1 + " " + data.records[0].field_2); 
              default:	sweetAlert("An unknown error has occurred!");

      	error: 		function(xhr){
          	sweetAlert("An error occured! Status: " + xhr.status + " " + xhr.statusText);
	  }); // ajax