0

I couldn't access the webservice call from cross domain. Please advice. I have pasted my source here.

PHP: webservice response

$data['response'] = 2;
header('Content-type: application/json');
echo json_encode($data);

jQuery Ajax Call:

$.ajax({
type: 'GET',
url: cross-domain-url,
data:{ param1:'123', param2:'123' },
dataType:'jsonp',
crossDomain: 'true',
async: true,
success:function (data) {
    alert('success');
},
error:function(){
    alert('error');
}
});

Cross Domain URL response:

{"ResultCode":2}

Always I am getting Error only. I don't know why. I can see the following message in Firefox inspect area.

SyntaxError: missing ; before statement
{"ResultCode":2}

Please help me.

Solution:

Modify the line like, echo 'someCallBackString('.json_encode($data).');'; instead of echo json_encode($data);

Created the function someCallBackString and proceeded my implementations.

user2987836
  • 1,543
  • 2
  • 10
  • 8
  • There must be a filename and line number being printed along with the error. That might help you debug. Can you check? – Pulkit Mittal Jan 23 '14 at 09:18
  • Check this out: http://stackoverflow.com/questions/19456146/ajax-call-and-clean-json-but-syntax-error-missing-before-statement You have to build the JSON rightly – owsata Jan 23 '14 at 09:20
  • @Pulkit: Thanks. I have checked the file. That contains "{"ResultCode":2}" only. It shows an error on 13th character. That is ":". – user2987836 Jan 23 '14 at 09:20
  • if you want to encode data why you are using header() because it will response you on ajax success and secondly you have miss ';' operator in your script please provide the line number and first direct hit your cross domain url – Agha Umair Ahmed Jan 23 '14 at 09:21
  • What is the output of your cross domain url? i mean is it producing valid json? – Jai Jan 23 '14 at 09:21
  • @owsata: Thanks for your response. But, we can't receive data from cross domain using JSON. So only I used JSONP. – user2987836 Jan 23 '14 at 09:23
  • @Jai: I have received {"ResultCode":2} from the cross domain. – user2987836 Jan 23 '14 at 09:25
  • @AghaUmairAhmed: I think you misunderstood my question. Please check the comments.. – user2987836 Jan 23 '14 at 09:27
  • @user2987836 how did you checked? by hitting the url in the web browser right. – Jai Jan 23 '14 at 09:28
  • @Jai: Yes. I checked it via browser. – user2987836 Jan 23 '14 at 09:30
  • @AghaUmairAhmed: We can't change JSONP to JSON. Similarly, if we use like someCallBackString({ The Object });, the response will be error only. No success. – user2987836 Jan 23 '14 at 09:34

3 Answers3

0

You are telling jQuery to make a JSON-P request (dataType:'jsonp'), but your server is returning JSON.

Consequently the browser is trying to execute a JSON text as if it was a JavaScript program (and it can't because it isn't).

Either:

  1. Remove the dataType property from the object so that jQuery will use the HTTP Content-Type to determine that it is JSON and add access control headers to permit your site to access the data on the other domain or
  2. Return JSON-P instead of JSON
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks for your attempt. 1. It is a cross domain related issue. I couldn't receive response without datatype. 2. We can't return JSON-P in webservice response. – user2987836 Jan 23 '14 at 09:42
  • 1. You need to implement the *entire* solution, not just the first half of it. The server must output HTTP headers that grant permission for JS in a browser to read it from another site. 2. Then you must use solution 1. – Quentin Jan 23 '14 at 09:43
  • How to give Access Control Headers. Please advice. – user2987836 Jan 23 '14 at 10:06
  • I have added the following codes in webservice. But still getting the same. header('Content-type: application/json'); header("access-control-allow-origin: *"); echo json_encode($data); – user2987836 Jan 23 '14 at 10:13
  • That should work. Look at your browser's developer tools. Does the JavaScript console report any errors? Does the Net tab show the HTTP request being sent and the response coming back? Are they correct? Is the status code OK? – Quentin Jan 23 '14 at 10:14
  • Yes. You are right. But I got the response in Net tab without adding the access control headers. My issue is getting error in ajax call. Although I got the response in Net tab, but the error alert box is displayed instead of success. – user2987836 Jan 23 '14 at 10:17
  • OK, so you got the response. Is the response correct? Is the status code OK? Does the JavaScript error console report any errors? – Quentin Jan 23 '14 at 10:19
  • Finally, I got the solution. I have added the following line in webservice. echo 'someCallBackString('.json_encode($data).');'; And Created the function someCallBackString, proceeded the upcoming steps. – user2987836 Jan 23 '14 at 10:32
  • @user2987836 — That was option 2 in my answer, which you said you couldn't do! (Well, it's a crappy option 2, and you *should* use a dynamic `$_GET['callback']` approach to get the function name, but it is still JSON-P). – Quentin Jan 23 '14 at 10:34
0

Ok the problem is in the JSONP data, when you send a request the JSON response would send a response as

callbackFunctionName(jsonData)

You do not have anything as such so is the issue you need to format the code as below

$(document).ready(function() {
    $.ajax({
        type: 'GET',
        url: 'your cross domain file',
        dataType:'jsonp',
        crossDomain: 'true',
        jsonpCallback: 'MyCallback',
        async: true,
        success:function (data) {
            console.log(data);
        },
        error:function(data){
                console.log('error');
        }
    });

    function MyCallback(data) {  
    }

});

Now in the response the data needs to be formatted as

$data['response'] = 2;
header('Content-type: application/json');
$json_data =  json_encode($data);
echo "MyCallback" . '(' . $json_data . ');';

You can now check your console and see the data is coming through

You can check more on this here http://remysharp.com/2007/10/08/what-is-jsonp/

Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63
-1

change your ajax to this code:

Solution

            $.ajax({
                    type: 'GET',
                    url: cross-domain-url,
                    data:{ param1:'123', param2:'123' },
                    dataType:'JSON',
                    success:function (data) {

                                alert('success');
                  },
                 error:function(){
                       alert('error');
                  }
             });

Hope it will work....

Nemo
  • 352
  • 3
  • 13