3

I only use JavaScript.

And i know jQuery will set's the CSRF by,

  $(function() {
   $.ajaxSetup({
     headers: {
       'X-CSRF-Token': $('meta[name="_token"]').attr('content')
    }
  });
});

But how could i use "CSRF-Token" in JavaScript ?

Is there any possibilities for common setup for all Ajax Call ?

4
  • What do you mean by how could I use? Commented Feb 22, 2017 at 5:01
  • ajaxSetup sets headers with csrf token for every ajax request Commented Feb 22, 2017 at 5:01
  • You do understand that jQuery is Javascript, right? Are you asking how to add a CSRF token to an AJAX request's headers without using jQuery? Commented Feb 22, 2017 at 5:17
  • Exactly...I'm not using jquert for Ajax. Commented Feb 22, 2017 at 11:19

4 Answers 4

5

To use csrf token common for all the ajax calls you have put following code in your master layout blade file.

In layout header:

 <meta name="csrf-token" content="{{ csrf_token() }}" />

In your layout footer:

    <script type="text/javascript">   
    jQuery(document).ready(function() {       
        jQuery.ajaxSetup({        
            headers: {            
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')        
            }    
        });    
    });
</script>

This will work for all your ajax requests.

Thanks

Sign up to request clarification or add additional context in comments.

2 Comments

I only want for JavaScript, not for jQuery !
In javascript you have to set token oin headers for each request. Like xhr.setRequestHeader("X-CSRFToken", csrf_token);
3

You can include layout header look same above

But if you want use pure javascript to include token you can use:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", url , true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.setRequestHeader("X-CSRF-TOKEN", document.head.querySelector("[name=csrf-token]").content );
xhttp.send(params);

Hope to help your code ^^

Comments

1

You can pass csrf token in ajax as like this:

   $.ajax({  
             url: "/user.php",  
             method:"post",  
             data: { 'user_id':user_id,
                    '_token': "{{ csrf_token() }}" }, 
             success:function(data){console.log(data);}
          });

Comments

0

I also have the same problem as you. But I have found the solution and you can take a look at this article How to include csrf_token() in an external js file in Laravel?. You just add a meta tag to your html

<meta name="_token" content="{{ csrf_token() }}">

And hopefully can help your problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.