0

I am trying to use ajax from another server to request for data from my server as a webservice. It returns a valid json generated by json_encode

 {"reference":"","mobile":"","document":"","appointment":""}

To make it avoid the 'Access Control Allow Origin issue, I have used the dataType as 'jsonp'. However, whenever I do that, I will receive a Parse Error which I can't seem to solve (even though I have tried to copy some other valid json from other people too.

Anyone have any idea how can I resolve this?

toffee.beanns
  • 435
  • 9
  • 17

2 Answers2

0

Well, jsonp is supposed to be a data type for json with padding not just any json. A jsonp is normal json wrapped in a function. Thus when you receive a jsonp, you can use that function in a closure and get the desired output. To avoid the cross-browser issue, you have three choices:

  1. If you have control over the server, then output cross-origin headers along with json.
  2. You get the json via backend calls like curl.
  3. You use a phantomJS (+ CasperJS to make your life easier) to scrape the page and get the json.

If you could describe actually what you are trying to accomplish, I might be able you better.

Chris Roy
  • 945
  • 1
  • 7
  • 19
  • I am trying to create a small plugin with the HTML iframe tag in wix. I have created a php file hosted on my own server to return the json I require. – toffee.beanns Jun 10 '15 at 05:22
  • I tried adding the cross origin headers into the json but it doesn't seem to work – toffee.beanns Jun 10 '15 at 05:23
  • could you post the error from the console in chrome along with the source of your file that returns the json output? Not the json file but the code that outputs the json? – Chris Roy Jun 10 '15 at 06:05
0

With Json for CORS error/Access Control Allow Origin issue i do the following, On the API end i make sure the headers are set to allow all. I am using SLIM framework(php) but this can be done in any framework.

function get_data(){
    .....(get the data from db)......
    $response->headers->set('Access-Control-Allow-Origin', '*');
    $response->headers->set('Cache-Control', 'no-cache'); 
    $response['Content-Type'] = 'application/json';
    $response->body(json_encode($result));
}

On the jquery end i call the API like so,

 $.ajax({   
    url: "http://api.example.com/v1/get-data",
    success: function(data) {       
        console.log(data);
    },
    error: function(){
        console.log('error');
    },
    method:"GET",
    async: true,
    });

If the above doesn't work for some reason and you have to use jsonp, then do the following: https://stackoverflow.com/a/6879276/4369851

Community
  • 1
  • 1
ziggrat
  • 106
  • 1
  • 7