You can insert and fetch data from Val Town from any web page using the Run API and some JavaScript.
Fork, or copy and paste this val into your workspace – keep it named as comments
so the snippets in this guide work correctly.
https://www.val.town/embed/vtdocs.comments
Fork, or copy and paste the below val into your workspace.
When it’s set to public, anyone can send an API request to it, and the data they send will be appended to the comments
val you created in the previous step.
https://www.val.town/embed/vtdocs.appendToComments
Get the Run API endpoint for the val you created in the step above.
The below JavaScript snippet sends data to your appendToComments
val which writes the data to your comments
val.
// change this URL to your appendToComments's Run API endpoint!
fetch("<https://api.val.town/v1/run/vtdocs.appendToComments>", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
// the single arg here maps to the `data` arg
args: ["hello world!"],
}),
}).then(r => {
// status will be 200 if everything went okay
console.log(r.status, r.statusText)
})
comments
If you make your comments
val public, anyone can read from it directly with the Run API with this JavaScript snippet.
// change this URL to your comments' Run API endpoint!
fetch("<https://api.val.town/v1/run/vtdocs.comments>")
.then(r => r.json())
.then(json => console.log(json.data));
When the Fetch API doesn’t include a method, it sends a GET request.
comments
Maybe you want to hide some of your data. You can keep comments
private and just provide access to a slice of it by using a public function val like this.