32 Replies Latest reply on Nov 6, 2006 8:16 AM by w4rts

    post and recieve without refresh

    w4rts
      Howdies,

      I'm trying to create a flash shoutbox for a site that I'm running.

      I have the movie calling a php (xml) file to read the shouts that have been made. I have a seperate php file that handles the POST addition of new shouts. The problem is that when the movie does the POST it brings the browser to the post.php page instead of adding the message and re-displaying the movie witht the new shout.

      Is there a way to use loadVars in a way to send the POST info but not redirect to the post.php page, and refresh the movie with the new shout?

      heres the script:

        • 1. post and recieve without refresh
          w4rts Level 1
          sorry... miss-post
          • 2. Re: post and recieve without refresh
            w4rts Level 1
            I guess maybe a better way of asking is is there a way to POST with loadVars *without* re-directing the page to the loadVars URL?

            I'm trying to get the swf to read and write from a php page that is handling the db stuff. The reading works fine, but when I try to POST a new message, it re-directs to the php page instead of staying within the swf, and updating the list.

            Is there a way to do this?

            Much thanks.
            • 3. Re: post and recieve without refresh
              TimSymons Level 1
              Use the sendAndLoad() method instead of just the send() method of the LoadVars class.

              Tim
              • 4. Re: post and recieve without refresh
                w4rts Level 1
                Yeah, I've been trying that, too. When I hit the send button using sendAndLoad, the movie just sits there. It never refreshes, and the data doesn't get sent tot the db.

                My mind is blank... 40+ hours on a simple thing like this is too much...

                Thanks for trying, Tim... It's greatly appreciated.

                aj
                • 5. Re: post and recieve without refresh
                  TimSymons Level 1
                  Do you want to Flash to re-read the XML file after a new shout has been posted? To do that you will have to add a return value in you PHP string. Once the result is sent back to Flash you can then, based on the information sent back to Flash, execute any number of functions to re-read in your XML.

                  I used this technique for a Flash Blog engine I wrote that uses just Flash, XML and PHP. It allows people to post comments to the site and then see what they posted immediately and the page never refreshes.

                  Tim
                  • 6. Re: post and recieve without refresh
                    w4rts Level 1
                    That sounds exactly like what I want... It'd be even preferable to avoid using sql at all, as it seems to slow down the movie quite a bit.. I was looking at writing to a txt file formatted as xml, but wasn't having much luck. Not to mention the lack of sleep has me typing backwards most of eht time.

                    Is there any way you could point me in the right direction to try and get something going similar to your blog engine? Could I utilize the code I've already written and just alter the send and receive commands?

                    Just to be clear, when you say add a return value to my PHP string, do you mean the sendAndLoad url ...( "post.php", return_value, "POST") ?

                    This is the php I have... no Idea if it's even close to what you're talking about. And thanks again.
                    • 7. Re: post and recieve without refresh
                      w4rts Level 1
                      Does anyone know of a tutorial or some help files that I could use to get something like this working? Flash, PHP, and xml ?

                      Much thanks.
                      • 8. Re: post and recieve without refresh
                        TimSymons Level 1
                        I can't give you all of the code because I wrote it for the company I work for but here are some of the functions that I use. I have included the addComment.php file code and the 2 AS functions that create and send the XML node to the PHP file.

                        The results that I am talking about it partly what you referred to in your post and the other part would be an "echo" statement from the PHP. I use the "echo" statement to send results back to flash. Based on what I send back, Flash will execute various functions to re-read in the data that I just posted. To get this to work properly, I had to make sure that each item that read in XML was self contained, meaning, that it did not depend on other functions to activate it. In this way it was like separate little independent windows of information. I then used 1 main class as the wrapper and event dispatcher for all of the those independent windows.

                        Hope this helps you out a little.

                        Also, I had to download the DOMIT! XML Parser for PHP. No installation is required for the PHP code. Just place it in a directory and then reference it like I did in the code below. I provided a link to the PHP code below as well.

                        Good luck.

                        Tim

                        • 9. Re: post and recieve without refresh
                          jonnybennett Level 1
                          Coud you not do it all using php.
                          Use LoadVars to sendAndLoad the 'shout', to a php file called shouts.php,
                          shouts.php firstly saves the new shout to the mysql database, it then selects all the info in the database, and outputs it as a string
                          print '&shoutsToFlash='.databaseShoutConents;

                          The Load part of the sendAndLoad,
                          Then reads the shoutsToFlash variable and displays it.

                          problem: is that they will only get new 'shouts' when they submit there shout...

                          however you could run another sendAndLoad to a php page that doesn't save but gets all the shouts from the database once every 20 secs using setInterval. This will refresh all the new shouts.
                          • 10. Re: post and recieve without refresh
                            w4rts Level 1
                            Hmm, yeah I hadn't even thought about that... when you cant' get step 1 to work , you don't usually look down the road. At least I don't, expecially being this frustrated.

                            I thought I may be on to something. I added
                            if($submit){
                            $result=mysql_query("INSERT INTO shoutbox (id,name,time,message)"."VALUES ('NULL','$name','$time','$message')", $linkID);
                            print($xml_output);
                            } else {
                            }

                            to the bottom of my php page, and changed my actionscript.

                            When I test it looks like it's doing something, but it just sites there for a minute, never refreshes and the data doesn't get written to the DB. If I submit again, the data does get written to the DB, but still no refresh. I have to manually refresh the page to see the change.

                            *sigh*

                            Thanks for your help.
                            • 11. Re: post and recieve without refresh
                              w4rts Level 1
                              OK, this is nutz =-[

                              If I put this:

                              function doThisOnResponse(result) {
                              //if the result is true, so if everything went ok and the data has been received, do this:
                              if (result) {
                              trace(response);
                              } else {
                              //else there went something wrong.
                              trace("everything went wrong...aaghhh..damn this");
                              }
                              }

                              it traces the xml data (looks like: %3Cshouts%3E%0A%09%3Cshout%3E%0A%09%09%3Cname%3E....) but no matter what I do I cannot get it to replace the data that is currently in the text field. I've tried replacing the whole xml parsing function, everything in the script that has to do with xml I've tried to put in place of the trace with the result as the feed, but it refuses to work. What am I missing?

                              Thanks, and sorry for being a bother.
                              • 12. post and recieve without refresh
                                TimSymons Level 1
                                How are you sending back a response from your PHP file? In the last sample of PHP code you posted you have:

                                echo $xml_output;

                                Which return the string you created back to Flash when you use the sendAndLoad() method.

                                Tim
                                • 13. Re: post and recieve without refresh
                                  w4rts Level 1
                                  if (result) {
                                  var myResults:String = unescape(result);
                                  var myXML:XML = new XML();
                                  myXML.parseXML(myResults);
                                  trace(myResults);

                                  }

                                  for some reason returns boolean "true", no data.

                                  And if it did return data, how would I get that data t replace what's already in the movie?

                                  Much thanks.

                                  aj
                                  • 14. Re: post and recieve without refresh
                                    w4rts Level 1
                                    also, when using the sendAndLoad as opposed to just send it doesn't send the data to the database unless I hit the button twice... Is there something wrong in the code that's making it do that?
                                    • 15. Re: post and recieve without refresh
                                      TimSymons Level 1
                                      Yeah, sorry about that I got confused in your code until I copied and pasted into Flash. I wasn't sure where some of you functions ended.

                                      I changed my post. Here is my next question:

                                      How are you sending back a response from your PHP file? In the last sample of PHP code you posted you have:

                                      echo $xml_output;

                                      Which return the string you created back to Flash when you use the sendAndLoad() method.

                                      This would be returned to the variable "response". The unescape routine would be more suited to that.

                                      Sorry for mis-reading your post. :-)

                                      Tim
                                      • 16. Re: post and recieve without refresh
                                        TimSymons Level 1
                                        Also, I am certain that you program is getting a little confused on scoping. Since you defined xmlData out side of any function and the loadXML function is defined on the main level then your doThisOnResponse function should be able to reduce to just this:

                                        function doThisOnResponse(result) {
                                        if (result) {
                                        xmlData.load(" http://chaliedoskope.com/talk/swfshout/shout.php?cache="+cache);
                                        } else {
                                        trace("Invalid response.");
                                        }
                                        }


                                        Tim
                                        • 17. Re: post and recieve without refresh
                                          w4rts Level 1
                                          yeah, the last line of the php reads echo ("$xml_output"); but it returns the whole select query (which is what I want, I think). I wan't the php file to return all of the data requested from the DB plus the message just entered after the POST.

                                          So when I do trace(result); it returns all of the xml. (Except that the POST isn't working; I have to hit the send button twice.)

                                          Here is everything I've got. And no worries about miss-reading the code; I'm just super-happy to get some help. Much thanks...
                                          • 18. post and recieve without refresh
                                            TimSymons Level 1
                                            The first thing I just noticed was that I think your PHP code is a little out of order. I have re-ordered it and added comments about stuff. Look at it and let me know if the order and my comments make sense.


                                            Tim

                                            • 19. Re: post and recieve without refresh
                                              w4rts Level 1
                                              OK, so I replaced the php you gave me, now when I trace result, I just get the boolean true again.

                                              I tried

                                              var myResults:String = unescape(result);
                                              var myXML:XML = new XML();
                                              myXML.parseXML(myResults);
                                              trace(myResults);

                                              and again, get the boolean. I'm at a total loss....

                                              Also, the order of the php didn't effect the need to click the submit button twice before the data gets submitted. It's strange, though, because I can't just hit the button twice, I have to actually pass data twice. eg I enter "asdf" and hit submit; data not there. hit submit again; data not there. enter "qwert" and hit submit; "asdf" shows up.

                                              It's all really confusing.

                                              Thanks for trying, Tim.
                                              • 20. Re: post and recieve without refresh
                                                TimSymons Level 1
                                                Just a quick tip. Trace "response" not "result", that was what I mis-read last time.

                                                Instead of

                                                var myResults:String = unescape(result);
                                                var myXML:XML = new XML();
                                                myXML.parseXML(myResults);
                                                trace(myResults);

                                                use this:

                                                var myResults:String = unescape(response);
                                                var myXML:XML = new XML();
                                                myXML.parseXML(myResults);
                                                trace(myResults);

                                                I will look at the double-button hit again.

                                                Tim
                                                • 21. Re: post and recieve without refresh
                                                  w4rts Level 1
                                                  Very cool... can't believe I missed that. Well, yeah I can; I think my eyes are starting to bleed ;) So that returns the pretty, well-formatted xml (except, for some reason it's adding "</shouts>=&onLoad=[type Function]" at the end of the xml... don't know if that will affect the page; and it's not returning the text posted).

                                                  Not really sure how to fix the double post thing, and not sure how to get myResult to replace the current data. Maybe some kind of refresh on the page every few seconds...?

                                                  Thanks again, Tim :)
                                                  • 22. Re: post and recieve without refresh
                                                    TimSymons Level 1
                                                    The refresh method will work, though it is server intensive to have a DB request every few seconds.

                                                    The addition of the "=&onLoad=[type Function'" is always there for the LoadVars variables on returned items. Before you use the parseXML() method you can strip out that stuff by using the following:

                                                    var tempResults:String = unescape(response);
                                                    var myResults:String = String(tempResults.split("=&onLoad").shift());
                                                    var myXML:XML = new XML();
                                                    myXML.parseXML(myResults);
                                                    trace(myResults);

                                                    The new line will turn the string into an array and the shift() method get the first element of the array. The String() method is just to make sure Flash doesn't give you a string of type [Object].

                                                    Tim
                                                    • 23. Re: post and recieve without refresh
                                                      TimSymons Level 1
                                                      Now that you have results coming into Flash, let's focus on the PHP part. In your Flash movie, comment out the sendAndLoad command and change it to just a "send()" command. This way output from the PHP file will display in the browser window and you will be able to debug it better.

                                                      I have attached some code. Let me know what output you get when you test the $result from the INSERT statement.

                                                      Tim



                                                      • 24. Re: post and recieve without refresh
                                                        w4rts Level 1
                                                        I tried to get that to work, but it seems that the XML take precedence, and displays the node tree.

                                                        I deleted the xml code, and tried again, but got a XML Parsing Error from the header, so I deleted that. With all of that gone, I tried again, and am met with a blank screen, which I assume means there is no error.
                                                        • 25. Re: post and recieve without refresh
                                                          TimSymons Level 1
                                                          That's what I would take it to mean too. Well, at this point I don't have much more to add except to try and echo out all of the variables you passed to the PHP file and then echo out the $result variable too.

                                                          Sorry I don't have much more to offer.

                                                          Tim
                                                          • 26. Re: post and recieve without refresh
                                                            w4rts Level 1
                                                            I was reading back, and totally missed your post on how you were doing the blog you created. I'm thinking that, as you said, the constant refreshing to the DB would be pretty intensive.

                                                            So you think that the file-writing approach would be less stranious on the sever? And do you think there is a way to instead of having it constantly refresh, have it refresh only when new dta is added to the file?

                                                            If this is possible, I'm thinking I'd probably prefer to battle it out trying to get that to work, despite all the time already invested in the current application.

                                                            When beginning this project, I was hoping that the fact that I know quite a bit more about AS then php (obviously not that much ;), it'd be easier to get this working instead of an ajax-y type of shoutbox.

                                                            Anyways, I really appreciate the time you put in trying to give me a hand. Even though it's not working, I've still learned a bit, and the more you know...

                                                            cheers

                                                            aj
                                                            • 27. post and recieve without refresh
                                                              jonnybennett Level 1
                                                              i dont really understand xml, however I have done this for you to take a look at, this does it with php only. Check out:

                                                              http://www.cretepropertyconsultant.com/forumHelp/shout.html


                                                              The actionscript is all on the main timeline:

                                                              sendShout=new LoadVars();
                                                              loadShouts=new LoadVars();

                                                              sendBtn.onRelease=function(){
                                                              sendShout.id='11111';
                                                              sendShout.userName='jono';
                                                              sendShout.newShoutMessage=newShout.text;
                                                              sendShout.sendAndLoad('shouts.php',loadShouts,'POST');}

                                                              loadShouts.onLoad=function(){
                                                              allShouts.text='';
                                                              idArray=this.idToFlash;
                                                              nameArray=this.nameToFlash;
                                                              timeArray=this.timeToFlash;
                                                              messageArray=this.messageToFlash;
                                                              splitArrays();}

                                                              function splitArrays(){
                                                              idArray2=idArray.split('|');
                                                              nameArray2=nameArray.split('|');
                                                              timeArray2=timeArray.split('|');
                                                              messageArray2=messageArray.split('|');
                                                              setTheText();
                                                              }

                                                              function setTheText(){
                                                              for (p=0;p<idArray2.length-1;p++){
                                                              allShouts.text+='id:'+idArray2[p]+' name: '+nameArray2[p]+' time: '+timeArray2[p]+' message: '+messageArray2[p]+' \r';}}


                                                              setInterval(updateShouts,1000);

                                                              loadShouts3=new LoadVars();

                                                              function updateShouts(){
                                                              loadShouts2=new LoadVars();
                                                              loadShouts2.nothing='';
                                                              loadShouts2.sendAndLoad('shoutsUpdating.php',loadShouts,'POST');}



                                                              ////////////////////// shout.php ////////////////////////////////////////////////////////////////////////


                                                              <?

                                                              $username=$_POST['userName'];
                                                              $id=$_POST['id'];
                                                              $message=$_POST['newShoutMessage'];

                                                              $user2="*****";
                                                              $password2="*******";
                                                              $database="shoutbox";
                                                              $connection = mysql_connect("localhost",$user2,$password2)or die("Unable to connect to database");
                                                              mysql_select_db($database,$connection) or die ("Unable to select database");

                                                              $sql1="INSERT INTO shoutbox (id,name,time,message) VALUES ('$id','$username',NOW(),'$message')";
                                                              $sql1_result = mysql_query($sql1,$connection)or die ("couldnt execute query 4. Reason - ".mysql_error());

                                                              $sql = "SELECT * FROM shoutbox";
                                                              $sql_result = mysql_query($sql,$connection)or die ("couldnt execute query 4. Reason - ".mysql_error());

                                                              print '&shoutsFromPhp=';


                                                              while ($row = mysql_fetch_array ($sql_result)) {
                                                              $ary[]=$row["id"];
                                                              $ary1[]=$row["name"];
                                                              $ary2[]=$row["time"];
                                                              $ary3[]=$row["message"];}


                                                              $numElements = count($ary);

                                                              print "&idToFlash=";
                                                              for($counter=0; $counter < $numElements; $counter++)
                                                              {print "$ary[$counter]|";}

                                                              print "&nameToFlash=";
                                                              for($counter=0; $counter < $numElements; $counter++)
                                                              {print "$ary1[$counter]|";}

                                                              print "&timeToFlash=";
                                                              for($counter=0; $counter < $numElements; $counter++)
                                                              {print "$ary2[$counter]|";}

                                                              print "&messageToFlash=";
                                                              for($counter=0; $counter < $numElements; $counter++)
                                                              {print "$ary3[$counter]|";}




                                                              ?>


                                                              ////////////////////// shoutUpdating.php ////////////////////////////////////////////////////////////////////////

                                                              <?
                                                              $nowt=$_POST['nothing'];

                                                              $user2="*****";
                                                              $password2="*******";
                                                              $database="shoutbox";
                                                              $connection = mysql_connect("localhost",$user2,$password2)or die("Unable to connect to database");
                                                              mysql_select_db($database,$connection) or die ("Unable to select database");

                                                              $sql = "SELECT * FROM shoutbox";
                                                              $sql_result = mysql_query($sql,$connection)or die ("couldnt execute query 4. Reason - ".mysql_error());


                                                              while ($row = mysql_fetch_array ($sql_result)) {
                                                              $ary[]=$row["id"];
                                                              $ary1[]=$row["name"];
                                                              $ary2[]=$row["time"];
                                                              $ary3[]=$row["message"];}


                                                              $numElements = count($ary);

                                                              print "&idToFlash=";
                                                              for($counter=0; $counter < $numElements; $counter++)
                                                              {print "$ary[$counter]|";}

                                                              print "&nameToFlash=";
                                                              for($counter=0; $counter < $numElements; $counter++)
                                                              {print "$ary1[$counter]|";}

                                                              print "&timeToFlash=";
                                                              for($counter=0; $counter < $numElements; $counter++)
                                                              {print "$ary2[$counter]|";}

                                                              print "&messageToFlash=";
                                                              for($counter=0; $counter < $numElements; $counter++)
                                                              {print "$ary3[$counter]|";}


                                                              mysql_close();

                                                              ?>


                                                              • 28. Re: post and recieve without refresh
                                                                w4rts Level 1
                                                                Thanks very much for the help. It is working (minus a few more tweaks).

                                                                The only issue is that the constant refreshes to the database is really bogging down the system. Is there a way to modify this script so that it only refreshes when someone adds a new comment? I know it'd be easy for the person making the comment, but if others are connected as well is there a way to have the php trigger an update to all connected clients?

                                                                Or even better would be to modify the script to write directly to a php file instead of the database?

                                                                Any help would be greatly appreciated.

                                                                regards,

                                                                aj
                                                                • 29. Re: post and recieve without refresh
                                                                  jonnybennett Level 1
                                                                  I don't know of another way... if there is one I would also like to know.

                                                                  You could use php to write to a file. However you are going to still need to use the constant refreshs to get php to constantly check the file to see if their are any new messages, in the same way it searches the database.

                                                                  The only way I can see that a user can find out it a new message has been posted is if that user is checking the database themselves for any new messages.

                                                                  You could slow down the amount of time between refreshes. So that each user only queries the database once a minute, however if it is an actual chat system you are trying to create waiting a minute for a new message could be somewhat painfull!!!.

                                                                  I am fairly new to this, so if someone knows a way for a database to contact a user I would also like to know. j.
                                                                  • 30. Re: post and recieve without refresh
                                                                    cside
                                                                    you're right that you have to get rid of the sql queries. you want to write the data to txt files.

                                                                    clients can load and reload text files over and over, every second if you want, with no load on server other than bandwidth.

                                                                    you can use a datase to manage the files if you want but you don't need a database at all. you can store all the info in text files. all your conversations will be saved and easy to maintain.

                                                                    .....after all, that's all that the database is doing anyways, storing text.
                                                                    • 31. Re: post and recieve without refresh
                                                                      w4rts Level 1
                                                                      Yeah, that's what I was thinking.

                                                                      Can anyone see an easy way to modify this script to write to some type of text file instead of a database?

                                                                      Much thanks.
                                                                      • 32. Re: post and recieve without refresh
                                                                        w4rts Level 1
                                                                        Yeah, that's what I was thinking.

                                                                        Can anyone see an easy way to modify this script to write to some type of text file instead of a database?

                                                                        Much thanks.