Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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() {
      }
    });
});
like image 947
Mark Preston Avatar asked Mar 30 '15 10:03

Mark Preston


2 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....

like image 150
AKhil N Avatar answered Oct 18 '22 15:10

AKhil N


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.

like image 44
Quentin Avatar answered Oct 18 '22 17:10

Quentin