10 Replies Latest reply on Feb 27, 2012 7:08 AM by Smoke Hyzbade

    Issue with online dynamic property (like Ajax for HTML).

    Smoke Hyzbade

      Hi!

       

      I am creating my own website, and I have choosed to create it in Flex 4.6.

      But, I have got an issue with his online dynamic property (like Ajax for HTML).

       

      Thus, I am looking for a solution to this problem:

       

      1. Create a checkbox and put it online

       

      <?xml version="1.0"?>

      <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"

          xmlns:s="library://ns.adobe.com/flex/spark"

          xmlns:mx="library://ns.adobe.com/flex/mx">

       

           <s:VGroup>

                <s:CheckBox width="100" label="Check me!" />

           </s:VGroup>


      </s:Application>


      2. Two people connect (so they will each see the checkbox)

       

      3. When one changes checkbox's state (checked / unchecked), the other one must see the state changement.

       

       

      Best regards

       

       

      --

       

       

      Smoke Hyzbade

        • 1. Re: Issue with online dynamic property (like Ajax for HTML).
          Sathyamoorthi Level 2

          changes should be co-ordinated with server side scripting.

           

          choose your serverside scripting language.

          • 2. Re: Issue with online dynamic property (like Ajax for HTML).
            Smoke Hyzbade Level 1

            My serverside scripting language is PHP, but I can change with ActionScript.

            Could you give me some clues for the script please?

            • 3. Re: Issue with online dynamic property (like Ajax for HTML).
              Sathyamoorthi Level 2

              hi,

               

              Whenever a change occured, send it to server write the change into a file. Always listen that file at certain timeiintervel, if change occured send reflect that data to all Flex UIs.

               

              you can use Database instead of file. it is depends on your need.

              • 4. Re: Issue with online dynamic property (like Ajax for HTML).
                Smoke Hyzbade Level 1

                Hi!

                You are right, I am used to code in Ajax and, by the way, do you know an object in ActionScript like HttpRequest in Ajax?

                If I want to create a chat on my website with a simple database. Imagine two TextAreas, the first (not editable) showing the full database like this : [pseudo] : [message], and second (editable) where user writes his message, and a button to send the message.

                I write into my database with successful, but if you are connecting on my website too, you do not see the changing directly (you must refresh).

                So, I become crazy with this problem! With Ajax, it's easiest. I take it I forgot something in my Flex's learning.

                 

                Could you help me again?

                • 6. Re: Issue with online dynamic property (like Ajax for HTML).
                  Smoke Hyzbade Level 1

                  I am already using HTTPService but with no success.

                  To be continued...

                  • 8. Re: Issue with online dynamic property (like Ajax for HTML).
                    Smoke Hyzbade Level 1

                    You are right

                     

                    MXML file :

                    in your flex project

                    <?xml version="1.0" encoding="utf-8"?>

                    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"

                                   xmlns:s="library://ns.adobe.com/flex/spark"

                                   xmlns:mx="library://ns.adobe.com/flex/mx"

                                   width="400" height="400" backgroundColor="#DEDEDE"

                                   creationComplete="init()">

                        <fx:Declarations>

                            <s:HTTPService

                                id="chatRequest"

                                url="http://localhost/Chat/request.php"

                                useProxy="false"

                                method="POST"

                                result="{resultHandler(event)}"

                                fault="{faultHandler(event)}">

                            </s:HTTPService>

                        </fx:Declarations>

                     

                        <fx:Script>

                            <![CDATA[

                                import mx.controls.Alert;

                                import mx.rpc.events.FaultEvent;

                                import mx.rpc.events.ResultEvent;

                     

                                /**

                                 * Envoi d'une requête à l'initialisation de l'application

                                 * Send a request to the application initialization

                                 */

                                public function init():void {

                                    // @ et @ est un cas spécifique, à voir dans le PHP

                                    // @ and @ is a specific case, look it on PHP file

                                    chatRequest.send({

                                        pseudo : "@",

                                        message : "@"

                                    });

                                }

                     

                                /**

                                 * Envoi la requête si un pseudo et un message sont biens remplis

                                 * Send request if nickname and message properties are filled

                                 */

                                public function httpRequest():void {

                                    // Si il n'y pas de message

                                    // If there are no message

                                    if( !message.text.match(/.+/) ) {

                                        Alert.show("If you want to chat, you must write a message!");

                                    }

                                    // Si le pseudo n'a pas trois caractères minimum

                                    // If the nickname is not three characters minimum

                                    else if( !message.text.match(/\w{3,}/) ) {

                                        Alert.show("If you want to chat, we need to know who you are!");

                                    }

                                    // Sinon nous envoyons la requete

                                    // Else we send the request

                                    else {

                                        chatRequest.send({

                                            pseudo : pseudo.text,

                                            message : message.text

                                        });

                                        pseudo.text = "";

                                        message.text = "";

                                    }

                                }

                     

                                public function resultHandler(event : ResultEvent):void {

                                    chat.text = "---\n";

                                    myDatagrid.selectedIndex = 0;

                                    for(var i=0 ; i<myDatagrid.selectedItem.count ; i++) {

                                        myDatagrid.selectedIndex = i;

                                        chat.text += "[" + myDatagrid.selectedItem.pseudo + "] : ";

                                        chat.text += myDatagrid.selectedItem.message + "\n";

                                    }

                                }

                                private function faultHandler(event : FaultEvent):void {

                                    Alert.show("F\n"+event.statusCode.toString() + "\n" + event.fault.message.toString());

                                }

                     

                            ]]>

                        </fx:Script>

                     

                        <s:TextArea id="message" x="10" y="340" width="302" height="50" prompt="Your message!"/>

                        <s:Button id="send" x="320" y="369" label="Envoyer" cornerRadius="10" click="httpRequest()"/>

                        <s:TextArea id="chat" x="10" y="10" width="380" height="322" editable="false"/>

                        <s:TextInput id="pseudo" x="320" y="340" width="70" prompt="Pseudo"/>

                     

                        <mx:DataGrid id="myDatagrid" visible="false" dataProvider="{chatRequest.lastResult.messages.messagepseudo}">

                            <mx:columns>

                                <mx:DataGridColumn dataField="message" headerText="Message"/>

                                <mx:DataGridColumn dataField="pseudo" headerText="Nickname"/>

                            </mx:columns>

                        </mx:DataGrid>

                    </s:Application>

                     

                    PHP file :

                    C:\wamp\www\Chat\request.php

                     

                    <?php

                    ## Nos deux variables doivent être initialisées

                    ## Our two variables must be initialized

                    if( isset($_POST['pseudo']) && isset($_POST['message']) ) {

                     

                        ## On définit les constantes

                        ## We define the constants

                        define( "DATABASE_SERVER", "localhost", false );

                        define( "DATABASE_USERNAME", "root", false );

                        define( "DATABASE_PASSWORD", "", false );

                        define( "DATABASE_NAME", "Chat", false );

                     

                        ## Connexion

                        ## Connection

                        $mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD);

                        mysql_select_db( DATABASE_NAME );

                     

                        ## Si nous ne sommes pas dans le cas spécial à l'initialisation de l'application

                        ## If we are not in the special case in the application initialization

                        if( ($_POST['pseudo']!="@") && ($_POST['message']!="@") ) {

                            ## Requête SQL

                            ## SQL request

                            $query = "INSERT INTO `discussion` (`message`, `pseudo`) VALUES ('" . $_POST['message'] . "', '" . $_POST['pseudo'] . "')";

                            $result = mysql_query( $query );

                        }

                     

                        $query = "SELECT COUNT(*) AS n FROM `discussion`";

                        $result = mysql_query( $query );

                     

                        $count = mysql_fetch_object( $result );

                     

                        $return = "<messages>";   

                     

                        ## Retourne la liste de la discussion

                        ## Return all the chat

                        $query = "SELECT * FROM `discussion`";

                        $result = mysql_query( $query );

                     

                        while ( $message = mysql_fetch_object( $result ) ) {

                            $return .= "<messagepseudo>";

                            $return .= "<message>" . $message->message . "</message>";

                            $return .= "<pseudo>" . $message->pseudo . "</pseudo>";

                            $return .= "<count>" . $count->n . "</count>";

                            $return .= "</messagepseudo>";

                        }

                     

                        $return .= "</messages>";

                     

                        print ( $return ) ;

                    }

                    ?>

                     

                    And DB ^^

                     

                    -- phpMyAdmin SQL Dump

                    -- version 3.4.9

                    -- http://www.phpmyadmin.net

                    --

                    -- Client: localhost

                    -- Généré le : Ven 24 Février 2012 à 15:57

                    -- Version du serveur: 5.5.20

                    -- Version de PHP: 5.3.9

                     

                    SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

                    SET time_zone = "+00:00";

                     

                     

                    /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;

                    /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;

                    /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;

                    /*!40101 SET NAMES utf8 */;

                     

                    --

                    -- Base de données: `chat`

                    --

                     

                    -- --------------------------------------------------------

                     

                    --

                    -- Structure de la table `discussion`

                    --

                     

                    CREATE TABLE IF NOT EXISTS `discussion` (

                      `message` varchar(1023) NOT NULL,

                      `pseudo` varchar(127) NOT NULL,

                      `hour` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

                    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

                     

                    --

                    -- Contenu de la table `discussion`

                    --

                     

                    INSERT INTO `discussion` (`message`, `pseudo`, `hour`) VALUES

                    ('Coucou', 'HyzLocal', '2012-02-24 08:21:58')

                    ;

                     

                    /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;

                    /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;

                    /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

                     

                    Thank you Sathyamoorthi!

                    • 9. Re: Issue with online dynamic property (like Ajax for HTML).
                      Sathyamoorthi Level 2

                      hi,

                       

                      i really don't have time to help you with that big code.

                       

                      here is a simple example. i wrote very samll sample for you. it is working good.

                       

                       

                       

                      <?xml version="1.0" encoding="utf-8"?>

                      <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"

                                     xmlns:s="library://ns.adobe.com/flex/spark"

                                     xmlns:mx="library://ns.adobe.com/flex/halo">

                         

                          <fx:Declarations>

                              <s:HTTPService id="userRequest" url="http://localhost/Flex.php"

                                                                          useProxy="false" method="GET" result="HTTPResultHandler(event)">                  

                              </s:HTTPService>

                          </fx:Declarations>

                         

                          <fx:Script>

                              <![CDATA[

                              import mx.rpc.events.ResultEvent;

                              import mx.rpc.events.FaultEvent;

                              import mx.controls.Alert;

                             

                              private function Login():void

                              {   

                                  var objParam:Object = { };

                       

                                  objParam['key'] = txtKey.text;

                                 

                                  userRequest.resultFormat = "e4x";

                                  userRequest.useProxy = false;

                                  userRequest.addEventListener(FaultEvent.FAULT , function(event:FaultEvent):void {Alert.show(event.fault.toString())});               

                                  userRequest.send(objParam);

                              }

                             

                              private function HTTPResultHandler(event:ResultEvent):void       

                              {

                                  Alert.show(event.message.body.toString());

                              }

                             

                              ]]>

                          </fx:Script>

                         

                          <s:HGroup width="100%" height="100%" verticalAlign="middle" horizontalAlign="center">

                              <s:TextInput id="txtKey" text="001" maxChars="10"></s:TextInput>

                              <s:Button label="Login" click="Login()"></s:Button>   

                          </s:HGroup>

                      </s:Application>

                       

                       

                       

                      <?php

                      if(isset($_GET['key']) && $_GET['key'] == "001")

                      {

                          echo "Login Sucess..";

                      }

                      else

                      {

                          echo "Something went wrong..";

                      }

                      ?>

                       

                       

                      All you want is basic flex and php knowledge.

                      • 10. Re: Issue with online dynamic property (like Ajax for HTML).
                        Smoke Hyzbade Level 1

                        Thank you, but your answer does not help me.

                        If I look at your example, I need (when I open Chrome and Firefox browsers) when I click on your button, the message appears simultaneously in both browser.

                         

                        Thank you again for the time you take to solve my problem.