Ajax always return error when use with jsonp

1k Views Asked by At

I have spent all my day in understanding how jsonp works. I have tried many solutions available over internet but none of them is working for me. following is the code, I am accessing a third party rest API. First I used

dataType : "Json"

but it was giving me cross domain blockage error. I changed it to use

dataType : "jsonp"

but now response always ends in error method with

textStatus ="parseerror" and jqXHR ="call back was not called."

following is my sample code, please have a look

 <script type="text/javascript">
    $(document).ready(function () {
        alert("document is ready");
        window.test = function (data) {
            debugger;
        };

        $("#btnAuth").click(function () {
            $.ajax({
                url: "https://partner3.powerschool.com",
                dataType: "jsonp",
                jsonpCallback: 'test',
                beforeSend: function (req) {
                                   req.setRequestHeader("Authorization", "Basic " + "abc" + ":" + "xyz");
                    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
                },
                success: function (data) {
                    debugger
                    alert("success"); alert(data);
                },
                error: function (data, textStatus, jqXHR) {
                    debugger
                    alert(JSON.stringify(data));
                }

            });
        });
    });
</script>
1

There are 1 best solutions below

1
On

I suggest trying the jQuery Cross Origin Plugin.

It takes care of all the jsonp stuff behind the scenes, so all you need to do change it from a local ajax call to a remote one is is add the plugin to your page and add crossOrigin: true to your ajax arguments list.