user4457363
user4457363

Reputation:

Cross domain Ajax requests with Symfony2 (example with FOSUserBundle)

I have a domain A "xbo.dev" and a sub domain B "blog.xbo.dev".

For example, on B domain, I would like to make an Ajax request to a domain A function.

I'm trying this with FOSUserBundle authentication. What I do :

    var xhr = new XMLHttpRequest();

      if ('withCredentials' in xhr) {
          xhr.open('POST', 'http://xbo.dev/ajax/check_login_ajax', true);
          // I am using hard coding for the URL because with Routing.generate I would have this URL : http://blog.xbo.dev/ajax/check_login_ajax
          // which is not good because the request is on a different domain
          xhr.onreadystatechange = function() {
          if (xhr.readyState === 4) {
              if (xhr.status >= 200 && xhr.status < 400) {
                  console.log(xhr);
                  console.log('ok');
              } else {
                  console.log('ko');
              }
          }
      };
      xhr.send(encodeURI('_username=' + $('#co_'+varName+'username').val() + '&_password=' + $('#co_'+varName+'password').val() + '&_remember_me=' + false + '&_csrf_token=' + $('#co__csrf_token').val()));

I have a "ok" displayed by my request but nothing special is happening (I should have something like "Bad credentials" or "success" (or others), returned by FOSUserBundle check_login_ajax function, but no one of those is displayed...)

How can I do ?

EDIT 1 : Here is the result I have each time, either the login / password are correct or not

Here is the Ajax result

And with a normal $.ajax, I have this :

Here is the Ajax result

Upvotes: 2

Views: 544

Answers (1)

Peter Bailey
Peter Bailey

Reputation: 105908

You need to implement something to relax the same-origin policy such as CORS.

As to your in-code note about hard-coding vs using the router to generate URLs, Symfony's router supports hostnames.

Upvotes: 1

Related Questions