mardi 11 septembre 2018

how to control multiple ajax requests in laravel 5.2

I am working on an application where different ajax requests fires depending upon different actions.

For example, there is a chat window having send button. When i click on that button an empty message is sent with ajax, successfully. It work nice. But when I hit the send button too many times, at start some requests respond 200 (ok) but then it respond 500 (internal server error). Due to this the other requests that are going continuously like updateLastActivity also disturb. The preview of the error in developer's tool is: Whoops like something went wrong.

Note: When I make this chat system in core PHP, it work fine. There is no internal server error when I send too may requests.

Here is the code I am using

    //the following code is used to send the message
 $(document).on('click','.send_message_bt',function(event){
     event.preventDefault();

        var id=$(this).data('id');
        var name=$(this).data('name');
        var message=$("#message_field-"+id).val();



    $.ajax({
        //headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
         headers: { 'X-CSRF-TOKEN': {!! json_encode(csrf_token()) !!} },
        url:'',
        type:'POST',
        data:{
          id:id,
        message:message
           },
        success:function(data,status){
        //clear the message field value
        $("#message_field-"+id).val('');

        //update the chat history
        fetchChatHistory(id,name);


    },
        error:function(response){
           if(response.status==401){
                  alert('You are not logged in!');
                  window.location=window.location.href;
                   }

           }

});

});

here is the back end code

public function sendMessage(Request $request){
    $message=new Userchatmessage();
     $message->message=$request->message;
     $message->sender_id=Auth::user()->id;
     $message->receiver_id=$request->id;
     $message->save();
     return response('success');
}

How to fix this issue.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire