4

I'm trying to make a cross domain JSONP call in Chrome, but the I keep getting back "Uncaught SyntaxError: Unexpected token :" I've tried: changing the response content type, setting xhr headers, JSON.stringify, just about most of the solutions offered on here but nothing worked so far :-(

 $.ajax({
                type: "POST",
                url: "https://www.virustotal.com/vtapi/v2/url/report",
                crossDomain: true,
                contentType: "application/json; charset=UTF-8",
                dataType: 'jsonp',
                data: {
                    apikey: "*",
                    resource: "http://www.1001freefonts.com/font/BaroqueScript.zip"
                },
                jsonp: false,
                jsonpCallback: receive,
                success: function (data, textStatus, jqXHR) {
                    console.log("Data retrieved: " + data);
                }
            }).done(function () {
                console.log('I think we are done here');
            })
        .error(function (e) {
            console.log(arguments);
            console.log('something went funny here');
        })
        .complete(function (xhr, status) {

            console.log("complete");
        if (status === 'error' || !xhr.responseText) {
            console.log('error');
        }
        else {
            console.log("data found:" + xhr.responseText);
            //...
        }
    });
    });

    function receive(saveData) {
        if (saveData == null) {
            console.log("DATA IS UNDEFINED!");  // displays every time
        }
        console.log("Success is " + saveData);  // 'Success is undefined'
    }

In the debugger I can see the response

{"permalink": "https://www.virustotal.com/url/b5b546fdbb49a2258e951c5e568a52655c65ac56112e39d15af0954a53b36772/analysis/1360339512/", "url": "http://www.1001freefonts.com/font/BaroqueScript.zip", "response_code": 1, "scan_date": "2013-02-08 16:05:12", "scan_id": "b5b546fdbb49a2258e951c5e568a52655c65ac56112e39d15af0954a53b36772-1360339512", "verbose_msg": "Scan finished, scan information embedded in this object", "filescan_id": "b7e13c0242e9690aba1f3da4b73d9c2e99a9b7fd03f542b55e694a34aaf9eca8-1360339519", "positives": 0, "total": 35, "scans": {"CLEAN MX": {"detected": false, "result": "clean site"}, "MalwarePatrol": {"detected": false, "result": "clean site"}, "ZDB Zeus": {"detected": false, "result": "clean site"}, "K7AntiVirus": {"detected": false, "result": "clean site"}, "Quttera": {"detected": false, "result": "clean site"}, "Yandex Safebrowsing": {"detected": false, "result": "clean site"}, "MalwareDomainList": {"detected": false, "result": "clean site"}, "ZeusTracker": {"detected": false, "result": "clean site"}, "zvelo": {"detected": false, "result": "clean site"}, "Google Safebrowsing": {"detected": false, "result": "clean site"}, "BitDefender": {"detected": false, "result": "clean site"}, "Opera": {"detected": false, "result": "clean site"}, "G-Data": {"detected": false, "result": "clean site"}, "C-SIRT": {"detected": false, "result": "clean site"}, "Sucuri SiteCheck": {"detected": false, "result": "clean site"}, "VX Vault": {"detected": false, "result": "clean site"}, "ADMINUSLabs": {"detected": false, "result": "clean site"}, "SCUMWARE.org": {"detected": false, "result": "clean site"}, "Dr.Web": {"detected": false, "result": "clean site"}, "AlienVault": {"detected": false, "result": "clean site"}, "Malc0de Database": {"detected": false, "result": "clean site"}, "SpyEyeTracker": {"detected": false, "result": "clean site"}, "Phishtank": {"detected": false, "result": "clean site"}, "Avira": {"detected": false, "result": "clean site"}, "Antiy-AVL": {"detected": false, "result": "clean site"}, "Comodo Site Inspector": {"detected": false, "result": "clean site"}, "Malekal": {"detected": false, "result": "clean site"}, "ESET": {"detected": false, "result": "clean site"}, "SecureBrain": {"detected": false, "result": "unrated site"}, "Netcraft": {"detected": false, "result": "clean site"}, "ParetoLogic": {"detected": false, "result": "clean site"}, "URLQuery": {"detected": false, "result": "unrated site"}, "Wepawet": {"detected": false, "result": "unrated site"}, "Minotaur": {"detected": false, "result": "clean site"}}}

