steph45
steph45

Reputation: 49

Sending data to a JSON with AS3

I've asked my client to share his database login and password but he can't give me full access to his database (security reason I suppose). He told me to use a REST/JSON service that allows to post the data via this url with a specific key that allows him to identify all the datas coming from my app.

Here's what I did :

var urlRequest:URLRequest = new URLRequest("the_url_using JSON service");
urlRequest.method = URLRequestMethod.POST;

 var urlvars: URLVariables = new URLVariables;
urlvars.observer_name = "Test Coco";
urlvars.observation_number = "5433";

trace("urlvars = "+urlvars);

urlRequest.data = urlvars;

var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, onComplete);
urlLoader.load(urlRequest);

It's working, as it's sending the data, but the data format seems to be incorrect..

the url returns this error : "Observer name is Missing"

And the "trace (urlvars)" output :

urlvars = observer%5Fname=Test%20Coco&observation%5Fnumber=5433

So I think the problem come from the special character or something like that (as you can "observer_name" results by "observer%5Fname" and we can see a lot of %5")

Any idea how can I solve this ?

Upvotes: 0

Views: 522

Answers (1)

Organis
Organis

Reputation: 7316

JSON string is a string representation of a generic object. Basically you go:

var anObject:Object =
{
    "observer_name": "Test Coco",
    "observation_number": 5433
};

or you can construct it

var anObject:Object = new Object;

anObject['observer_name'] = "Test Coco";
anObject['observation_number'] = 5433;

and then you convert it to String and attach to request

var jsonString:String = JSON.stringify(anObject);

urlRequest.method = URLRequestMethod.POST;
urlRequest.data = jsonString;

Read more about it: https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/JSON.html

Keep in mind that I don't know the specifics of that REST server of yours and the code above just might not work as it is. I only explain how to send a JSON string as a POST request.

Upvotes: 2

Related Questions