LoginSignup
29
33

More than 5 years have passed since last update.

FormでPOST処理をしつつ画面遷移させない方法

Last updated at Posted at 2019-04-23

いろいろ調べてみて、iframeを使う方法のみ上手くいったのでメモ。
参考:Form Submit 後に画面遷移をさせない方法

formタグのtarget属性にiframeを指定。
formタグのtarget属性は送信結果をどのフレーム(ウィンドウ)に表示するのかを指定するもの。
https://www.tagindex.com/html_tag/form/form_target.html

index.html
<form method="post" id="form" action="/api/upload" target="sendPhoto">
  <input type="file" capture="camera" accept="image/*" id="file-image">
  <button class="btn-send">送信</button>
</form>

<iframe name="sendPhoto" style="width:0px;height:0px;border:0px;"></iframe>
script.js
const $form = $('#form')
$('.btn-send').on('click', evt => {
  $form.submit()
  $form[0].reset()
  return false
})

formタグのonsubmitイベントでreturn falseしたり、
submitボタンのclickイベントでreturn falseしたり、
submitボタンのclickイベントでevent.preventDefault()したり。

これらは、ページ遷移してしまったり、一見するとAjax通信が成功しているように見えるが中身が送信されていなかったりした失敗例。

29
33
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
33