Search code examples
jqueryjsonjsonp

Can't get JSON from external service even using JSONP


Hi I'm trying to use json data from a site, but I'm unable to do it with jsonp, not sure if I'm coding something wrong or it's the service.

   <script>
    $(function () {
        $("#frmInstrumento").submit(function(event) {
            alert("hello");
            $.ajax({
                url: "https://www.camaradenegocios.com/api/get/",
                // The name of the callback parameter, as specified by the YQL service
                jsonp: "promotions",

                // Tell jQuery we're expecting JSONP
                dataType: "jsonp",

                // Work with the response
                success: function( response ) {
                    alert(response);
                    console.log( response ); // server response
                }
            });
        });
    });
    </script>

The url to work with is https://www.camaradenegocios.com/api/get/promotions I can see the data if I browse, but can't consume it with Jquery.


Solution

  • I hope you have included the jQuery library. If not, please do so by having something like this in your HTML page header:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    I think if you try to get JSON data instead of JSONP, it should work. Replacing your code with the one mentioned below will work as expected, fetching the response array that we see when we browse the URL.

    <script>
    $(function () {
        $("#frmInstrumento").submit(function(event) {
            alert("hello");
            $.ajax({
                url: "https://www.camaradenegocios.com/api/get/promotions",
                // The name of the callback parameter, as specified by the YQL service
    
                // Tell jQuery we're expecting JSON
                dataType: "json",
    
                // Work with the response
                success: function( response ) {
                    alert(response);
                    console.log( response ); // server response
                }
            });
        });
    });
    </script>
    

    Now response will have the raw response, you will have to stringify it to have it in readable format. Also you can play with this response as an object and extract attributes and members from it.