Insert laravel csrf-token in ajax

0

This in a <script> to send a form without reloading the page but I get the HTTP419 error so I read the token failure, I was looking at the laravel documentation and the solution is this:

JS :

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

But I can not implement it in the script ..

JS:

<script>
    function loadLog() {
        var empresa= document.getElementById('empresa').value;
        var grupo= document.getElementById('grupo').value;
        var user_id= document.getElementById('user_id').value; 
        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                document.getElementById("createform").innerHTML = xhttp.responseText;
            }
        };

        xhttp.open("POST", "{{route('products.store')}}", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("empresa="+empresa+"grupo="+grupo+"user_id="+user_id+"");
    }
</script>
    
asked by jorge 09.11.2018 в 14:54
source

1 answer

1

You can do it in several ways: the best way is always to send it as data:

<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">

or with jquery:

"_token": "{{ csrf_token() }}"   // directo con php
"_token": $('meta[name="csrf_token"]').attr('content') // obteniendo el valor
    
answered by 09.11.2018 / 15:11
source