0

I'm doing chat app Laravel 5.7 and having a challenge with jQuery AJAX function.

I'm using PHP version 7.1.9 with 3.x version of jQuery.

Here's my form with the AJAX request:

<form action="/channels/{{$channel->id}}" method="POST">
  <input type="hidden" name="_token" value="{{ csrf_token() }}" />
  <input type="hidden" name="user_id" value="{{Auth::user()->id}}" />
  <input type="hidden" name="channel_id" value="{{$channel->id}}" />
  <input type="hidden" name="user" value="{{Auth::user()->name}}" />
  <input type="text" name="msg" class="form-control msg" />
  <input type="submit" value="Envoyer" class="btn send-msg" />
</form>
<script type="text/javascript">
  $(document).ready(function() {
    $.ajaxSetup({
      headers: {
        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
      }
    });
    $(".send-msg").click(function(e) {
      e.preventDefault();
      var user_id = $("input[name='user_id']").val();
      var channel_id = $("input[name='channel_id']").val();
      var user = $("input[name='user']").val();
      var msg = $("input[name='msg']").val();
      $.ajax({
        type: "POST",
        url: "/channels/{{$channel->id}}",
        data: {
          msg: msg,
          user: user,
          channel_id: channel_id,
          user_id: user_id
        },
        success: function(data) {
          alert(data.success);
        }
      });
    });
  });
</script>

And my PHP code:

public function sendmessage(Request $request){
  $message = new Messages();
  $message->channel_id = $request->channel_id;
  $message->user_id = $request->user_id;
  $message->username = $request->user;
  $message->message = $request->msg;
  $message->save();
  return response()->json(['success'=>'Got Simple Ajax Request.']);
}

Normally, it should post an alert with data, but actually, it redirect me to /channels/{id} with json : success: Got Simple Ajax Request

What am I doing wrong and how can I fix it?

nyedidikeke
  • 6,899
  • 7
  • 44
  • 59

2 Answers2

1

Since you only attached the event handler to the submit button, your form will still follow the default behaviour of form submission when other events such as pressing the enter key after changing the input value are fired.

To solve this, instead of attaching the event listener to the button, it's better to listen for the submit event on the form itself.

This will cover both the form submit and button click events.

$("form").on('submit', function(e){
    e.preventDefault();
    // if e.preventDefault() doesn't work, try `return false`

    // your remaining code here
});
Ana Liza Pandac
  • 4,795
  • 2
  • 24
  • 36
0

i finnally found the solution ! It was not from the ajax but the form, in fact in my form I had this:

<form action="/channels/{{$channel->id}}" method="POST">

I replace it by

<form>

And now it works perfectly ! Thanks everybody ! Love ya !