Luka Horvat Luka Horvat - 5 months ago 29
HTML Question

Dynamically create and submit a form

I have some data in my model which I want to put into a request body and send it with a POST request. The problem is I want the browser to navigate to the request URL because the route returns a new HTML page. Normally this would be done by putting the data in a form and then using JS to submit it.

How can I do this with Elm?

Answer Source

Edit - Updated based on your comment clarification

As I understand your question, you want to be able to construct a POST request behind the scenes but let the browser post it so that the browser is redirected to the actual page it is posted, leaving your Elm app behind.

You could build up the form in Elm but keep it hidden, then when you want to trigger it, pass the form ID to a port which performs the form submission.

type alias Model =
    { foo : String }

view model =
    div []
        [ Html.form
            [ id "my-form"
            , action ""
            , method "POST"
            , style [ ( "display", "none" ) ]
            [ input [ type_ "text", name "foo", value ] []
        , div []
            [ button [ onClick SubmitForm ] [ text "Submit" ] ]

type Msg
    = SubmitForm

update msg model =
    case msg of
        SubmitForm ->
            model ! [ submitForm "my-form" ]

port submitForm : String -> Cmd msg

Your javascript could look something like this (albeit with some error handling in case the id doesn't exist):

var app = Elm.Main.fullscreen()
app.ports.submitForm.subscribe(function(formId) {

Here is a working example of this on It posts the form to so you can see what has been posted by going here.

The reason I'm recommending a hidden form instead of trying to use the standard Http packages is because it sounds like you want the browser to be redirected to whatever form you are posting to. You couldn't really achieve the same thing by using the Http packages.