SitePoint Sponsor

User Tag List

Results 1 to 12 of 12

Thread: ajax shoutbox?

  1. #1
    SitePoint Wizard
    Join Date
    Oct 2005
    Location
    London
    Posts
    1,678
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    ajax shoutbox?

    hi,

    i dont know if this is the correct place to post an ajax question so apologies if it isnt.

    Basically i want to create an ajax shoutbox. One of those things where people input a line of text and click submit and the message shows up...then someone else can reply.

    I have it working in php now but you have to refresh the screen all the time. basically im inputting the data entered ( name, and email, date, time) in to a database on submit and then using another query to select the last five messages entered. It works fine and heres the code:

    PHP Code:
    if($submit) {

       //use the PHP date function for the time
       $time=date("h:ia d/j/y");
        
       $result=MYSQL_QUERY("INSERT INTO shoutbox (id,name,message,time)".
          "VALUES ('NULL','$name', '$message','$time')");
    }

    //and heres the select
    $result = mysql_query("select * from shoutbox order by id desc limit 5");

    //the while loop
    while($r=mysql_fetch_array($result))
    {        
       //getting each variable from the table
       $time=$r["time"]; 
       $id=$r["id"];
       $message=$r["message"];
       $name=$r["name"];
    ?>
       <? echo $time ?><br>
       <? echo $name ?><br>
       <? echo $message ?><br>
    <? ?>
    now im really an ajax and sql virgin but im sure i can pick it up. Any help or suggestion would be appreciated as ive scoured google for this for about an hour this morning without any luck

  2. #2
    SitePoint Zealot
    Join Date
    Jul 2006
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    My suggestion is to use the Jquery library. You can download it from here. You'd just have to add the file you download (jquery.js) as an external JS file.

    How it works is you take your form, and add an onsubmit="return myAjax();" into the form.

    Then you create a function like so in Javascript (probably an external file is a good idea):

    Code:
    function myAjax() {
          // get the value of your data here.  Something like this.
          var text = document.forms["myForm"].elements["myInput"].value;
          //myForm and myInput should be referenced by their name attribute.
           
          // Send the data to your URL via cross-browser Ajax courtesy of Jquery
          $.ajax({ type: "POST", url: "whatever.php", data: text, success: displayMessage});
    
          //Stop the submit event from firing.
          return false;
    }
    
    function displayMessage(msg) {
          if (msg) {
                // reference your chat div by ID
                document.getElementsById("yourChat").innerHTML += msg;
          }
    }
    I think something like this should work...
    Last edited by dwees; Jan 13, 2007 at 05:02. Reason: forgot something

  3. #3
    SitePoint Wizard
    Join Date
    Oct 2005
    Location
    London
    Posts
    1,678
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hi,

    thanks for the prompt reply.

    ill give that a try....coupla things though, as i said im not too good with javascript at the moment. Ive put some comments in the code below.

    PHP Code:
    function myAjax() {
          
    // get the value of your data here.  Something like this.
          
    var text document.forms["myForm"].elements["myInput"].value;
          
    //myForm and myInput should be referenced by their name attribute.
           
          // Send the data to your URL via cross-browser Ajax courtesy of Jquery
         //so this bit is taken care of by the library code? All i need to do is put the address that the form should post to?
      
          
    $.ajax({ type"POST"url"whatever.php"datatextsuccessdisplayMessage});

          
    //Stop the submit event from firing.
          
    return false;
    }

    function 
    displayMessage(msg) {
          if (
    msg) {
    //im sorry i dont quite get whats going on with this bit, could you clarify it a bit? Wheres the displayMessage function being called? Wheres the msg variable?

                // reference your chat div by ID
                  //hows this line working?
                
    document.getElementsById("yourChat").innerHTML += msg;
          }

    thanks

  4. #4
    SitePoint Zealot
    Join Date
    Jul 2006
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sure no sweat.

    Yes, the library handles the function entirely, and I have carefully constructed the statement so it will work with the library, all you will need to do is adjust the URL.

    If you examine that line, you may notice that it says success: displayMessage, this is where the text you send back with the PHP is sent to, so it needs to be processed.

    So I've written a function which takes the text returned by PHP (msg) and adds it to the innerHTML of the chat box (whatever HTML element you are using to display the chat text) which is what the last line of the function does.

    Dave

  5. #5
    SitePoint Wizard
    Join Date
    Oct 2005
    Location
    London
    Posts
    1,678
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi dave,

    Right understanding you now! Ive implemented it but it doesnt seem to work. Any chance you could have a quick peek at what ive done? Ive placed a link to the query.js in the head of my document and this is the snippet of what ive got. Im probably missing something in the inline javascript.

    (apologies for the antiquated code and inline styles! Im just experimenting at the moment!)

    PHP Code:
    <script type="text/javascript">
        
    function myAjax() {
          // get the value of your data here.  Something like this.
          var text = document.forms["myForm"].elements["message"].value;
          //myForm and myInput should be referenced by their name attribute.
           
          // Send the data to your URL via cross-browser Ajax courtesy of Jquery
          $.ajax({ type: "POST", url: "<?php echo $_SERVER['PHP_SELF']; ?>", data: text, success: displayMessage});

          //Stop the submit event from firing.
          return false;
    }

    function displayMessage(msg) {
          if (msg) {
                // reference your chat div by ID
                document.getElementsById("mychat").innerHTML += msg;
          }
    }
    </script>
    <div style="background-color: black; border: 1px solid #ccc; width: 400px; padding: 10px 30px; id="mychat">
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" name="myform" method="post">
    <input type="text" name="message" />
    <input type="submit" class="submit" name="submitchat" value="submit post" /> 
    </form>
    <?php 

    if(isset($_POST['submitchat'])) {
        
    $submitchat $_POST['submitchat'];


    if(isset(
    $_POST['message'])) {
        
    $message $_POST['message'];
    }

    }

    if(
    $message) {





    $name = ($_SESSION['first_name']);

      
    //use the PHP date function for the time
      
    $time=date("h:ia d/j/y");
      require_once (
    'mysql_connect.php'); // Connect to the db.

      
    $sql"INSERT INTO shoutbox(shout_id, name, message, time) VALUES ('NULL','$name', '$message','$time')";
      
    $result mysql_query($sql);
      
    }

    //and heres the select
    $sql "select * from shoutbox order by shout_id desc limit 5";
    $result mysql_query($sql);

    while(
    $row mysql_fetch_array($result)) 
    //the while loop

    {        
       
    //getting each variable from the table
       
    $time=$row["time"];
       
    $id=$row["id"];
       
    $message=$row["message"];
       
    $name=$row["name"];
    ?>
       
           
      
       <p style="color: white"><em style="color: green; font-weight:bold; display: inline; margin-right: 5px;"> <? echo $name ?>:</em><? echo $message ?></p>
     
    <? ?>
     </div>

  6. #6
    SitePoint Zealot
    Join Date
    Jul 2006
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hrmm. I would separate your logic a bit more.

    Create a regular HTML page (or PHP emulating HTML) and a separate PHP file that handles the database query. Inside this PHP file, have it generate the HTML you want displayed inside the chatbox div. Also, if you probably want the form to show up underneath the chatbox div and have its action be the additional PHP file from before. This is so that if Javascript is disabled in your users browser, you can have it degrade to what you had before.

  7. #7
    SitePoint Wizard
    Join Date
    Oct 2005
    Location
    London
    Posts
    1,678
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    right, ok , Thanks for the tip about moving the code for users that dont have JS enabled, ill do that now

    do you think thats the reason its not working is the seperation of logic? The php version works all within that one script, so thats working fine. Its just the JS isnt working so i assumed that id done something wrong with the function that you wrote.

    what do you think?

  8. #8
    SitePoint Zealot
    Join Date
    Jul 2006
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well I guess I need to know more information than I have.

    The way I see it, your current script calls itself to do the update, which is fine when you are using PHP + HTML. However, when you are using Ajax, you actually just want to update just the chat window box.

    Also I see another error. You will want to add this line:

    Code:
    function myAjax() {
          // get the value of your data here.  Something like this.
          var text = document.forms["myForm"].elements["message"].value;
          //myForm and myInput should be referenced by their name attribute.
           
          // turn the text variable into something resembling a POST variable
          text = "message=" + text;
    
          // Send the data to your URL via cross-browser Ajax courtesy of Jquery
          $.ajax({ type: "POST", url: "<?php echo $_SERVER['PHP_SELF']; ?>", data: text, success: displayMessage});
    
          //Stop the submit event from firing.
          return false;
    }
    Also, this means that 'submitchat' will no longer show up as a POST variable.

    Since you do no want to change your existing code which currently allows for the user not having Javascript enabled, I suggest you create a new Php script, and put a copy of all of the logic that creates the HTML just inside of the chat box.

    Dave

  9. #9
    SitePoint Wizard
    Join Date
    Oct 2005
    Location
    London
    Posts
    1,678
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    im sorry dave, im lost, how do i put all the code that contains the logic creating the html for the chatbox in another php file. How would the main page access it? Would i use an include or something?

  10. #10
    SitePoint Zealot
    Join Date
    Jul 2006
    Posts
    151
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You could put something like this:

    Code:
    <?php
    if(!isset($_POST['ajaxrequest'])) {
         if (isset($_POST['submitchat']) { include('your_other_php_file.php?submitchat='.$_POST['submitchat'].'&message='$_POST['message']);
    } else {
            include('your_other_php_file.php');
    }
    ?>
    Put this as a PHP island inside your chat box, and then have the external file create all of the HTML.

    If the page is reloaded, the $_POST variables get passed along as $_GET variables (if this doesn't work, you'd have to use CURL here instead...) to the chat script. If the page isn't reloaded, and Javascript is enabled, then Ajax will call directly to the external script, using the correct variables, and have the appropriate HTML, just for the chat box, returned.

    Does this make any sense?

  11. #11
    SitePoint Wizard
    Join Date
    Oct 2005
    Location
    London
    Posts
    1,678
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    HI Dave,

    Ive decided that im going to go and learn some AJAX and try and achieve this myself as its something i definately need to know anyway!

    Thanks for your help, i really appreciate it

  12. #12
    SitePoint Member
    Join Date
    Jan 2007
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have a question, how could I make it so the shoutbox refreshes whenever there's a new post?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •