Created
September 19, 2022 14:57
-
-
Save icebeam7/cc012e71c22a106ae776ef1370edeb6e to your computer and use it in GitHub Desktop.
restdb collection access in Javscript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="description" content="Minimal HTML5 Document Showing How to use RestDB API and jQuery"> | |
<title>RestDB jQuery example</title> | |
<script src="https://code.jquery.com/jquery-latest.js"></script> | |
</head> | |
<body> | |
<h1>RestDB jQuery example</h1> | |
<div id="content"> | |
</div> | |
<script> | |
$(document).ready(function() { | |
/* | |
Inject the API key for every call to the database. | |
*/ | |
$.ajaxPrefilter(function( options ) { | |
if ( !options.beforeSend) { | |
options.beforeSend = function (xhr) { | |
xhr.setRequestHeader('x-apikey', 'REPLACE-WITH-YOUR-KEY'); | |
} | |
} | |
}); | |
/* | |
Create html from one record | |
*/ | |
var makeHtmlItem = function(item) { | |
var element = $('<div></div>').attr('id', item._id); | |
element.append('<hr><span>'+item['ProductName']+' '+item['UnitPrice']+'</span>'); | |
if (item['comment']){ | |
element.append('<br><q>'+item['comment']+'</q>'); | |
} | |
element.append($('<br><input type="text">')); | |
element.append($('<input type="button" value="send">').attr('id', item._id).on('click', itemClicked)); | |
return element; | |
} | |
/* | |
PUT a comment to a record and replace html element with updated record | |
*/ | |
var itemClicked = function(evt){ | |
console.log(this.id); | |
var comment = $(this).prev().val(); | |
var jsondata = {"comment": comment}; | |
$.ajax({ | |
type: "PUT", | |
url: 'https://REPLACE-WITH-YOUR-DATABASE-NAME-AND-SUFFIX.restdb.io/rest/products/'+this.id, | |
contentType: "application/json", | |
data: JSON.stringify(jsondata) | |
}).done(function(result) { | |
// replace div with a fresh record | |
$("#"+result._id).empty().append(makeHtmlItem(result)); | |
}); | |
} | |
/* | |
GET 5 records from contact Collection. | |
Sort by _id in reverse order, i.e. newest first | |
*/ | |
$.getJSON('https://REPLACE-WITH-YOUR-DATABASE-NAME-AND-SUFFIX.restdb.io/rest/products?max=5&sort=_id&dir=-1', function(data){ | |
$.each(data, function(key, item){ | |
console.log(item); | |
$('#content').append(makeHtmlItem(item)); | |
}); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment