0

First of all Hello , i have a kinda of problem that i cannot manage . am posting an ajax request like the following

  <script>



    $(document).ready(function(){


        $(document).on('keydown' , '.message_input', function(e){



            var token = $('input[name=_token]').val(); 
            var msg  = $(this).val(); 
            var element = $(this) ; 
            var ul = element.parent().parent().find('ul'); 
            var authenticated_user_id = $(this).attr('data-auth-id'); 
            var user_id = $(this).attr('data-to-user-id'); 
            var conversation_id = $(this).attr('data-conversation-id'); 

            if(!msg == '' && e.keyCode == 13  && !e.shiftKey){


                                 $.ajaxSetup({
                                      headers: {
                                          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                                      }
                                  });


                                $.ajax({



                                    url : "{{ url("$lang/post_message_test")}}" ,
                                    method : 'POST',
                                    cache: false, 
                                    dataType:'JSON', 
                                    data: {   msg:msg  , authenticated_user_id:authenticated_user_id  , user_id:user_id , conversation_id: conversation_id , _token:token   },

                                    success:function(data){

                                       // my logic  
                                    }
                                });


                                return false ;    


            } 

        });

    });

</script>

this will take with a chat controller and specific function called postMessage

it has a structure like the following

public function postMessage(Request $request ){


    if($request->ajax()){




        /** data coming from our post request with an elegant way */
        $authenticated_user_id = $request->get('authenticated_user_id'); 
        $user_id = $request->get('user_id'); 
        $conversation_id = $request->get('conversation_id');

        $msg = $request->get('msg');




        // find user image  
        $user = User::find($authenticated_user_id) ; 
        $image = asset('uploads/users/').'/'.$user->profileImage ; 




        $name = '' ; 

        if($user->userType == 'doctor'){

            $name = $user->doctorName ;
        }else{
            $name = $user->headPersonName  ; 
        }





        $message  = new Message ; 

        $message->sender_id = $authenticated_user_id ; 
        $message->receiver_id = $user_id ; 
        $message->conversation_id = $conversation_id ; 
        $message->message = $msg ; 
        $message->is_read = 'not_read'  ; 

        if($message->save()){

            $msg=Message::where('id',$message->id)
            ->select('id','message','sender_id','receiver_id','created_at')
            ->with('sender')
            ->with('receiver')
            ->first();






         $sender_name =  $msg->sender->name ; 
         $sender_image =  $msg->sender->profileImage ; 

          $dt = Carbon::now(); 

                $message_date  = $dt->diffForHumans() ; 






           event(new MessageWasRecieved( $user_id , $message->message , $image  , $authenticated_user_id , $name ));

           return Response::json([
                                    'status'=>'success'   , 
                                    'message'=>$msg->message , 
                                    'user_id'=>$user_id , 
                                    'auth_id'=>Auth::user()->id , 
                                    'image'=>$sender_image , 
                                    'name'=>$sender_name 


                                ]);



        }else{

             return Response::json([
                                    'status'=>'error'   , 



                                ]);
        }






    }


}

in that simple logic when it reaches to event function , it should trigger that event and in javascript am waiting to listen to this event .

what really happens is that after posting to this url post_message_test that what happens in network tab instead of returning a status code of 200 it gives me a 302 status ( check image below )

enter image description here

and call another url called campaign ( this is a url found also in my project ) . i have tried all possible cautions , i terrible checked my code and am sure of every thing is working perfect

so what is causing that and i hope i could described my problem correct
thanks

1 Answers1

0

The status code 302 means a redirection! There is more than one explanation for this, but often it is due to a route protected by the auth middleware while the user is not connected!

To communicate with laravel by XHR request the best way to do this is to use Laravel Passport ( link here )! I already met this kind of problem! This problem is that Laravel when it receives a request ajax it checked if in the headers there is the 'Authorization' header otherwise it redirects the user because for him he has no access token

How to install Laravel Passport ?

  • with composer run : composer require laravel/passport
  • Then run : php artisan migrate to migrate passport Tables

Configuration

  • Go to Config/auth.php and change the api driver to passpor

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
    
    • Finally add HasApiTokens traits in your User Model and Passport::routes() in your AuthServicePovider Class : method boot()
Aboubacar Ouattara
  • 511
  • 1
  • 6
  • 18
  • Okay , hence my request is ajax , i returned it all {"msg":"fdfdsfsdd dfsdfd","authenticated_user_id":"1","user_id":"2","conversation_id":"4","_token":"B3jfy7nOHMcUnebqCFJxgfX4qgl37wZyYyWdFTyc"} this is the request->all() – Emad Rashad Muhammed Feb 20 '18 at 13:32
  • when you put dd () at the beginning of your postMethd you get this result? – Aboubacar Ouattara Feb 20 '18 at 13:37
  • To communicate with laravel by XHR request the best way to do this is to use Laravel Passport! I already met this kind of problem! This problem is that Laravel when he receives a request ajax it checked if in the headers there is the header 'Authorization' otherwise it redirects the user because for him it has no access token - il edit my answer and i add Laravel Password Link! – Aboubacar Ouattara Feb 20 '18 at 13:52