Send a response without redirecting

I’ve used phx.gen.html to generate the boilerplate and added resources "/route", RouteController to the router.ex. I’m trying to insert a record into the database using create in the controller using a button inside another module.

At first I just had

conn
|> put_flash(:info, "Item added")

which returns

(Plug.Conn.NotSentError) a response was neither set nor sent from the connection

So I added

conn
|> put_flash(:info, "Item added")
|> send_resp(:ok, "Success")

but this is still undesired because it redirects me to a blank page /route?id=1 URL when this function gets called. I want to insert the record without changing the current page or even refreshing. I feel like I’m missing something fundamental but the phoenix plug and controller docs have not been sufficient, for me.

<%= button "Add", to: Routes.route_path(@conn, :create, id: id) %> is the button I’m using.

Sending form data

button/2

button("hello", to: "/world")
#=> <button class="button" data-csrf="csrf_token" data-method="post" data-to="/world">hello</button>

when that button is clicked it executes this handler:

that last statement

form.submit();

is sending a POST request to the server. A request needs to have a response. In case of a form submission that response is expected to contain the page that will replace the one that submitted the form data.

This is how the HTTP protocol and therefore the web is designed to work.

Requests that don’t change the page require custom JavaScript which use the fetch API (which replaces XMLHttpRequest).

3 Likes

As part of your response you should render something.

Usually render or redirect is the last function you call in your controller.