Hi,
I have a template showing some data from Redis. Now, I want to create a delete button or call other action not related to redirecting\linking. How to invoke such `action (defined in the view ?) from the template?
Hi,
I have a template showing some data from Redis. Now, I want to create a delete button or call other action not related to redirecting\linking. How to invoke such `action (defined in the view ?) from the template?
do you mean a button, that is not a link to another page? Are you using LiveView or just regular view/controller?
If you are using LiveView, here in docs it is explained
If you are using regular view/controller, there you cannot handle it without page reload, but you can use <form> to send action, or you can also use javascript ajax calls, to send the request, that will do that action.
Exactly, I have a regular controller and wanted a button without a link to any page. I haven’t used LiveView so far. And yes, I achieved it by:
exposing my action in router.ex
post("/flush_db", UtilController, :flush_db)
creating a function in controller
def flush_db(conn, _) do
{:ok} = Datastore.Redis.flush_db()
json(conn, %{ok: true})
end
<script>
function flushdb() {
$.ajax({
type: "POST",
url: "/api/flush_db",
success: function () {
location.reload();
},
});
}
</script>
In template:
<form action="javascript:void(0);" id="delete-form">
<div id="submit_flushdb">
<button
type="“submit”"
onclick="flushdb()"
class="btn btn-danger"
>
Delete All
</button>
</div>
</form>