javascriptfetch-api

When using window.fetch is there a way to actually "submit()" the form?


Say I have a web page and I want it to automatically "go to" some form. This sort of thing works fine:

script(type = 'text/javascript').
    var ff = document.createElement("form")
    document.body.appendChild(ff)

    var ii = document.createElement("input")
    ii.setAttribute("type","hidden")
    ii.setAttribute("height", 69)
    ff.appendChild(ii)

    ff.method = "POST"
    ff.action = window.location + "/someform"
    ff.submit()

However, it's much easier to use fetch to send a form:

script(type = 'text/javascript').
    fetch("/someform", {
    method: "POST",
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({height: 69})
    })

However that does not actually "go to" the new page, /someform.

Is there actually a way to make fetch "go to" the form in question, rather than just fetch the results behind the scene?


Solution

  • No, there's no way to make fetch() automatically navigate. In general, we use AJAX because we don't want to reload the page with the form response; if that's what you want, use form.submit().

    You can navigate away after getting the AJAX response, but that won't generally be the same as reloading with the HTML returned by the action URL.