tadasajon

tadasajon

Why doesn't my template get rendered when I post from JavaScript?

I have a function called create(conn, params) in my controller that gets called when some data is posted to my server from a form on the client – the form was built using Phoenix templates.

All I do is extract some data from the params, do something with it, and then render another template in response.

Now I would like to write myself a little javascript helper function so that I can click something in my browser and have this data posted from JS – i.e., I just want to post the same data I would otherwise post, except without going through the form.

Everything seems to work, I can see the data arriving at my server, and the params are what I expect. But no response is ever rendered.

code inside my create(conn, params) function looks like this:

    IO.inspect("I get this far okay")
    conn
    |> put_flash(:info, "Found ID: #{the_id}")
    |> render("confirm_sheet.html", title: title, some_data: some_data)

I don’t see any error message on the server or client – it’s like my code just prints out “I get this far okay” and then vanishes into thin air.

But then if I go post the data from my form, I see the response in the confirm_sheet.html template as expected.

The only difference I can think of is that I am posting JSON instead of some other format. Here is the JS function that I am using to try to call my route:

<script>
    window.quick_post = function(gsheet_id) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://localhost:4000/sheets", true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
        var to_send = JSON.stringify({
            "_csrf_token": "<%= Phoenix.Controller.get_csrf_token() %>",
            "sheet": {"the_id": the_id}
        });
        xhr.send(to_send);
    }
</script>

So what is happening here? How can a route give no error / warning and also no response?

Marked As Solved

Nicd

Nicd

Looking at your JS client code, what do you expect it to do? Seems to me that you told your client to send a request to the backend and then do nothing with the response. The response will not be automatically inserted or replaced into the DOM, you need to write the code to do that.

Keep your browser’s developer tool’s network console open while sending the request. You should see what the server responded. But if nothing is done with the response, then it will indeed “vanish into thin air”.

Now, if you want to replicate the behaviour of a browser’s form – i.e. once you have submitted something, you are taken to a new page that completely replaces the old one – without using a form, you need to actually create a hidden form on the page and submit it in JS. Then it will act like a normal form was submitted. You can accomplish sort of the same thing with XMLHttpRequest by using the response HTML to replace the entire page HTML and updating the URL, but it’s not entirely the same thing.

Also Liked

Nicd

Nicd

The browser does not do anything by default for requests sent from JavaScript, i.e. XMLHttpRequest or Fetch API. That’s entirely manual for you to implement. The easiest way to simulate a normal form post is indeed to make an invisible form (with <input type="hidden"> elements), fill it with values, and submit it.

Where Next?

Popular in Questions Top

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
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
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
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
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
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

We're in Beta

About us Mission Statement