[Solved] Issue pulling survey response data via API

0

Hi, I am attempting to pull data from a survey via API so I can customize the reporting process.

I have the following:

$(document).ready(function () {
var url = ‘https://restapi.surveygizmo.com/v4/survey/2367402/surveyresponse/429.json?api_token=xxxxxxxxxx’;
$.getJSON(url, function (data) {
alert(data.name);
});
}); 

I am receiving the following error –

XMLHttpRequest cannot load https://restapi.surveygizmo.com/v4/survey/2367402/surveyresponse/429.json?api_token=xxxxxxxxxx. The ‘Access-Control-Allow-Origin’ header has a value ‘http://www.surveygizmo.com’ that is not equal to the supplied origin. Origin ‘http://hayslett.xyz’ is therefore not allowed access. 

Is there something I am doing incorrectly that is causing this error?

Thanks!

Jacob Hayslett asked

    Best answer

    0

    Hi Jacob,

    The error you are running in to is due to the “Same Origin Policy” enforced by browsers. Essentially, you cannot use AJAX to request information from a URL with a different domain, unless “Cross Origin Resource Sharing” has been enabled on that resource.

    A workaround

    A workaround for this is something called JSONP, or “JSON with padding”. Essentially, you make your request by “loading” it as a <script> tag, which bypasses the Same Origin Policy. There’s a wonderful explanation of what JSONP is over at stackoverflow:

    http://stackoverflow.com/a/2067584

    And even better, jQuery has now abstracted away all of this as well, so using JSONP is just as easy as making a normal AJAX request:

    https://learn.jquery.com/ajax/working-with-jsonp/

    $.ajax({
    url: “https://restapi.surveygizmo.com/v4/survey.jsonp?api_token=XXXXXX”,
    jsonp: “callback”,
    dataType: “jsonp”,
    success: function( response ) {
    console.log( response );
    }
    });

    A word of warning

    Any Javascript that is loaded in the web browser is able to be read in plain-text by a visitor with the right technical knowledge. This includes the URL of your JSONP request, where your API token lies in plain sight.

    This method is “use at your own risk” – if you do not trust every visitor of your website with your API token, do not use JSONP.

    A better solution would be to send requests to your own server (“hey, go get me response ID 429!”), where you can then decide if you wish to process the request or not (“hmm, okay – this seems legit. Just one moment, reaching out to SurveyGizmo now…”). This avoids the Same Origin Policy, and also keeps your API token safe and out of sight.

    I hope this information helps!

    Nathan - Survey Astronaut answered
      ×

      Login

      Question stats

      • Active
      • Views1518 times
      • Answers1 answer
      • Followers0 followers