carlosarli

carlosarli

Call the new action from a controller with javascript

Hello,
I am a complete jasvascript newbie so please bear with me.
I am using fullcalnedar.io to render a calendar in one of my views and I would like to prompt the new action from my appointment controller when I click on a date on the calendar. So i have to create a function that corresponds to the dayClick helper from the api that calls the new action in the controller and passes to it the start and end date. I know how to get the start date and the other details in javascrit I just don’t know how to make the call. should I use ajax? if so could you give me an example of how you would do it that I coul use as an example for then my other actions such as edit?
Thank you very much for your patience
Carlo

Marked As Solved

carlosarli

carlosarli

BTW I solved my issue by using HTML local storage to pass the datetime data from the calendar to the form :slight_smile: thank you all for the help!

Also Liked

peerreynders

peerreynders

Doing what exactly?

You have to understand that once the page is loaded in the browser there is no inherent “connection” between the browser page and the Phoenix controller.

It is up to you to add this functionality through FullCalendar’s event hooks.

In dayClick you could simply set something like

location.href = 'http://localhost:4000/date/2018/03/01'

to navigate to a new page (see Window.location).

If you have your routes set up something like this:

date_path  GET     /date/:year/:month/:day  HelloWeb.DateController :edit

then that request would be routed to the DateController to generate the new page which would then be loaded in the browser.

peerreynders

peerreynders

Sounds like you want something like a modal rather than a submittable form.

See Considerations for Styling a Modal (demo) to see how the HTML/CSS/JS elements interact to achieve the basic desired result with vanilla JS. Of course you are going to still have to add:

  • the input fields (and a cancel button)
  • the dayClick code to fetch the data from Phoenix with fetch (some people prefer axios)
  • the handler for the returned promise that populates and opens the modal when the response arrives.
  • The JS code to send the updated information to Phoenix when the modal is closed (but not canceled).

For improved performance you may want to consider having all the detailed information relating to any dates already on the screen inside the browser so that you can grab the information from there and only send the changes back to Phoenix while you update your local copy.

For example TodoMVC maintains an array of todo objects as a model (though in your case use of LocalStorage would be overkill) - any information in the DOM is simply a copy of information inside that client side model.

There is an example todo backend implementation with an older version of Phoenix here (demo).

In particular look at the router.ex and todo_controller.ex.

In general I wouldn’t pay any attention to the JavaScript client used here because it’s ancient. It uses Backbones.js fetch.

idi527

idi527

You can read about making requests from js using XMLHttpRequest here or fetch here.

For XMLHttpRequest it would be something like this, probably (adapted from https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest)

var xhr = new XMLHttpRequest();
var endpoint = "/api/calendar";
var payload = JSON.stringify({startDate: startDate, endDate: endDate});
xhr.open("POST", endpoint);

xhr.setRequestHeader("content-type", "application/json");

xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    console.log(xhr.responseText);
  }
}

xhr.send(payload);

And for fetch (adapted from https://stackoverflow.com/questions/29775797/fetch-post-json-data)

fetch("/api/calendar", {
  headers: {
    "accept": "application/json",
    "content-type": "application/json"
  },
  method: "POST",
  body: JSON.stringify({startDate: startDate, endDate: endDate})
})
.then(function(resp) { console.log(resp) })
.catch(function(resp) { console.log(resp) })

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

We're in Beta

About us Mission Statement