-1

$.ajax({
  url: "RestEndPoint",
  headers: {
    'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
  }
  method: 'POST',
  dataType: 'JSON',
  data: dataObj,
  success: function(data) {
    console.log('Success')
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

There are hundreds of ajax post calls. Is there a way to intercept all the calls in one place and add the header there? Cannot use ajaxPrefilter as jquery 1.11.3 doesn't support it.

  • 1
    _"Cannot use ajaxPrefilter as jquery 1.11.3 doesn't support it"_ - Why do you think so? [`.ajaxPrefilter()`](https://api.jquery.com/jQuery.ajaxPrefilter/) is part of jQuery since version 1.5. Open the URI from your ` – Andreas Sep 16 '20 at 16:38
  • @Andreas You are right. I'll try to use ajaxPrefilter to add header globally. – Anita Ghising Sep 16 '20 at 16:48

2 Answers2

0

var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxPrefilter(function(options, originalOptions, jqXHR){
    if (options['type'].toLowerCase() === "post") {
        jqXHR.setRequestHeader('X-CSRFToken', csrf_token);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Resolved using ajaxPrefilter

0

You can do it global by set it on the $.ajaxsetup function

$.ajaxSetup({
headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
         }
});
J. Murray
  • 1,460
  • 11
  • 19
shabandino
  • 224
  • 1
  • 3