4

I am trying to parse the response data sent by RestResource in my VF page using Javascript.

The JS looks like:

var forceTKClient = new forcetk.Client();
    var Resp;
            forceTKClient.setSessionToken('{!$Api.Session_ID}');

            forceTKClient.apexrest(
                '/AD/SampleResponse',
                function(data, textStatus, jqXHR) {
                    alert((data));
                    Resp = data;
                     alert('Out '+Resp);
                },
                function(jqXHR, textStatus, errorThrown) {
                    alert('ERROR - ' + textStatus+'/'+errorThrown);
                },
                'GET',
                'json',
                null,
                false
            );

     alert('Outside '+Resp); 

Although I have assigned the variable "Resp" with the data from the rest output, I am unable to read the same outside the function.

ex; The alert('Out '+ Resp) gives proper output. But, alert('Outside '+Resp) does not. it gives a blank output.

Also the JSON.parser(Resp) throws a error: unexpected token.

Below is my RestResource:

@RestResource(urlMapping='/AD/SampleResponse')
global class ADServiceDemo{

    @HttpGET
    global static string getSampleResponse() {

        return'{    "content": {        "result": {            "countryCode": "USA",            "modeUsed": "FASTCOMPLETION",            "preferredLanguage": "DATABASE",            "preferredScript": "POSTAL_ADMIN_PREF",            "processStatus": "Q3",            "countOverflow": true        },        "resultData": [            {                "elementInputStatus": "60000000000000000060",                "elementResultStatus": "F08080808000000000E0",                "elementRelevance": "10101010100000000010",                "mailabilityScore": "2",                "resultPercentage": "100.00",                "cassStatus": "ECA0",                "serpStatus": "ESE0",                "snaStatus": "ESN0",                "supplementaryGBStatus": "EGB0",                "supplementaryUSStatus": "EUS0",                "key": [],                "country": [                    {                        "type": "ISO2",                        "value": "US"                    },                    {                        "type": "ISO3",                        "value": "USA"                    },                    {                        "type": "ISO_NUMBER",                        "value": "840"                    },                    {                        "type": "NAME_CN",                        "value": "美国"                    },                    {                        "type": "NAME_DA",                        "value": "AMERIKAS FORENEDE STATER"                    },                    {                        "type": "NAME_DE",                        "value": "VEREINIGTE STAATEN VON AMERIKA"                    },                    {                        "type": "NAME_EN",                        "value": "UNITED STATES"                    },                    {                        "type": "NAME_ES",                        "value": "ESTADOS UNIDOS (LOS)"                    },                    {                        "type": "NAME_FI",                        "value": "YHDYSVALLAT"                    },                    {                        "type": "NAME_FR",                        "value": "ÉTATS-UNIS"                    },                    {                        "type": "NAME_GR",                        "value": "ΗΠΑ"                    },                    {                        "type": "NAME_HU",                        "value": "EGYESÜLT ÁLLAMOK"                    },                    {                        "type": "NAME_IT",                        "value": "STATI UNITI D AMERICA"                    },                    {                        "type": "NAME_JP",                        "value": "アメリカ合衆国"                    },                    {                        "type": "NAME_KR",                        "value": "미국"                    },                    {                        "type": "NAME_NL",                        "value": "VERENIGDE STATEN VAN AMERICA (VS)"                    },                    {                        "type": "NAME_PL",                        "value": "STANY ZJEDNOCZONE AMERYKI"                    },                    {                        "type": "NAME_PT",                        "value": "ESTADOS UNIDOS DA AMÉRICA (EUA)"                    },                    {                        "type": "NAME_RU",                        "value": "США"                    },                    {                        "type": "NAME_SA",                        "value": "الولايات المتحدة"                    },                    {                        "type": "NAME_SE",                        "value": "USA"                    }                ],                "supplementaryUS": [],                "locality": [                    {                        "type": "COMPLETE",                        "value": "MOUNTAIN VIEW"                    },                    {                        "type": "NAME",                        "value": "MOUNTAIN VIEW"                    }                ],                "postalCode": [                    {                        "type": "BASE",                        "value": "94043"                    },                    {                        "type": "FORMATTED",                        "value": "94043"                    },                    {                        "type": "UNFORMATTED",                        "value": "94043"                    }                ],                "province": [                    {                        "type": "ABBREVIATION",                        "value": "CA"                    },                    {                        "type": "COUNTRY_STANDARD",                        "value": "CA"                    },                    {                        "type": "EXTENDED",                        "value": "CALIFORNIA"                    }                ],                "subProvince": [],                "street": [                    {                        "type": "COMPLETE",                        "value": "ADA AVE"                    },                    {                        "type": "COMPLETE_WITH_NUMBER",                        "value": "100-299 ADA AVE"                    },                    {                        "type": "POST_DESCRIPTOR",                        "value": "AVE"                    }                ],                "number": [                    {                        "type": "NUMBER",                        "value": "100-299"                    },                    {                        "type": "COMPLETE",                        "value": "100-299"                    }                ],                "building": [],                "subBuilding": [],                "deliveryService": [],                "organization": [],                "contact": [],                "residue": [],                "recipientLines": [],                "deliveryAddressLine": [                    "100-299 ADA AVE"                ],                "countrySpecificLocalityLine": [                    "MOUNTAIN VIEW CA 94043"                ],                "formattedAddressLine": [                    "100-299 ADA AVE",                    "MOUNTAIN VIEW CA 94043"                ],                "completeAddress": "100-299 ADA AVE\r\nMOUNTAIN VIEW CA 94043"            }        ]    }}';
    }
}

Need inputs on why I cannot refer the response data outside the function and why the JSON.parser giving a error as "Unexpected Token"

Many thanks in advance!!

-Prashant

3
  • 1
    I would imagine that Resp inside the function yields a value because its invoked by the callback function when the async javascript invocation finishes. The one in the main body executes on load, when Resp doesn't have a value yet. Commented May 15, 2013 at 13:53
  • Ok. how would I refer the response outside, I want to parse the response using JSON parser. Commented May 15, 2013 at 13:55
  • I would try invoking Json parsing from within the callback method, i.e. inside the function? Commented May 15, 2013 at 14:31

1 Answer 1

4

The reason it doesn't seem to work is this: The request done is an ajax request and that takes a while. The javascript does not wait for this request to finish and therefore alerts Resp before Resp is set. So this is actually expected behaviour.

1
  • In other words, it will be visible in that scope, but not until the call completes. Another function in the same scope could be called to process the response when it's available (thus called a callback).
    – sfdcfox
    Commented Oct 18, 2013 at 14:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .