Loading data from php page into startLoading();
|
|
Thread rating:  |
Bublin - 10 Aug 2008 16:32 GMT Loading data from the test.php into the startLoading(); --------------------------------------------------------------------------------
Hi, How do I load the data from test.php "echo $photo_out;" into the startLoading();
Thanx in advance
loadVariables("test.php", this, "POST");
infoField._visible = true; startLoading(test.jpg); // need to replace "test.jpg" with the data from - test.php "echo $photo_out;"
function startLoading(whichImage) { loadMovie(whichImage, "imageLoader"); _root.onEnterFrame = function() { infoLoaded = imageLoader.getBytesLoaded(); infoTotal = imageLoader.getBytesTotal(); percentage = Math.floor(infoLoaded/infoTotal*100); infoField.text = percentage+"%"; if (percentage>=100) { delete this.onEnterFrame; infoField._visible = false; } }; }
Noelbaland - 11 Aug 2008 04:04 GMT Hello,
You should put your test.jpg in a variable and echo that out to Flash as a URL encoded string. Like so...
echo "photo_out=test.jpg";
Then in Flash you assign photo_out to your startLoading function.
startLoading(_root.photo_out);
You should try getting familiar with using the LoadVars object. With loadVariables you can't successfully tell whether the variable has loaded into Flash or not. On some servers it's "hit or miss" and users could be left with a long hangtime if variables haven't loaded. LoadVars has an onLoad method that takes care of that.
So if I was to use LoadVars in your code above - I'd do it like this...
// Create a LoadVars object var lv = new LoadVars();
// Load the PHP file using the POST method lv.load("test.php", POST);
// Test for a successfull load in Flash. success is a boolean // variable that returns true or false lv.onLoad = function(success){ if(success){ // Access photo_out variable thru the LoadVars object (lv) // using dot syntax startLoading(lv.photo_out); } else { trace("Error loading"); } }
// Rest of code
Bublin - 11 Aug 2008 10:42 GMT Hi,
Thanx for the reply, and can you help me out if you have the time.
I have no problem with PHP but the Flash action scripting is new to me. What I would like to do is the following:
Calling a php file example: test.php
<? if ($_GET['id']=="") { // check for main page $_GET['id']=1; } $dbh=mysql_connect ("localhost", "root", "password") or die ('I cannot connect to the Fine Gael database because: ' . mysql_error()); mysql_select_db ("finegael"); $result = mysql_query("select * from main where id= '".$_GET['id']."'"); $record = mysql_fetch_object($result)
echo "$record->title"; echo "$record->header"; echo "$record->description"; echo "$record->photo"; // will be news.jpg ?>
Then importing the data into flash:
The echoed "title" must go into a dynamic text field called: "title" The echoed "header" must go into a dynamic text field called: "header" The echoed "description" must go into a dynamic text field called: "description" And the echoed "photo" goes into the: startLoading();
infoField._visible = true; //startLoading("http://87.232.XX.XXX/finegael/images/photo/photo01.jpg"); startLoading(echoed photo data);
function startLoading(whichImage) { loadMovie(whichImage, "imageLoader"); _root.onEnterFrame = function() { infoLoaded = imageLoader.getBytesLoaded(); infoTotal = imageLoader.getBytesTotal(); percentage = Math.floor(infoLoaded/infoTotal*100); infoField.text = percentage+"%"; if (percentage>=100) { delete this.onEnterFrame; infoField._visible = false; } }; }
So the result will be: A displayed photo with the title, header and description.
Hope you are able to help me out here. Thanx in advance,
Rick
Noelbaland - 12 Aug 2008 08:26 GMT Hello again,
It doesn't matter what method in PHP you use to pull records out of MySQL - you still need to send the results back to Flash as an URL encoded string (or as XML). Once it's in Flash you use the LoadVars object to assign the appropriate data to the text boxes and your startLoading function.
Look at the code below and read the comments for more info.
PHP -------------------------------------------------------------------------------- -----------------
// Check incoming GET variable with isset if(isset($_GET['id'])){ $id = $_GET['id']; } else { $id = 1; }
$dbh = mysql_connect ("localhost", "root", "password") or die ('I cannot connect to the Fine Gael database because: ' . mysql_error()); mysql_select_db ("finegael"); $result = mysql_query("select * from main where id= $id");
// It's faster to use mysql_fetch_assoc than mysql_fetch_object while($row = mysql_fetch_assoc($result)){ // Start building your URL encoded string $return = "title=".$row['title']; $return .= "&header=".$row['header']; $return .= "&description=".$row['description']; $return .= "&photo=".$row['photo']; }
// Output to Flash echo $return;
// This is what the string will look like in the browser title=MyTitle&header=MyHeader&description=MyDescription&photo=MyPhoto1
ACTIONSCRIPT -------------------------------------------------------------------------------- -----------------
// Create a LoadVars object var lv:LoadVars = new LoadVars();
// Load the absolute url. The default method to send is GET lv.load("http://localhost/test.php");
// Test that our data has successfully loaded lv.onLoad = function(success) {
// If so, fill the textboxes with the appropriate data and // pass the photo into the startLoading function if (success) { title_txt.text = this.title; header_txt.text = this.header; body_txt.text = this.description; startLoading(this.photo); } };
function startLoading(whichImage) { loadMovie(whichImage, imageLoader); _root.onEnterFrame = function() { infoLoaded = imageLoader.getBytesLoaded(); infoTotal = imageLoader.getBytesTotal(); percentage = Math.floor(infoLoaded/infoTotal*100); infoField.text = percentage + "%"; if (percentage >= 100) { delete this.onEnterFrame; infoField._visible = false; } }; }
Bublin - 12 Aug 2008 14:09 GMT Hi again,
Would you be able to make a working .fla The .php is working fine but when I create a .swf I can't get it working. Can't see what I am doing wrong!
So if you have the time Thanx in advance,
Rick
Bublin - 12 Aug 2008 14:15 GMT Hi again :)
Got it now (after alot of messing) The thing I did wrong was so simple! I used the AS 3 and it didnt work, when I used AS 2 it's working fine.
Thanx again with this working example it's clear to me how it works.
Grtx, Rick
SmilingRoses - 15 Aug 2008 15:50 GMT Noelbaland,
I have been searching for days for an explanation as succinctly put as yours. I got all excited, but then I tried it - it didn't work and then read to the bottom of the page where Bublin says your code works for AS 2, but not AS 3. Do you know how to make it work in AS 3? I will be grateful 'til the end of time if you can answer this question for me.
Noelbaland - 17 Aug 2008 03:24 GMT Ok - So to recreate the same example in AS3 takes a little more work and is a little different, but the logic involved is the same. The PHP file stays the same and still needs to output the results as an URL encoded string. The heavy work gets done in Flash. Unlike the AS2 version where everything was handled with the LoadVars object, AS3 uses the URLLoader, URLVariables and URLRequest classes to send and recieve data from the server.
I've put up a simple example online that can be viewed here. You can download the files here. Below is the code thats used in both PHP and Flash. Read the comments for more.
[PHP]
<?php
// Connection variables $host = "localhost"; $user = "root"; $pass = ""; $database = "thenews";
// Open a connection to the server and database $conn = mysql_connect($host, $user, $pass); mysql_select_db($database);
// Get one record from the news table $sql = "SELECT * FROM news WHERE id = 1"; $query = mysql_query($sql);
// Start building and concatenating variables to form our // URL encoded string while($row = mysql_fetch_assoc($query)){ $return = "title=".$row['title']; $return .= "&header=".$row['header']; $return .= "&description=".$row['description']; $return .= "&photo=".$row['photo']; }
// Output the string to Flash echo $return;
// Close the connection to database mysql_close($conn);
?>
[ACTIONSCRIPT]
// Import the required classes import flash.net.*; import flash.display.*; import flash.events.*;
// Create a URLRequest object and put the absolute url to the PHP file in it var request:URLRequest = new URLRequest("http://localhost/FLASH/news.php");
// Create a URLLoader object and load all the data from the PHP file into it. // This would be the equivalent to the LoadVars object in AS2 var loader:URLLoader = new URLLoader(); loader.load(request);
// This lets Flash know that the data recieved will be in variable=value format loader.dataFormat = URLLoaderDataFormat.VARIABLES;
// When all the data is all loaded we send it to the onComplete function loader.addEventListener(Event.COMPLETE, onComplete);
// This is for the preloader mc thats on stage. The preloader is for the photo // that gets loaded in. Here we're just hiding it for now. preloader.visible = false;
// The onComplete function basically takes all the data and assigns // the variables to dynamic textfields on stage. It then sends the photo // variable to the startLoading function. function onComplete(event:Event):void { // Using an object to hold all the variables makes it easier // to access and assign the values to the right textfields var article:Object = event.target.data; title_txt.text = article.title; header_txt.text = article.header; body_txt.text = article.description;
// Concatenate the complete URL to the photos folder with the // photo name and pass it into the startLoading function as a string. var photo:String = "http://localhost/FLASH/photos/" + article.photo; startLoading(photo); }
// The startLoading function creates a new Loader object and loads the // photo into it. It uses the event handlers to show, monitor and animate, // and finally hide the preloader function startLoading(image:String):void { // Assign the url to the photo to a URLRequest object var photoURL:URLRequest = new URLRequest(image);
// Create a new Loader object that will hold the photo var photoLoader:Loader = new Loader(); photoLoader.load(photoURL);
// Event handler to show the preloader photoLoader.contentLoaderInfo.addEventListener(Event.OPEN, onOpen); // Event handler to monitor and animate the preloader photoLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
// Event handler to hide the preloader after photo has appeared photoLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onFinished);
// Add the loader object to the stage and position it addChild(photoLoader); photoLoader.x = 280; photoLoader.y = 120; }
function onOpen(event:Event):void { preloader.visible = true; preloader.loader_bar.scaleX = 0; }
function onProgress(event:ProgressEvent):void { var percent = event.bytesLoaded/event.bytesTotal; preloader.loader_bar.scaleX = percent; }
function onFinished(event:Event):void { preloader.visible = false; }
SmilingRoses - 19 Aug 2008 20:08 GMT Thank you so much for your effort with this. I followed your code, but I am not uploading a photo - just name, address, phone, etc., so I followed your code to the end of where you created the article variable and matched the dynamic text fields to the php variables.
Below is the Flash error I get when I try to run it.
TypeError: Error #2007: Parameter text must be non-null. at flash.text::TextField/set text() at pageList/onComplete() at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at flash.net::URLLoader/onComplete()
Below is my onComplete function
function onComplete(event:Event):void { var article:Object = event.target.data; first_tx.text = article.firstName; last_tx.text = article.lastName; address_tx.text = article.address; phone_tx.text = article.phone; email_tx.text = article.email; website_tx.text = article.website; occupation_tx.text = article.occupation; comments_tx.text = article.comments1; }
Noelbaland - 20 Aug 2008 01:01 GMT Hello SmilingRoses,
I don't think the error is in the onComplete function. I think it's something else. It starts from a pageList function. Can you post your full code here?
Thanks
SmilingRoses - 20 Aug 2008 12:17 GMT I rechecked everything and reran it. Still doesn't work, but am getting different error message. The pageList is one of the pages of the website I am trying to put together. I will include the php code, the code on the pageList page and the code on the main page followed by the error message in that order. Thanks again for your time with this.
<?php $con = mysql_connect('localhost', 'root', 'xxxxxxxxx'); if (!$con) {die('Could not connect; ' . mysql_error($con));} mysql_select_db('sle',$con);
$sql = "select firstName,lastName,address,phone,email,website,occupation,comments1 from form where id=1"; $query = mysql_query($query);
while($row = mysql_fetch_assoc($query)) { $return = "firstName=".$row['firstName']; $return .= "&lastName=".$row['lastName']; $return .= "&address=".$row['address']; $return .= "&phone=".$row['phone']; $return .= "&email=".$row['email']; $return .= "&website=".$row['website']; $return .= "&occupation=".$row['occupation']; $return .= "&comments1=".$row['comments1']; } echo $return; mysql_close($con); ?>
import flash.net.*; import flash.display.*; import flash.events.*;
var request:URLRequest = new URLRequest("http://localhost/sle/listRequest.php");
var loader:URLLoader = new URLLoader(); loader.load(request); loader.dataFormat = URLLoaderDataFormat.VARIABLES; loader.addEventListener(Event.COMPLETE, onComplete);
function onComplete(event:Event):void { var article:Object = event.target.data; first_tx.text = article.firstName; last_tx.text = article.lastName; address_tx.text = article.address; phone_tx.text = article.phone; email_tx.text = article.email; website_tx.text = article.website; occupation_tx.text = article.occupation; comments_tx.text = article.comments1; }
// Scene 1 code /////////////////////////
import fl.transitions.Tween; import fl.transitions.easing.*; import flash.net.*; import flash.media.Video;
// footer code /////
footer_mc.addEventListener(MouseEvent.MOUSE_OVER, over); footer_mc.addEventListener(MouseEvent.MOUSE_OUT, out);
function over(e:MouseEvent):void { footer_mc.gotoAndStop(2); }
function out(e:MouseEvent):void { footer_mc.gotoAndStop(1); }
// title play button code //
play_btn.addEventListener(MouseEvent.CLICK, startAnim); stop_btn.addEventListener(MouseEvent.CLICK, stopAnim);
function stopAnim(e:MouseEvent):void { house_mc.stop(); }
function startAnim(e:MouseEvent):void { house_mc.play(); }
// code for Menu Buttons //
var currentPage:MovieClip = home_mc;
var homePage:pageHome = new pageHome(); var formPage:pageForm = new pageForm(); formPage.stop(); var listPage:pageList = new pageList(); listPage.stop(); var marketPage:pageMarket = new pageMarket(); marketPage.stop(); var loginPage:pageLogin = new pageLogin(); loginPage.stop(); var chatPage:pageChat = new pageChat(); chatPage.stop(); var adsPage:pageAds = new pageAds(); adsPage.stop(); var funPage:pageFun = new pageFun(); funPage.stop(); var videoPage:pageVideo = new pageVideo(); videoPage.stop();
homePage.x = 76; homePage.y = 292; formPage.x = 92; formPage.y = 290; listPage.x = 500; listPage.y = 330; marketPage.x = 500; marketPage.y = 380; loginPage.x = 515; loginPage.y = 425; chatPage.x = 500; chatPage.y = 508; adsPage.x = funPage.x = videoPage.x = 500; adsPage.y = funPage.y = videoPage.y = 550;
addChild(homePage);
highlight_mc.x = home_mc.x; underline_mc.x = home_mc.x;
home_mc.targetMC = homePage; form_mc.targetMC = formPage; list_mc.targetMC = listPage; market_mc.targetMC = loginPage; chat_mc.targetMC = chatPage; ads_mc.targetMC = adsPage; fun_mc.targetMC = funPage; video_mc.targetMC = videoPage;
home_mc.buttonMode = true; form_mc.buttonMode = true; list_mc.buttonMode = true; market_mc.buttonMode = true; chat_mc.buttonMode = true; ads_mc.buttonMode = true; fun_mc.buttonMode = true; video_mc.buttonMode = true;
home_mc.addEventListener(MouseEvent.MOUSE_OVER, mUnderline); form_mc.addEventListener(MouseEvent.MOUSE_OVER, mUnderline); list_mc.addEventListener(MouseEvent.MOUSE_OVER, mUnderline); market_mc.addEventListener(MouseEvent.MOUSE_OVER, mUnderline); chat_mc.addEventListener(MouseEvent.MOUSE_OVER, mUnderline); ads_mc.addEventListener(MouseEvent.MOUSE_OVER, mUnderline); fun_mc.addEventListener(MouseEvent.MOUSE_OVER, mUnderline); video_mc.addEventListener(MouseEvent.MOUSE_OVER, mUnderline);
function mUnderline(e:MouseEvent):void { new Tween(underline_mc,"x",Strong.easeInOut,underline_mc.x,e.currentTarget.x,.5,true ); }
home_mc.addEventListener(MouseEvent.MOUSE_OUT, mUnderlineBack); form_mc.addEventListener(MouseEvent.MOUSE_OUT, mUnderlineBack); list_mc.addEventListener(MouseEvent.MOUSE_OUT, mUnderlineBack); market_mc.addEventListener(MouseEvent.MOUSE_OUT, mUnderlineBack); chat_mc.addEventListener(MouseEvent.MOUSE_OUT, mUnderlineBack); ads_mc.addEventListener(MouseEvent.MOUSE_OUT, mUnderlineBack); fun_mc.addEventListener(MouseEvent.MOUSE_OUT, mUnderlineBack); video_mc.addEventListener(MouseEvent.MOUSE_OUT, mUnderlineBack);
function mUnderlineBack(e:MouseEvent):void { new Tween(underline_mc,"x",Strong.easeInOut,e.currentTarget.x,currentPage.x,.5,true) ; }
home_mc.addEventListener(MouseEvent.CLICK, newPage); form_mc.addEventListener(MouseEvent.CLICK, newPage); list_mc.addEventListener(MouseEvent.CLICK, newPage); market_mc.addEventListener(MouseEvent.CLICK, newPage); chat_mc.addEventListener(MouseEvent.CLICK, newPage); ads_mc.addEventListener(MouseEvent.CLICK, newPage); fun_mc.addEventListener(MouseEvent.CLICK, newPage); video_mc.addEventListener(MouseEvent.CLICK, newPage);
function newPage(e:MouseEvent):void { new Tween(highlight_mc,"x",Strong.easeInOut,highlight_mc.x,e.currentTarget.x,.5,true ); removeChild(currentPage.targetMC); currentPage = MovieClip(e.currentTarget); addChild(currentPage.targetMC); }
///////// Flash Error /////////////////////////
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs. at Error$/throwError() at flash.net::URLVariables/decode() at flash.net::URLVariables() at flash.net::URLLoader/onComplete()
Noelbaland - 21 Aug 2008 01:54 GMT Hi again,
If I had thought about the error in Flash yesterday that you posted I wouldn't had made you waste your time posting your full code. I'd just finished resolving the same issue (before I saw yours) in another post. I'll explain it here.
I'm guessing you have your FLA file saved in your root directory of your server (I use Wampserver which has Apache, MySQL, and PHP for Windows). When you start up Flash for the first time and do a Test Movie(Ctrl+Enter) the first result will be the one and only result you'll see. What I mean is that if you make a change in your actionscript and then do a Test Movie and preview it thru Flash - you'll just see the same thing over and over again. Even if you change your PHP code or database the result will be the same. The reason for this is that Flash doesn't cache the SWF file each time you Test Movie. The most reliable way is to save, publish, and view the result in the browser.
So ignore the error in Flash and look at your movie in the browser. I'm sure it will display as it should.
SmilingRoses - 22 Aug 2008 22:09 GMT I thought that if you saw the website that I am trying to put together it would be easier for you to suggest ways to help me. My biggest problem is getting the data back into Flash. The data gets to the mysql database just fine.
the url is www.malinda-bruce.com/sle/sle.html
SmilingRoses - 23 Aug 2008 15:02 GMT I don't know what changed, but I finally got the data to show on my list page. Now how do I get it to show more than one row of data?
Noelbaland - 24 Aug 2008 07:45 GMT Hello,
OK. The best way to do that is to select all your textfields and turn it into one whole movieclip. Then we give that movieclip a custom class name and use actionscript to attach it to the stage at runtime. We need to make a change to the PHP script and also the onComplete function in the actionscript.
In the PHP script, create the $return variable before the while loop and type the following
$return = "num=". mysql_num_rows($query) ."&";
Here we start the URL encoded string by attaching a new variable called num. This num variable will return the number of rows(or records) in our database. We use this variable in Flash to loop thru our data.
Back in Flash, create a New Symbol and name it "empty". Once inside the empty mc go back to the main stage. This what we want - an empty movieclip. We're going to put this clip on stage later and fill it up with our custom movieclips.
Select all your textboxes on stage and convert them into one whole movieclip(F8). You can leave your instance names for the textfields the same as we will still be accessing them. In the Create New Symbol box name it "infobox_mc" and make sure it's registration point is in the top left. Hit OK to close.
Now right click on this infobox_mc in the Library and choose Linkage. Check the Export for Actionscript box and in the Class field type in InfoBox. This is our custom class for our custom Movieclip.
Finally, drag out the empty movieclip and position it on stage. Give it an instance name of empty_mc.
The rest gets handled in the actionscript. We'll only be changing the onComplete function so the rest of your code will be fine. Read the comments for more info.
[Changes to PHP code]
$sql = "SELECT firstName,lastName,address,phone, email,website,occupation,comments1 FROM form "; $query = mysql_query($sql);
// Start the $return varable here and pass in a new variable // called num. num will be assigned the number of rows returned // from the database. $return = "num=". mysql_num_rows($query) ."&";
while($row = mysql_fetch_assoc($query)) { $return .= "firstName=".$row['firstName']; $return .= "&lastName=".$row['lastName']; etc...
[Actionscript]
function onComplete(event:Event):void { // See note below var article:Object = event.target.data;
// We need to attach our custom InfoBox class to // an instance of the MovieClip object. So we declare that here var infobox:MovieClip;
// Next we need to get the num variable from the PHP script // so that we can use it in a loop var numRecords:Number = article.num;
for(var i:int=0; i<numRecords; i++) { // Now we assign the custom class Infobox to // the infobox mc infobox = new InfoBox();
// Space each infobox instance vertically. Change the // number if you want more or less space. infobox.y = i * 30;
// Like before, we now access the textfields(via the infobox instance) // and assign the matching data from server to them. infobox.first_tx.text = article.firstName; infobox.last_tx.text = article.lastName; infobox.address_tx.text = article.address; infobox.phone_tx.text = article.phone; infobox.email_tx.text = article.email; infobox.website_tx.text = article.website; infobox.occupation_tx.text = article.occupation; infobox.comments_tx.text = article.comments1;
// Finally, we add the infobox instances to the empty movieclip empty_mc.addChild(infobox); } }
NOTE: You might want to change this article variable name to a name that more closely resembles it's purpose - maybe "details" or "clientlist".
SmilingRoses - 21 Aug 2008 13:37 GMT I tried. It doesn't work.
pulmego - 09 Oct 2008 14:36 GMT Thanks for the code, very nice and useful
|
|
|