Search code examples
jqueryajaxjsonp

Implementing jQuery AJAX with jsonp response


I am having problem implementing jQuery AJAX with jsonp response. I try to access it but my failed callback function is called. I want my success callback function to get called.

Also note that on plain JavaScript i have already implemented it and i know about jsonp and cross domain ajax fundas. It on jQuery where I am failing.

The jsonp location is - here

The code is:

$.ajax({
  url: "http://www.demo.yogihosting.com/jquery/jsonp/data1.json",
  dataType: "jsonp",
  type: "POST",
  contentType: "application/json; charset=utf-8",
  success: function(result, status, xhr) {
    alert(result);
  },
  error: function(xhr, status, error) {
    alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
  }
});

You can view this on jQuery AJAX with jsonp on CodePen.

Please help !


Solution

  • The JSONP format you're calling has a callback of processJSONPResponse, so you need to set that in the jsonpCallback parameter of your AJAX request:

    $(document).ready(function() {
      $("#jsonpButton1").click(function(e) {
        $.ajax({
          url: "http://www.demo.yogihosting.com/jquery/jsonp/data1.json",
          dataType: "jsonp",
          type: "POST",
          jsonpCallback: 'processJSONPResponse', // add this property
          contentType: "application/json; charset=utf-8",
          success: function(result, status, xhr) {
            console.log(result);
          },
          error: function(xhr, status, error) {
            console.log("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
          }
        });
      });
    });
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <button id="jsonpButton1">Button 1</button>
    

    Working example

    Note that I had to place the working example in a fiddle as SO does not allow insecure outbound requests to be made.