0

I'm doing a CORS attempt trying a autocomplete functionality, just as a test, from my local server to other one which is online. This server has a basic authentication configured in the folder I'm trying to access. So I've done the ajax function (I'm using JQuery UI autocomplete) and I have configured the php script to return me a JSON. Everything was working fine from the same server.

This is what I've done:

$(function() {
      $( "#field" ).autocomplete({
        minLength: 1,
        source: function (request, response) {
          console.log(request.term);
          $.ajax({
            type: 'POST',
            url: url,
            data: {
              'idautor': 417,
              'lat': 43.56,
              'lon': -5.96,
              'etiqueta': request.term
            },
            crossDomain: true,
            dataType: 'json',
            beforeSend: function (xhr) {
              xhr.setRequestHeader ("Authorization", btoa(username + ":" + password));
            },
            success: function( data ) {
              response( $.map( data["pines"], function( item ) {
                return {
                  value: item["nombre"],
                  label: item["nombre"],
                  idsitio: item["idsitio"],
                  autor: item["autor"]
                }
              }));
            }
          }).then(function(data) {
            console.log('data', data);
          }, 
          function(err) {
            console.log('err', err);
          });
        },
        select: function (event, ui) {
          alert("El sitio con id "+ui.item.idsitio+" y autor "+ui.item.autor+" ha sido pulsado.");
        }
      })
    });  

The problem is when I try to use it from my local server, basically the cross-origin HTTP request I'm talking about I get the following error in my browser console:

XMLHttpRequest cannot load URL Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401

So I've researched the subject and I found couple of promissing and easy solutions to my problem. I've tried to add the headers to the php file:

header("Access-Control-Allow-Origin: *"); 
header("Access-Control-Allow-Credentials: true"); 
header("Access-Control-Allow-Methods: GET,POST,OPTIONS");
header("Access-Control-Allow-Headers: accept, authorization, content-type");  

Also tried to add them to my .htaccess file with no success at all. I'm still getting the same error. Any clue about what am I missing?

Just in case and for further information this is my XHR connection record when I send the request, where I cannot see the new headers I've added manually in the php.

enter image description here Thank you in advance.

Asur
  • 379
  • 3
  • 20
  • I had a similar problem with my php server and got it working by adding the code from this answer: http://stackoverflow.com/questions/18382740/cors-not-working-php/18399709#18399709 Try it out. – noviewpoint Feb 29 '16 at 15:27
  • @noviewpoint I've tried and still the same, don't know why but something is denying me the headers modifications or just overwriting it... – Asur Feb 29 '16 at 15:36

1 Answers1

0

Your AJAX request needs withCredentials set to true if you want CORS credentials.

Setting Access-Control-Allow-Origin to * also does not work when combined with Access-Control-Allow-Credentials. You will have to specify the exact domain.

Community
  • 1
  • 1
  • I've added `xhrFields:{withCredentials: true}` to my ajax function and `http://localhost` to my `Access-Control-Allow-Origin` header and I'm still getting the exact same feedback? Any possibility something is overwriting the headers? – Asur Feb 29 '16 at 15:35
  • I've noticed issues with local development and anything AJAX/CORS, so would it be possible to test it in an online environment and report back? – Sébastien Vercammen Feb 29 '16 at 15:38
  • I've already tested it without cors, just in the same server and the request and the json are perfect, they work alright so that's why I'm curious, appart from that what really draws my attention is the XHR browser report, I can't see the added headers anywere, as you can see at the image of the post. – Asur Feb 29 '16 at 15:43
  • You're now testing it with CORS and Googling gives enough results that explain how CORS can break when working in a local environment. It depends on too many factors that can influence your code: browser, browser version, xmlhttprequest vs jQuery. Can you test it on an online environment? – Sébastien Vercammen Feb 29 '16 at 15:46
  • Do you mean a fiddle? Because I only have 1 server... :( – Asur Feb 29 '16 at 15:58