Jump to content

Ajax & PHP Help


MRGRIM

Recommended Posts

Ok, I've started to play around with Ajax (I am a late adopter I know), I found a PHP/Ajax example on W3Schools, the example works fine when I recreate it, but when I try and fudge it into my code it doesn’t work (I prefer to work/learn by copying examples, pushing and peeking etc – so the go read a book/Google doesn’t work as well for me – though I did start reading “Beginning PHP and MySQL E Commerce 2nd Edition” Published by Apres, it has a very similar example.

Anyway, what I currently have is a user message system, where site users can send each other short messages (PM’s basically) this works fine, everything is dandy. I have a JavaScript function that allows the user to hide or show the message body (collapses or expands the content) similar to what they do at Iso Hunt, so I figured this would be an excellent opportunity to try my hand at some Ajax and actually get the status of the message updated and saved (Collapsed or Expanded) sounds simple enough, no?

Now my site is currently laid out as follows;-

Root

-Index.php

[scripts]

-DB Connection.php

-Message Class.php

[Modules]

-Message Function.php

(So that’s Root/Index.php, Root/Scripts/DB Connection.php, Root/Modules/Message Function.php etc)

I hope this will make sense to someone, this started out as a small Friday night code mash up a few weeks ago, now I seem to be spending all my spare time hitting my head against the wall.

