Summer Sale! All accounts are 50% off this week.

karthik_dev's avatar

Ideal way to use ajax in laravel

I want to save the user data in users table using AJAX.when i check the post route in postman It throws TokenMismatchException in VerifyCsrfToken.php line 67: . I have added the following code in the head.blade <meta name="csrf-token" content="{{ csrf_token() }}">

$(document).ready(function()
{
    $('.sendBtn').click(function()
    {
      var _token = $('input[name="_token"]').val();
      var customerName = $('.customerName').text();
      var url='{{ url('postitemdata') }}';
          $.ajax
          ({
            url: url,
            data: {           
       'username':customerName,
            '_token': _token
              },
            type: 'POST',
            success: function(data)
            {
              $('#loadingmessage').hide();
            }
          });
    });
});

in controller

    public function postitemdata()
    {
        if(Request::ajax())
        {
        $users= new User(Input::all());
                 $users->save();
               return redirect()->back()->with('success','data added Successfully');
    }
    }

In view

<form class="form-horizontal" role="form" enctype="multipart/form-data" method="POST" action="{{ url('postitemdata') }}">
<span class="customerName ">yyy</span>
</form>
0 likes
1 reply
topvillas's avatar

Postman doesn't care what's in your blade template.

To test with Postman disable the csrf middleware temporarily or move the route to the api route file.

Please or to participate in this conversation.