简体   繁体   中英

Send Messages without reload page using ajax in laravel

I am working on laravel and I want to send personally messages to the users using blade template. But when I press submit button it gets refreshed/reload the page every time. what to do? and please anyone tell me how to use ajax url, type, data

View file

<form action="{{action('MessageController@sendmessagereply')}}" method="post">         
            <div class="panel-footer">
                <div class="input-group">
                   <?php if(isset($data)){ ?>
                   <?php for($i=0;$i<count($data);$i++) {?>
                    <input type="hidden" name="_token" value="{{csrf_token()}}">
                    <input type="hidden" name="id" value="<?php echo $data[$i]->receivermsgid;?>">
                    <?php } }?>
                    <input type="text"  name="messages" class="form-control" placeholder="Enter Message" /> 
                    <span class="input-group-btn">
                       <button class="btn btn-info" type="submit">SEND</button>  
                    </span>
                </div>
            </div>
          </form>

Controller file

 public function sendmessagereply(Request $request)
      {
            $post=$request->all();
            $id=$post['id'];
            $senderid=Session::get('login_userid');
            $receiverid = $id;
            $data=array(
                        'sendermsgid' => $senderid,
                        'receivermsgid' => $receiverid,
                        'message'=>$post['messages'],
                        'sdate'=> DB::raw('CURRENT_TIMESTAMP')
                        );
            $messages = DB::table('messages')->insert($data);
            if($messages){
                \Session::flash('msg','Your Message Has Been Sent Successfully');
                return redirect('messageschat/'.$id);
            } else {
                \Session::flash('msg','Error In Sending Message');
                return redirect('basicsearch');
            } 

        }

  //i get the all messages between two users
  public function messageschat($id)
    {      
       $senderid=Session::get('login_userid');
       $result=DB::table('messages')
                  ->join('user_register','messages.sendermsgid','=','user_register.id')
                  ->leftjoin('profilephoto','messages.receivermsgid','=','profilephoto.userid','messages.sendermsgid','=','profilephoto.userid')
                  ->where('sendermsgid', $senderid)->where('receivermsgid',$receivermsgid)
                  ->orwhere('sendermsgid',$receivermsgid)->where('receivermsgid',$senderid)
                  ->select('messages.message','messages.sendermsgid','messages.receivermsgid','user_register.first_name as fname','profilephoto.name')
                  ->orderby('messages.sdate')
                  ->get();

       $chatdata=DB::table('messages')
                     ->select('messages.message','messages.receivermsgid','messages.sendermsgid')
                     ->where('receivermsgid',$receivermsgid)
                     ->where('sendermsgid',$senderid)->get();

       return view('users.messageschat')->with('data',$chatdata)->with('data1',$result);
    }

Route file

Route::any('messageschat/{id}','MessageController@messageschat');

Javascript file

<script>
$("#add").click(function() {

    $.ajax({
        type: 'post',
        url: 'messageschat/{id}',
        data: {
            '_token': $('input[name=_token]').val(),
            'messages': $('input[messages=messages]').val(),
            'id':$('input[name=_token]').val()
        },
        success: function(data) {
          alert(data)
            if ((data.errors)) {
                $('.error').removeClass('hidden');
                $('.error').text(data.errors.name);
            } else {
                $('.error').remove();
                $('#table').append("");
            }
        },
    });
    $('#name').val('');
});
    </script>

Just change the button type to avoid default form submission and use ajax

<button class="btn btn-info" type="submit" id="add">SEND</button>

to

<button class="btn btn-info" type="button" id="add">SEND</button>

Plus there's some typo in the data that you are sending

data: {
        '_token': $('input[]').val(),
        'messages': $('input[]').val(),
        'id':$('input[]').val()
}

id isn't defined in JavaScript, so the ajax url would be wrong

if #add is the submit button ID then i believe you have tto call the preventDefault() function before ajax call `

$("#add").click(function(e) {
e.preventDefault();
    $.ajax({
        type: 'post',
        url: 'messageschat/{id}',
        data: {
            '_token': $('input[name=_token]').val(),
            'messages': $('input[messages=messages]').val(),
            'id':$('input[name=_token]').val()
        },
        success: function(data) {
          alert(data)
            if ((data.errors)) {
                $('.error').removeClass('hidden');
                $('.error').text(data.errors.name);
            } else {
                $('.error').remove();
                $('#table').append("");
            }
        },
    });
    $('#name').val('');
});

plus you forgot to add id to btn

To submit a HTML form using ajax, first you need to disable the full reload submission. For that make following amendments in your code -

Use this -

<button class="btn btn-info" type="button" id="add">SEND</button>

instead of this -

<button class="btn btn-info" type="submit" id="add">SEND</button>

JavaScript-

event.preventDefault(); will disable the default full page reload based form submission and will allow you to create an ajax request delivering your payload to your MessageController@messageschat controller.

$("#add").click(function(event) {
    //Preventing the default form submission
    event.preventDefault();
    $.ajax({
    type: 'post',
    url: 'messageschat/{id}',
    data: {
        '_token': $('input[name=_token]').val(),
        'messages': $('input[messages=messages]').val(),
        'id':$('input[name=_token]').val()
    },
    success: function(data) {
        alert(data);
        if ((data.errors)) {
            $('.error').removeClass('hidden');
            $('.error').text(data.errors.name);
        } else {
            $('.error').remove();
            $('#table').append("");
        }
    },
  });
  $('#name').val('');
}

You need to make sure your form is not submitted. This can be one by using preventDefault() or returning false . Also I prefer to use submit() as callback on submitting a form.

$('form').submit(function (e) {
    e.preventDefault(); // prevent default behaviour

    ...

    return false; // return false to be sure
});

Also I should enable "preserve log" in your console to see all errors before the page refreshes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM