Ajax POST request in laravel

Answers 2
  • Add CSRF token to data attribute in laravel ajax post request

    --PATH resources/views/<yourfile>.blade.php
    <script>
    $.ajax({
        url: "{{ route('postAjaxResponse') }}",
        method: "POST",
        data:{
            _token: '{{ csrf_token() }}',
            id: 4 
        },
        success:function(response){
            console.log(response);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(thrownError);
        }
    })
    </script>
    
    0

    Using this code snippet you can call the ajax post request in laravel by adding CSRF token to data attribute of ajax function. Laravel ajax POST request method is used to send and receive data from the server without reloading the page. 

    On the server side you can use the response() function with json() in your controller file to send response in json format to the client, like  return response()->json(['msg'=>'This is a message from server']);

    You have to use jQuery library in your view file to use the ajax function. You can change url route and data parameters and values as per your requirement and after getting response you can display in your view file using DOM manipulation.

  • Add CSRF token to headers in laravel ajax post request

    --PATH resources/views/<yourfile>.blade.php
    <!-- <head> -->
    <meta name="csrf-token" content="{{ csrf_token() }}"/>
    <!-- </head> -->
    
    <script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    $.ajax({
        url: "{{ route('postAjaxResponse') }}",
        method: "POST",
        data:{
            id: 4,
        },
        success:function(response){
            console.log(response);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(thrownError);
        }
    })
    </script>
    
    0

    Using the headers attribute in ajaxSetup() method you can add the CSRF token to all request headers in laravel post request. Once you set the csrf token in headers using ajaxSetup function you don’t have to pass the CSRF token in your data attribute of ajax function.

  • Back to code snippet queries related laravel