I've verified it on http://jsonlint.com/ and it shows that it's a valid JSON.

Here are the Response Headers

cache-control:no-cache
content-encoding:gzip
content-length:695
content-type:application/json
date:Wed, 13 Feb 2013 12:00:33 GMT
server:Google Frontend
status:200 OK
vary:Accept-Encoding
version:HTTP/1.1

Anyone have any ideas/suggestions?

10
  • 2
    For JSONP you need a functionwrapper. A Plain JSON Object is no valid JSONP Response. Is the server actually capable of serving JSONP-Responses? Commented Feb 13, 2013 at 12:18
  • Also dataType: 'jsonp', jsonp: false does not look correct. Commented Feb 13, 2013 at 12:27
  • 1
    @Christoph Re dataType: 'jsonp', jsonp: false they are correct, check out the documentation at api.jquery.com/jQuery.ajax Commented Feb 13, 2013 at 13:03
  • @Christoph after further checking it seems the server can only send back JSON but not JSONP. I need to figure out to convert the response. Commented Feb 13, 2013 at 13:55
  • 1
    Further explanation for the readers JSON header is content-type:application/json JSONP header should be like this Content-Type:application/javascript Commented Feb 13, 2013 at 13:58

3 Answers 3

3

After thorough testing, it was evident that it's not possible to capture the JSON object results when ajax is expecting JSONP in return (due to cross-domain restrictions). Even though the response status = 200.

I've been testing using jQuery AJAX calls, in attempt to see if the result can still be captured - despite there's Parsing Error thrown by the browser - but it didn't seem that's possible. It looks like that the Response Text arrives in the header after JS work is completed.

As @Florian F. @Likwid_T @Christoph have suggested above, a server-side script is definitely required to make it working properly. Other developers seem to be keen on using a proxy written in C# as a solution.

Sign up to request clarification or add additional context in comments.

Comments

1

JSONP doesn't work out of the box.

JSONP bypasses the cross-domain restriction by loading the result in a script tag.

Basically, your server has to be JSONP-enabled.

Do whatever needs to be done on your server side then right before sending the response :

  1. Check if the request has "_callback" set
  2. If set, wrap your content with the value of _callback.
  3. Send your data

Code example in PHP :

$responseString = '{"smthing":"val","smthingelse":"val2"}';
if (isset($_REQUEST['_callback'])) {
    $responseString = $_REQUEST['_callback'] . '(' . $responseString . ');';
}

It'll execute your 'done' anonymous function with the right arguments. (JQuery handles everything else)

7 Comments

what makes you think, he can modify the server? If he's doing a crossdomain request it's very likely he is not controlling this.
Cause it's the only solution as is. Crossdomain is only useful when you control the server, or if the server accepts it itself. Next solution is to build a proxy on your own domain that'll forward the request to the webservice.
@FlorianF. Christoph is right, I don't have control over the server. My project is restricted to JS only.
@Eric Then what about a proxy on your own server ?
@FlorianF. It would've made life easier, unfortunately the code has to run as an extension. It's all JS.
|
1

Christoph is right you need to encase your answer in your callback function, in your case at the end of the PHP file:

echo $_GET['receive'] . '(' . json_encode($yourResultObject) . ');';

or if you need a more complex object

echo $_GET['receive'] . '(' . json_encode(array(name1 => object1, name2 => object2, name3 => object3)) . ');';

You might have to tweak a bit, but basically whenever I get Unexpected token is almost always a syntax error that makes jQuery not get my callback function.

4 Comments

he doesn't have control over the serverside I think. Else in most cases you don't have to do a crossdomain request.
@Likwid_T unfortunately no server-side script can be involved. It'll have to remain JS. Is it possible to apply the same manipulation in JS? My callback function is not receiving the data, even though I can see in the response header the JSON object result returned.
Wait I just re-read: you're getting the data from the server in the response? {"permalink": "virustotal.com/url/…... etc? Is that correct?
What's happens if you console.log(data["permalink"]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.