I need some help with debugging what's going on in the Javascript, at the moment my message hide and show works, but It looks like the Ajax side of things isn't working :(

Index.php

<?php session_start();
    //Instantiate Session and DB classes
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="css/theme.css" rel="stylesheet" type="text/css" />
   <script type="text/javascript">
   
   var xmlHttp
   
   function getParentElement(elem, searchtag, mid, state)
   {
   
         xmlHttp=GetXmlHttpObject()
        
        if (xmlHttp==null)
         {
             alert ("Browser does not support HTTP Request")
             return
         }
        
        var url="modules/messages.php"
        url=url+"?action=updateMessageStatus"
        url=url+"&mid"+mid
        url=url+"&state="+state
        //creates a random sid to prevent caching
        url=url+"&sid="+Math.random()
    
        xmlHttp.onreadystatechange=stateChanged 
        xmlHttp.open("GET",url,true)
        xmlHttp.send(null)    
    
        while(elem.tagName.toLowerCase() != searchtag)
        {
            if(!elem.parentNode)
                return false;
               elem = elem.parentNode;
        }
     
        return elem;
    }
   
    function stateChanged() 
    { 
        if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
         { 
             //Alert(xmlHttp.responseText)
         } 
    }       

    function GetXmlHttpObject()
    {
    var xmlHttp=null;
    try
     {
     // Firefox, Opera 8.0+, Safari
     xmlHttp=new XMLHttpRequest();
     }
    catch (e)
     {
     //Internet Explorer
     try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
     catch (e)
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
     }
    return xmlHttp;
    }
   </script>
</head>

<body class="">
<p align="right">
    <img src="images/logo.jpg" alt="Logo" width="388" height="135" />
</p>
<br />
<?php
    //Include Menu
?>
<br />
<?php
    //Include modules user has requested
        include(modules/messages.php)    
?>
<br />
<?php
    //Include disclaimer
?>
</body>
</html>

modules/message.php

<?php
    //check if a view is defined
    if (isset($_GET['view']))
    {
        if ($_GET['view']=='inbox')
        {
            include_once('scripts/cMessages.class.php');
            //include_once('scripts/message_functions.php');
            
            //initialise the CCustomers class for usage
            $messages = new CMessages;
                         
            //call the viewAllMessages function (takes the user id of the current user) fixed for testing 
            $messages->viewAllMessages(00001);
                          
        }
    }
    if (isset($_GET['action']))
    {
        if ($_GET['action']=='updateMessageStatus')
        {
            
            include_once('scripts/cMessages.class.php');
            
            $messages = new CMessages;
            
            //use the following fixed message values (i.e. only update the following message, for testing purposes)
            $message_id='0000000005';
            $message_action='1';
            $messages->updateMessageState($message_id, $message_action);
        }
    }    
?>

scripts/cMessages.class.php

<?php

class CMessages extends CDBConn {

//---------------------------------------------------------
//View all messages stored in the DB
        function viewAllMessages($user_id) {
            
            $this->sql = "SELECT * FROM user_messages WHERE to_user_id=".$user_id." and deleted=0 ORDER BY created DESC";
            $this->DBExecute($this->sql);
            
            while($this->row = mysql_fetch_array($this->rs, MYSQL_ASSOC)) 
            {
            
            $hidestatus = $this->row['hide'];
            
            if ($hidestatus==0)
            {
                $hidestatus="opened";
            }
            else
            {
                $hidestatus="closed";
            }
            ?>               
            <table width="100%" cellpadding="0" cellspacing="0">
            <tbody class="<?=$hidestatus?>">
              <tr class="whenclosed" height="25px" valign="top">
                 <td class="bordersmall"><?=$this->row['title'];?> - <i><?=date("H:i d-m-y", strtotime($this->row['created']));?></i></td><td class="bordersmall"><div align="right"><a href="#" onClick="getParentElement(this, 'tbody', '<?=$this->row['message_id'];?>', 'Show').className='opened';return false;">Show</a></div></td>
               </tr>
              <tr class="whenopened" height="25px" valign="top">
                 <td class="bordersmall"><?=$this->row['title'];?> - <i><?=date("H:i d-m-y", strtotime($this->row['created']));?></i></td><td class="bordersmall"><div align="right"><a href="#" onClick="getParentElement(this, 'tbody', '<?=$this->row['message_id'];?>', 'Hide').className='closed';return false;">Hide</a></div></td>
              </tr>
              <tr class="whenopened">
                  <td class="blacktext" colspan="2"><?=$this->row['content'];?><p> </p></td>
               </tr>
            </tbody>
            </table>
            <br />
            <?               
               
            }
        }
//-------------------------------------------------------
        function updateMessageState($message_id, $message_action) 
        {h
           $this->sql = "UPDATE quoteforit.user_messages SET hide=".$message_action." WHERE message_id = ".$message_id;
           $this->DBExecute($this->sql);
        }
};
?>

Link to comment
Share on other sites

Validation will be done once everything is up and running, thanks for the heads up though.

//Do Some Shit Here with xmlHttp.responseText

See this is where I am confused, surely this would just be "Hello World"; ? What my problem is the database isn't getting updated via Ajax. (I could be wrong) but from my understand the .responceText would normally just be a resultant dataset? I don't intend on returning any value, as I just want the DB update to happen slightly in the background.

Link to comment
Share on other sites

        url=url+"&mid"+mid

is there supposed to be an '=' in there?

the only way that i've been able to debug javascript has been by viewing the page through IE and opening the error dialog. it's a pain.

Link to comment
Share on other sites

url=url+"&mid"+mid

Errrm yeah in the quotes there should be :blink: I'll go modify that now... not sure if that would cause a problem though, seen as the function the other end isn't using the data I'm passing it at the moment.

Debugging it is a pain, however IE is not showing me any JS errors, so it's me whos doing something wrong :)

Right ok, we seem to be onto something I uncommented

Alert(xmlHttp.responseText)

And it started alerting me (not sure if Alert works in FF? Will have to brush up on my JS) but I started to get "failed to includes" PHP errors, so it looks like I know what the problem is, however I'm trying to make my code as reusable as possible, so my problem now is the DB connection is sat in its own DIR. Has anyone got any advice on this? As the AJAX is running from the root and the file its calling is 1 DIR down, so is then going back up to get the DB Connection, yet other functions are running off that, so moving and change path strings is going to make things a real mess. ;) does anyone even know what I am talking about?

Link to comment
Share on other sites

Two suggestions for you:

Firebug addon for Firefox https://addons.mozilla.org/en-US/firefox/addon/1843

and

YUI http://developer.yahoo.com/yui/connection/

Yahoo's YUI is nice because they solve the problems for you, then give you a platform to use. They work out all of the cross-browser crap and deal with a lot of the javascript bugs and give you something a lot more sane.

Even if you aren't interested in YUI, check out some of the javascript, DOM and Ajax videos, especially the ones by Douglas Crockford. http://developer.yahoo.com/yui/theater/

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...