I have a Flash developer I'm working with. This person is building a tool in AS2 that will provide an interface that will send voting data (firstname, lastname, email address, votes (there are 100 items in categories and users will be able to choose some subset to declare "best").
All fair enough, Flash dev will POST data to a PHP app I will develop, and I will store the data in MySQL. This Flash dev has not done a great deal of work with databases or web apps.
I want to return data back to the Flash application. I want to be able to return "email address invalid" or "problem connecting to database" or "vote information accepted" messages. My instinct is to want to send back JSON or XML data. But I'm wondering if there are tools in AS2 to easily consume such responses.
I would like to see some "Hello World" type examples of AS2 code that consumes JSON or XML data so I can get the Flash app and the PHP app interacting well. My understanding is AMF is not on the table because it's AS2, but I'm open to what will work on both ends given the constraint of it being AS2.
Below should give you an example.
XML:
<alldots>
<dotname id="bigDot" color="0xff0000" url="http://www.fletchermartin.com/" photos="8" />
<dotname id="otherDot" color="0x000066" url="http://www.ajc.com/" photos="8" />
<dotname id="thirdDot" color="0xCC0099" url="http://www.tiffanybbrown.com/" photos="0" />
</alldots>
AS2 Code
var dots:XML = new XML();
dots.load('bigdot.xml');
dots.onLoad = function(success:Boolean){
if(success){
if(dots.status == 0){
var dotsToXMLString:String = new String(); // initializes a new string variable
dotsToXMLString = dots.toString(); // converts dots XML object to a string and stores it in dotsToXMLString.
var dotsXML:XML = new XML(dotsToXMLString);// creates new XML object with the string contents from above.
dotsXML.parseXML(dotsToXMLString); // parses the string from above.
var dotsNodes:Object = dotsXML.firstChild; // Saves the firstChild (in this case, the outermost element) as an object
var dotsNodesChildren:Object = dotsNodes.childNodes; // Saves the childNodes of firstChild as an object
for(i=0;i<dotsNodesChildren.length;i++){
var newObj:Object = dotsNodes.childNodes[i].attributes.id; // creates a new object out of the child node's id.
var newObjColor:Color = new Color(newObj); // creates a new color object with newObj as its target
var theColor:Number = dotsNodes.childNodes[i].attributes.color; //retrieves the hex code value (number) of the attribute color
newObjColor.setRGB(theColor); // sets the RGB value of newObjColor.
}
} else {
trace("Problem parsing XML.");
}
} else{
trace("Could not load XML");
}
}
Related
i am a beginner. I'm starting to learn Adobe Flash. I followed the code on Google on AS2:
l = new LoadVars();
l.onLoad = function(ok) {
ttl0=l.ttlslv0; atc0=l.atcslv0;
ttl1=l.ttlslv1; atc1=l.atcslv1;
};
l.sendAndLoad("http:localhost/getdata.php", l, "POST");
with php like this:
<?php
include_once("koneksi.php");
$qr = mysqli_query($con,"SELECT title, article from $tabel");
$nr = 0;
while($kolom=mysqli_fetch_row($qr) )
{
$ttl=$kolom[0];
$atc=$kolom[1];
echo "&ttlslv$nr=$ttl&atcslv$nr=$atc";
$nr++;
}
echo "&nr=$nr&";
?>
with the results that I can specify "what row" and "what column" will I take.
can this be changed to AS3 with the same results?
I have difficulty studying AS3
anyone want to give me a solution? thanx...
In AS3 you use the URLLoader class to load text/binary data. To work with URL-encoded strings you need the URLVariables class.
Something like that (not tested, no error handling either, just a common guideline):
// URLRequest instance holds various information
// about what, where and how you send.
var aRequest:URLRequest = new URLRequest;
// URL address.
aRequest.url = "http://localhost/getdata.php";
// Request method (POST or GET mostly).
aRequest.method = URLRequestMethod.POST;
// URLLoader instance performs the requested operations:
// uploads the request and relevant data, reads the answer,
// and dispatches all the events about any status changes.
var aLoader:URLLoader = new URLLoader;
// Tell the URLLoader that the answer is
// an URL-encoded text of key=value pairs.
aLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
// This event handler function will be triggered
// upon successfully completed operation.
aLoader.addEventListener(Event.COMPLETE, onData);
// Start loading.
aLoader.load(aRequest);
// The COMPLETE event handler function.
function onData(e:Event):void
{
// Unsubscribe from the event. For the most part it is
// a GOOD idea NOT to re-use any network-related
// class instances once they've done their job.
// Just unsubscribe from all their events,
// dismantle their data structures, purge
// any references to them and let the
// Garbage Collector do his job.
aLoader.removeEventListener(Event.COMPLETE, onData);
// Retrieve the object that contains key=value pairs.
var anAnswer:URLVariables = aLoader.data as URLVariables;
// The data you wanted to get.
trace(anAnswer.ttlslv0);
trace(anAnswer.atcslv0);
trace(anAnswer.ttlslv1);
trace(anAnswer.atcslv1);
}
UPD: It seems that you are dealing with escaped text there. I composed a simple script that explains how it works:
import flash.net.URLVariables;
var V:URLVariables = new URLVariables;
var S:String = "a=1&b=2";
V.decode(S);
trace(V.a); // 1
trace(V.b); // 2
S = escape(S);
trace(S); // a%3D1%26b%3D2
trace(unescape(S)); // a=1&b=2
V.decode(S); // Error #2101
So, there are two options you can work on:
Figure out why server passes the escaped string and prevent it.
Load the server's answer as a plain text (URLLoaderDataFormat.TEXT instead of VARIABLES) so the URLLoader.data will be just a simple String, then unescape(...) it if necessary and feed to the URLVariables.decode(...).
I'm having trouble populating a combobox from an XML response. Here is the XML that I am receiving:
<distros>
<entry>
<distro>CentOS</distro>
<distro>Debian</distro>
<distro>Other</distro>
<distro>Sabayon</distro>
<distro>Ubuntu</distro>
<distro>VMware</distro>
<distro>Windows</distro>
</entry>
</distros>
So probably the most basic form of XML ever!
and here is the flex code:
private function getDistros():void
{
httpReq = new HTTPService;
httpReq.url = 'http://myserver/xml.php';
httpReq.resultFormat = 'e4x';
httpReq.method = 'GET';
httpReq.addEventListener(ResultEvent.RESULT, popDistros);
httpReq.send( null );
}
private function popDistros(event:ResultEvent):void
{
if(event.result != "")
{
// Set the data to the XMLListCollection for lookup
myXmlCollection= new XMLListCollection(event.result.entry);
// Bind the ListCollection to the comboBox
Alert.show(myXmlCollection.toString());
distroCombo.dataProvider = myXmlCollection.toString();
}
}
and the MXML:
<mx:ControlBar x="139" y="10" width="266" height="358" verticalAlign="top" horizontalAlign="left" direction="vertical">
<mx:ComboBox id="distroCombo" labelField="distro"></mx:ComboBox>
<mx:ComboBox id="imageCombo"></mx:ComboBox>
<mx:Button label="Download"/>
</mx:ControlBar>
The XML comes back fine in the Alert but the comboBox won't populate and I have tried this so many different ways now, anyone got any suggestions? Have I just been staring at it far too long?
if the result (event.result) is XML, then It should wotk like this: (it differs with .distro in the end compared to yours)
myXmlCollection = new XMLListCollection(event.result.entry.distro);
...this should create valid data in myXmlCollection
But then also this row is wrong:
distroCombo.dataProvider = myXmlCollection.toString();
it creates just one item in dataProvider of type string, (Just BTW: if you would have used spark combobox, you would have get compile error at this row).
just use this instead:
distroCombo.dataProvider = myXmlCollection;
And also note, that you can see correct result in the Alert, but it does not say if the data are of correct type, coz Alert evertyhing converts to string :)
I am working on some code using Google Maps API. To sum up shortly, I have MySQL database with a table of information used to generate markers on the map. I connected to the database and am using PHP to draw out the necessary attributes and communicate with my Javascript code using XML.
What I'm currently attempting to do is go in the other direction, I'm trying to send a string of information (for example "1,2,3,45,18") from my Javascript code to MySQL to be set as a session parameter (call it #sparam). What is the process behind passing this value to MySQL?
Would I be able to access a MySQL variable through PHP in the same way I can access tables (for the purpose of getting a value back into Javascript)?
I'd appreciate any insight.
Thanks.
EDIT
Maybe I was unclear in my original post. What I'm asking is how would I be able to pass a string to a MySQL session variable, specifically a set of IDs directly related to the IDs in the table of the MySQL database, and then be able to work with these IDs by calling the necessary procedures in MySQL. In turn, the procedures called in MySQL would generate some output, which would then have to be passed back to the Javascript code.
I created a special JSON (JavaScript Object Notation) php pages that I would call from javascript. Then I would parse those JSON responses.
Simple example:
JAVASCRIPT:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "page_json.php?action=getsession",
type : "GET",
success : function(data) {
//Get Json and loop over it's data
if (data.length>10){
var jsonData = JSON.parse(data);
$.each(jsonData, function(Idx, Value) {
if (Idx>0){
//get values for each vehicle and then remove it's marker from the map and then add new marker on the map (thereofore update the marker)
c_latitude = Value["lat"];
c_longitude = Value["lon"];
c_name = Value["name"];
c_notes= Value["notes"];
removeMarker(c_name); //remove old marker function
addMarker(c_latitude, c_longitude, c_name); //add current marker function
}
});
}
}
});
});
}
PHP: Here I loop over my arrayList and then create a simple array with values. Then I just output it as a json string
foreach ($listOfCars->arrayList as $key => $value) {
$unit = new fleetUnit();
$unit = $value;
//create array for json output
$data[] = array('lat' => $unit->lat,
'lon' => $unit->lon, 'name' => $unit->name, 'notes' => $unit->notes);
}
echo json_encode($data);
I am creating a mobile app that needs to be connected with mysql. I used php to query it and got the data to my php page.. I would like to bind this data with the list box in my windows phone 7. I am very new to this kind of programming and would like to how to get the data from the php page and bind it with the list box in my wp7 app.. I managed to print the data using webclient in a messagebox in wp7 app.. but i would like to bind it to the list box... please help....
My code:
public Article()
{
InitializeComponent();
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(printlist);
wc.DownloadStringAsync(new Uri("http://www.skbcreations.com/app/Pushnotification.php") );
return;
}
void printlist(object sender, DownloadStringCompletedEventArgs e)
{
string res = (String)e.Result;
MessageBox.Show(res);
}
My XAML:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.061*"/>
<ColumnDefinition Width="0.939*"/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="1" Margin="24,28,36,56"/>
</Grid>
Which format has your response?
If XML, you could use this one:
XElement xmlItems = XElement.Parse(e.Result);
var items = from item in xmlItems.Descendants("item-element-name")
select new Item
{
field1 = item.Element("field1").Value,
field2 = item.Element("field2").Value
};
listBox.ItemsSource = items.ToList();
Also, consider to use ObservableCollection if your list will be changing in run-time
I'm writing an application that downloads an XML string from a URL and POSTs that to another URL (that's set up to handle an incoming "XML" field). I've got the first part right - it downloads the XML and I can alert() it and all that, but I'm unable to figure out how to POST that data to a server.
function pull() {
var myLoader = new air.URLLoader();
var myRequest = new air.URLRequest('http://something/something.xml');
myLoader.addEventListener(air.Event.COMPLETE, pulled);
myLoader.load(myRequest);
}
function pulled(evt) {
if (evt.target.bytesTotal>0) {
// alerting shows the full string just fine
alert(evt.target.data);
var myLoader = new air.URLLoader();
var myRequest = new air.URLRequest('http://someplace/push.php');
myRequest.method = air.URLRequestMethod.POST;
// myVars = new air.URLVariables("xml="+evt.target.data); //
// alert(evt.target.data.toUpperCase());
myRequest.data = "xml="+evt.target.data; // myVars;
myLoader.dataFormat = air.URLLoaderDataFormat.TEXT;
myLoader.addEventListener(air.Event.COMPLETE, pushed);
myLoader.load(myRequest);
}
}
I made the 2nd server PHP echo the contents of the xml variable, but I'm just unable to get the exact contents of the XML string. There is something I'm doing wring with the myRequest.data and/or dataFormat bit.
Can someone just figure this out? I know it's probably a simple thing, but I'm at my wit's end right now.
This is my first AIR app.
Another related question (or sub-question) is that...
alert(evt.target.data); // shows an alert box with the XML
alert(typeof evt.target.data); // shows String
alert(evt.target.data.toUpperCase()); // shows the xml converted to upper case
alert(encodeURI(evt.target.data)); // shows up blank.
alert(escape(evt.target.data)); // shows up blank.
Why??
The error seems to be the way you are assigning the parameters to 'data' ... Use URLVariables.
var params:URLVariables = new URLVariables();
params.[name of parameter] = [value];
--- so like params.xml = (YOUR XML) ... from your example:
// uses the dynamic object to add the 'xml' property to 'params' at runtime.
params.xml = evt.target.data
Then Change you request.data to request.data = params;
-- The URLVariables guy is dynamic - so you can add properties as I describe above.
For a basic example - much more complete that what I have here: http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_2.html