External Connection JSON WebService

Posted on

Question :

I have a webservice in PHP feeding data from a array via JSON , to read in an HTML file.

When I run the application having $.get with a local file it works, but when I change the path to read the same file on my server, it does not connect.

I noticed in the console that there is an impediment to connections via localhost.

Considering that this application will be run from the base PhoneGap , what would be the best alternative to address this problem?


Answer :

It’s only localhost running, right? then the problem might be because it is not releasing the cross-domain, it must allow external access in the header:

header('Access-Control-Allow-Origin: *');



This problem is very common in webservices I suggest you study about CORS link .

This is a problem that has to be solved both on the server and in your client application being it a JS or another client.

To solve this on the server you can do as follows, just call this php function in your input file

  function cors() {

// permite para qualquer origem
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache por 1 dia

// Essa parte cuida do preflight request

    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         

    header("Access-Control-Allow-Headers: Accept, Content-Type");


echo "Você está com CORS!";

Remembering that it is not legal to access global variables like $ _SERVER directly strongly recommend some php package that does this, if possible a framework or mini framework for this service link already help.

To resolve this from the client side, just activate CORS in the jquery or http of the angle in which you prefer

        url: "http://example.com/minha/acao/",
        type: "POST",
        crossDomain: true,
        data: {conteudopost: "algumacoisa"},
        dataType: "json",
        success: function (response) {
        error: function (xhr, status) {

Basically this is any question leave a comment ai, vlw


I use the? callback =? to be able to access json webservices outside the local domain.
Example below.

<script type="text/javascript>
     $.getJSON("http://dominioexterno.com/caminho-do-get/?callback=?", function(exemplo){

        //o que voce quer fazer.


There is also the JSONP option, to take a look at this link here: Jquery Cross-Domain ajax call using JSONP


I ended up migrating to Angular.js and adopting the more structured CORS to serve my application.


Leave a Reply

Your email address will not be published. Required fields are marked *