Home » Php » javascript – X-Requested-With is not allowed by Access-Control-Allow-Headers

javascript – X-Requested-With is not allowed by Access-Control-Allow-Headers

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am developing one system. In that system there is one add item to cart functionality. In that functionality, I am using Jquery $.ajax used. But online server I have facing this error –

“XMLHttpRequest cannot load domain
name/add_to_cart.php?item_id=3&hotel_id=2. Request header field
X-Requested-With is not allowed by Access-Control-Allow-Headers.”

Can any help me how to solve this error.

I am using this jquery code

$(document).on('click', '.ordering_btn', function(){
    var item_id = $(this).data('value');
    var hotel_id = "<?php echo $hotel_id; ?>";

    $.ajax({
      type: 'GET',

      url: 'add_to_cart.php?item_id='+item_id+'&hotel_id='+hotel_id+'',

      contentType: 'text/plain',

      xhrFields: {
        withCredentials: false
      },

      headers: {
        "Access-Control-Allow-Headers": "X-Requested-With",
        "X-Requested-With": "XMLHttpRequest"        
      },

      success: function(data) {
        $('#cart_msg').css('display', 'none');
        $('#cart_item').html(data);
        console.log(data);
      },

      error: function() {
      }
    });
});
How to&Answers:

The error can be fixed by adding

header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

in the server where ajax call leads to….

Answer:

Remove this:

  headers: {
    "Access-Control-Allow-Headers": "X-Requested-With",
    "X-Requested-With": "XMLHttpRequest"        
  },

Access-Control-Allow-Headers is a response header, not a request header.

The server you are making the request to does not allow X-Requested-With.