0

I am trying to access the JSON object from this third party service, inside my javascript application.

However, because I was getting the Same Origin Policy error earlier, I have tried using JSONP and jQuery and AJAX, respectively as follows.

Using JSONP

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>
    function foo(data)
    {
        // do stuff with JSON
        console.log(data);
    }

    var script = document.createElement('script');
    script.src = 'https://matchstat.com/tennis/match-stats/m/8348298?callback=foo'

    document.body.appendChild(script);
    // or document.head.appendChild(script) in modern browsers
</script>
</body>
</html>

Using jQuery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script>
    $.getJSON("https://matchstat.com/tennis/match-stats/m/8348298?callback=?", function(data) {
        console.log(data);

        // Get the element with id summary and set the inner text to the result.
        $('#summary').text(data.result);
    });
</script>
</body>
</html>

Using AJAX

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script>
    CallURL();

    function CallURL(){
        $.ajax({
            url: 'https://matchstat.com/tennis/match-stats/m/8348298',
            type: "GET",
            dataType: "jsonp",
            async:false,
            success: function (msg) {
                JsonpCallback(msg);
            },
            error: function () {
                ErrorFunction();
            }

        });

    }

    function JsonpCallback(json)
    {
        console.log("came inside JsonpCallback ...");
        document.getElementById('summary').innerHtml=json.result;
    }

    function ErrorFunction()
    {
        console.log("came inside the ErrorFunction() ...");
    }
</script>
</body>
</html>

However, I haven't been able to access the JSON object.

tubby
  • 2,074
  • 3
  • 33
  • 55
  • 2
    You cannot just change the request type to JSONP, the response has to be formatted correctly for that to work which depends on the server. If you're getting SOP errors from the request using JSON, then the receiving domain has not enabled third-party requests through JS and there's nothing you can do about that. – Rory McCrossan May 29 '16 at 21:29
  • ^ that, if the service doesn't specifically support JSONP, there's nothing you can do – adeneo May 29 '16 at 21:29
  • @RoryMcCrossan, thanks. So, how do you suggest that I read json data from this URL ? Using server side PHP as an AJAX call? – tubby May 29 '16 at 22:18

0 Answers0