0

In my angular JS app i need to send data to server:

"profile":"OLTP",
"security":"rsh",
"availability":"4",
"performance": {
     "TRANSACTION_PER_SEC":1000,
     "RESPONSE_TIME":200,
     "CONCURRENT_CONNECTION_COUNT":500,
     "STORAGE_SIZE":200,
     "TOTAL_CONNECTION_COUNT":500
}

and in return i'll get

{"estimate" : 1600,"quoteid" : "Q1234"}

I was trying to do that with $resource but I am lost in syntax.

app.factory("VaaniEstimateService", function($resource) {
    var requestURL = "http://128.34.32.34:8080/enquiry";
    return $resource(requestURL, {callback: 'JSON_CALLBACK'}, { get: { method:'JSON'}, isArray:false });
});

Can you please provide me something to get me on the right path.

Oshenko
  • 17
  • 4

1 Answers1

0

You must use JSONP method and insert JSON_CALLBACK keyword to your url as callback function.

app.factory("VaaniEstimateService", function($resource) {
    return $resource("http://128.34.32.34:8080/enquiry?callback=JSON_CALLBACK", {}, {
        get: {
            method:'JSONP'
        },
        isArray:false
    }).get({
        profile:"OLTP",
        security:"rsh",
        availability:"4",
        "performance.TRANSACTION_PER_SEC":1000,
        "performance.RESPONSE_TIME":200,
        "performance.CONCURRENT_CONNECTION_COUNT":500,
        "performance.STORAGE_SIZE":200,
        "performance.TOTAL_CONNECTION_COUNT":500
    }, function (response) {
        console.log('Success, data received!', response);
    });
});

Your params will be sent as query params. Angularjs will automatically generate a global function for callback and replace its name with JSON_CALLBACK keyword. Your server must return json as javascript code by calling function that sent with callback parameter. For example, AngularJS is going to make GET request to that url:

http://128.34.32.34:8080/enquiry?callback=angular.callbacks._0?availability=4&performance.CONCURRENT_CONNECTION_COUNT=500&performance.RESPONSE_TIME=200&performance.STORAGE_SIZE=200&performance.TOTAL_CONNECTION_COUNT=500&performance.TRANSACTION_PER_SEC=1000&profile=OLTP&security=rsh

And your server must return response like that:

angular.callbacks._0({"estimate" : 1600,"quoteid" : "Q1234"});

Hope that's enough to give you an idea how jsonp works.

Murat Çorlu
  • 8,207
  • 5
  • 53
  • 78
  • Wow, thank you. I got it, now I understand. Can I ask u for a solution if a page is on same domain and I request as JSON? – Oshenko Sep 02 '13 at 21:50
  • If you remove `callback` parameter from URL and set method as `GET`(actually it's default method, so it's not necessary to set it), everything will be fine to work with JSON resources. – Murat Çorlu Sep 03 '13 at 08:10
  • 1
    Thank you very much. It is working fantastic! Now i get the difference between JSON and JSONP. – Oshenko Sep 03 '13 at 16:11