0

I have to make a request from javascript that is on server A, to a php file that is on server B. I can access both servers.

But something is getting wrong. I always get ready state 0, status 0.

This is the latest thing I tried: Please advice what I'm doing wrong. thanks.

Server A:

$.ajax({
    type: "GET",
    url: 'http://server_B/request.php',
    data: form_data,
    dataType: 'json',
    success: function (resp) {
        alert("Successful");
        console.log("Response completed");
        console.log("resp is" + resp);
    },
    error: function (xhr, error) {
        console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
        console.log("responseText: " + xhr.responseText);
        alert("Error occurred.");
    }
});

Server B: request.php

<?php
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

    # do the work and save it on $result array.
    print json_encode($result,true);
?>
Jason P
  • 26,984
  • 3
  • 31
  • 45
little star
  • 90
  • 1
  • 2
  • 8
  • I'm not familiar with jsnop, and I don't get any result on console so to understand what is happening.. – little star May 08 '14 at 16:55
  • in your ajax call, use `dataType: 'jsonp'` - learn about [JSONP](http://en.wikipedia.org/wiki/JSONP) – Pedro Estrada May 08 '14 at 16:56
  • Do you get a _SecurityError_ from the _XMLHttpRequest_ logged in your console? Does it work if you allow `*`? – Paul S. May 08 '14 at 16:58
  • What are you seeing in the console? What specific request is being sent? Is it an OPTIONS, or a GET? – Ray Nicholus May 08 '14 at 17:05
  • You should have an error in your javascript console. In Chrome (and maybe others, but Chrome for sure), it will tell you exactly what the problem was. – Jason P May 08 '14 at 17:08
  • I see this: readyState: 0 status: 0 responseText:, I also see the php url on red, I'm using firefox. – little star May 08 '14 at 17:11
  • Try Chrome... the console gives an error like `XMLHttpRequest cannot load http://serverB/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://serverA' is therefore not allowed access.` – Jason P May 08 '14 at 17:18
  • @JasonP, The console is giving same as firefox, however I noticed this under networks: GET (canceled) jquery-1.9.1.js:8526 Script 0 B 0 B Pending – little star May 08 '14 at 18:14

1 Answers1

-1

To use ajax between two different domains you will have to use jsonp

You can find more help in here

Community
  • 1
  • 1
vsmoraes
  • 194
  • 2
  • 7