0

I have set very simple php page which return rows feteched from mysql. On localhost my jquery page is

 $.ajax({
        url: "http://abcd.com/cccbsapp/test.php",

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

        complete:function(data){
            console.log(data)
        }           
    })

but console.log shows

enter image description here

I am not been able to get the actual JSON array returned by my php page. But console/network tab shows the returned data. enter image description here

So I know that data is returning from remote server, but how can I get it in $.ajax.

When I use dataType:"JSON", it give CORS error, so I am using JSNOP. I am not very experienced with that.

Rafael
  • 18,349
  • 5
  • 58
  • 67
raju
  • 6,448
  • 24
  • 80
  • 163
  • A little Google will take one far - http://stackoverflow.com/questions/3839966/can-anyone-explain-what-jsonp-is-in-layman-terms https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS HNY! – tiblu Jan 02 '17 at 13:41
  • @Rafael, I already tried these links, the problem is, when I give dataType: 'jsonp', the success event never get fired. Any suggestion. – raju Jan 02 '17 at 13:54

1 Answers1

1

The problem here is, that in order to use JSONP, the server needs to reply in a special way, not just print the data in JSON format.

When using jsonp, jQuery sends a request to the server with callback=someFunctionName in the URL. In this case the server response should be

someFunctionName(HERE THE DATA)

Also, complete callback gets as first argument always the jqXHR object, not the returned data, because complete is called by jQuery in both - request success and error - scenarios. Better use success callback for fetching the data and error for handling errors or even the Promise interface (.done() and .fail() methods).

$.ajax({
    url: "http://abcd.com/cccbsapp/test.php",
    // Tell jQuery we're expecting JSONP
    dataType: "jsonp"           
}).done(function (data) {
    console.log(data);
}).fail(function () {
    console.log("An error occured");
});

As an alternative way to using JSONP, you could just stick to normal JSON requests. To make Cross-Origin requests work, the server needs to include Access-Control-Allow-Origin header in the response, e.g.

header('Access-Control-Allow-Origin: *');

(instead of the * you can list domains that are allowed to query this API)

Rafael
  • 18,349
  • 5
  • 58
  • 67
  • I have added header('Access-Control-Allow-Origin: *'); and it works now. But I want to know that I have already added it inside .htaccess Header set Access-Control-Allow-Origin "*", but it was not working. Can you please help me in understanding PHP access vs .htaccess Access. – raju Jan 02 '17 at 14:46
  • @raju Just guessing, but If PHP on your server runs through fastcgi, maybe the issue is related to this: stackoverflow.com/a/38159002/80720 – Rafael Jan 02 '17 at 21:19