6
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ajaxでよく起こるエラー!

Last updated at Posted at 2019-06-17

今回は備忘録も兼ねて、私がAjax実装するにあたってよくぶち当たった2種類のエラーについてまとめていきます!

参考程度にして頂けると幸いです:relaxed:

それではスタート!

➀404エラー

そもそも404エラーとは???

簡単にまとめると、サーバーエラーの1つで、ページが存在していないときに表示されるエラーです。

・ajaxでは、情報を送る段階で起きやすいエラーです!
 例を出しながら見ていきましょう!

posts.js
$(function() {
  function buildPost(post){
    var html = `<div class="content">
                  ${post.text}
                </div>`
    return html;
  }

  $("#new_post").on('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    var url = $(this).attr('action');
    $.ajax({
      url: '/posttt',  スペルミス
      type: "POST",
      data: formData,
      dataType: 'json',
      processData: false,
      contentData: false
    })
    .done(function(post){
      var html = buildPost(post);
      $('.contents').append(html);
      $('post_text').val('');
    })
    .fail(function(post){
      alert('エラー');
    })
  })
});

上記のコードですと、ajaxを送る送信先にスペルミスがありそうですね...

こうした上で検証ツールのコンソールログを確認して見ます!

934787d1c7761fb220e8feb1c1d08466.png

404のエラーが発生していますね:joy:

404エラーまとめ:ajaxの送信先URLの記述を確かめる!

➁500 Internal Server Error

そもそも500 Internal Server Errorとは???

簡単にまとめると、サーバー側に問題があるときに表示されるエラーです。
*ただ5xxエラーはたくさんの種類があるので内容にも種類はさまざまです。

・ajaxでは、送った側(サーバー側)で起きやすいエラーです!
 例を出しながら見ていきましょう!

create.json.jbuilder
json.text @post.texttt  スペルミス

上記のコードですと、jsonに情報を読み込むスペルミスがありそうですね...

こうした上で検証ツールのコンソールログを確認して見ます!

41c08edcd77772b800e50fdfea153625.png

500 Internal Server Errorが発生していますね:joy:

500 Internal Server Errorまとめ:コントローラやjbuilderの記述を確かめる!

ajaxで私がぶち当たったエラーは以上になります!

エラーが起こった時は、
console.log
debugger
binding.pry
と言ったデバックを利用すると解決するスピードも速くなるかと思うので、実践していってみてください!

それではご静聴ありがとうございました!

6
11
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
6
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?