Go Back   CodingForums.com > :: Client side development > JavaScript programming > Ajax and Design

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rating: Thread Rating: 10 votes, 3.60 average.
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 05-13-2007, 05:43 PM   PM User | #1
thesmart1
Regular Coder

 
thesmart1's Avatar
 
Join Date: Dec 2005
Posts: 369
Thanks: 7
Thanked 3 Times in 3 Posts
thesmart1 is an unknown quantity at this point
Add Comment Form Not Working

I'm trying to add a comments system to a page on my site. Users will add a comment using a form and submit it using AJAX. I already have a ratings system that works in a similar way. I can't seem to get the add comment form to work, though. It just tries to load the current url with the specified variables attached. Could the two AJAX items be conflicting?

The page:
PHP Code:
<?php include("headtags.php"); ?>
        <title>Red Hat Entertainment - Playing - <?php echo $_GET["movie"]; ?></title>
        <link rel="stylesheet" type="text/css" href="play.css" />
        <script type="text/javascript"><!--
            var xmlHttp
            function addrating(str){
                xmlHttp=GetXmlHttpObject()
                if (xmlHttp==null){
                    alert("Your browser doesn't support the technology required for this function.")
                    return
                }
                var url="add_user_rating.php"
                url=url+"?movie=<?php echo $_GET['movie']; ?>&rating="+str
                url=url+"&sid="+Math.random()
                //xmlHttp.onreadystatechange=stateChanged
                xmlHttp.open("GET",url,true)
                xmlHttp.send(null)
            }
            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>
        <script type="text/javascript"><!--
            var xmlHttp
            function addcomment(name,comment){
                xmlHttp=GetXmlHttpObject()
                if (xmlHttp==null){
                    alert("Your browser doesn't support the technology required for this function.")
                    return
                }
                var url="add_comment.php"
                url=url+"?movie=<?php echo $_GET['movie']; ?>&name="+name+"&comment="+comment
                comurl=comurl+"&sid="+Math.random()
                //xmlHttp.onreadystatechange=stateChanged
                xmlHttpcom.open("GET",url,true)
                xmlHttpcom.send(null)
            }
            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>
        <div class="header">
            <?php include("header.php"); ?>
        </div>
        <div class="navbar">
            <?php include("nav.php"); ?>
        </div>
        <div class="main">
            <div>
                <?php
                
if ($_GET["movie"]==null || $_GET["quality"]==null){
                    echo 
"No movie and/or quality was specified.";
                    }
                else {
                    echo 
'<embed name="MediaPlayer" type="application/x-mplayer2" autostart="1" loop="false" displaysize="4" pluginspage="http://www.microsoft.com/windows/mediaplayer/en/download/" ShowTracker="1" ShowControls="1" ShowStatusBar="0" EnableContextMenu="0" src="movies/'.$_GET["movie"].'/'.$_GET["movie"].'_'.$_GET["quality"].'.wmv" class="player">';
                    }
                
?>
                <div class="info">
                    <h2><?php echo $_GET['movie']; ?></h2>
                    <p>
                        <br />
                        <?php
                            
if ($_GET["movie"]!=null && $_GET["quality"]!=null){
                                include(
'disp_user_rating.php');
                                
$aurwidth=$aur*25;
                                if (
$aur!=0){
                                    
$aurating=$aur.'/5.0 stars';
                                }
                                else {
                                    
$aurating='Not Yet Rated';
                                }
                                echo 
'Average User Rating: <div class="aur" style="position:relative;left:20px;width:125px;height:23px;z-index:4;overflow:hidden;"><div><img src="stars.gif" alt="'.$aurating.'" title="'.$aurating.'" style="position:relative;z-index:3;" /><div style="position:relative;left:0px;top:-30px;background-color:#ffcc00;height:34px;width:'.$aurwidth.'px;z-index:2;"></div></div></div><br />';
                            }
                        
?>
                        <form>
                            <select name="ratingselect" onchange="addrating(this.value)">
                                <option value="null" selected="selected">Rate this movie</option>
                                <option value="1">1 (Worst)</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                                <option value="5">5 (Best)</option>
                            </select>
                        </form>
                </div>
            </div>
            <div class="comments">
                <table>
                    <tr><td><h3>Comments</h3></td></tr><?php
                        $commentdblink
=mysql_connect('h50mysql11.secureserver.net','rhe_data','*****')
                            or die(
'Failed to log your view. Please notify webmaster at <a href="mailto:rhe@pehjota.com">rhe@pehjota.com</a> and include the code "comhostcon".');
                        
mysql_select_db('rhe_data')
                            or die(
'Failed to log your view. Please notify webmaster at <a href="mailto:rhe@pehjota.com">rhe@pehjota.com</a> and include the code "comdbsel".');
                        
$commentresult=mysql_query('SELECT * FROM comments WHERE movie="'.$_GET['movie'].'"')
                            or die(
'Failed to load views. Please notify webmaster at <a href="mailto:rhe@pehjota.com">rhe@pehjota.com</a> and include the code "comquerysel".');
                        while (
$row mysql_fetch_array($commentresult)){
                            
$datetime=$row['datetime'];
                            
$name=$row['name'];
                            
$comment=$row['comment'];
                            
$commentid=$row['id'];
                            echo 
"\n\t\t\t\t\t";
                            echo 
'<tr><td>&nbsp;</td></tr>';
                            echo 
"\n\t\t\t\t\t";
                            echo 
'<tr><td><table class="comment"><tr><td class="comname">'.$name.'</td><td class="comdt">'.$datetime.'</td>';
                            if (isset(
$_COOKIE['rhe_block_visit_logging'])){
                                echo 
'<td class="comdel">Del ('.$commentid.')</td>';
                            }
                            echo 
'</tr>';
                            echo 
'<tr><td colspan="';
                            if (isset(
$_COOKIE['rhe_block_visit_logging'])){
                                echo 
'3';
                            }
                            else {
                                echo 
'2';
                            }
                            echo 
'" class="comcom">'.$comment.'</td></tr></td></tr></table>';
                        }
                        echo 
"\n";
                        
mysql_free_result($commentresult);
                        
mysql_close($commentdblink);
                    
?>
                </table>
                <form>
                    Name: <input type="text" name="name" />
                    Comment: <textarea name="comment"></textarea>
                    <input type="submit" onclick="addcomment(name.value,comment.value)" />
                </form>
            </div>
        </div>
    </body>
</html>
<?php include("/home/content/p/e/h/pehjota/html/globalfooter.php"); ?>
thesmart1 is offline   Reply With Quote
Old 05-13-2007, 09:45 PM   PM User | #2
thesmart1
Regular Coder

 
thesmart1's Avatar
 
Join Date: Dec 2005
Posts: 369
Thanks: 7
Thanked 3 Times in 3 Posts
thesmart1 is an unknown quantity at this point
I noticed a problem with it, but it still just loads the current page with the variables attached. The problem was that I didn't have the variables named the same way throughout the script. I fixed that.

Here's the script:
PHP Code:
        <script type="text/javascript"><!--
            var xmlHttpcom
            function addcomment(name,comment){
                xmlHttpcom=GetXmlHttpcomObject()
                if (xmlHttpcom==null){
                    alert("Your browser doesn't support the technology required for this function.")
                    return
                }
                var comurl="add_comment.php?movie=<?php echo $_GET['movie']; ?>&name="+name+"&comment="+comment
                comurl=comurl+"&sid="+Math.random()
                xmlHttpcom.open("GET",comurl,true)
                xmlHttpcom.send(null)
            }
            function GetXmlHttpcomObject(){
                var xmlHttpcom=null;
                try{
                    // Firefox, Opera 8.0+, Safari
                    xmlHttpcom=new XMLHttpRequest();
                }
                catch (e){
                    //Internet Explorer
                    try{
                        xmlHttpcom=new ActiveXObject("Msxml2.XMLHTTP");
                    }
                    catch (e){
                        xmlHttpcom=new ActiveXObject("Microsoft.XMLHTTP");
                    }
                }
                return xmlHttpcom;
            }
        --></script>
And the form:
PHP Code:
                <form>
                    <
h3>Add Comment</h3>
                    
Name: <input type="text" name="name" /><br />
                    
Comment: <textarea name="comment"></textarea><br />
                    <
input type="submit" value="Add Comment" id="postbutton" onclick="disablepostbutton();alert('Thank you! Your comment has been posted.');addcomment(name.value,comment.value);" />
                </
form
I changed the names of the variables (by adding "com") to prevent mix-ups between the two scripts.
thesmart1 is offline   Reply With Quote
Old 05-14-2007, 08:50 AM   PM User | #3
snake_eyes
New Coder

 
Join Date: Mar 2007
Posts: 74
Thanks: 0
Thanked 0 Times in 0 Posts
snake_eyes is an unknown quantity at this point
Smile

Hello,

Quote:
var comurl="add_comment.php?movie=<?php echo $_GET['movie']; ?>&name="+name+"&comment="+comment
base on my knowledge you can't pass php variable into JS, you should pass the variable together the in the head of the function not in function body

Regards
snake_eyes is offline   Reply With Quote
Old 05-14-2007, 02:21 PM   PM User | #4
BonRouge
Regular Coder

 
BonRouge's Avatar
 
Join Date: Mar 2006
Location: Sendai, Japan
Posts: 328
Thanks: 0
Thanked 0 Times in 0 Posts
BonRouge is on a distinguished road
You can put php anywhere you like on your page.
__________________
bonrouge
BonRouge is offline   Reply With Quote
Old 05-17-2007, 10:29 PM   PM User | #5
thesmart1
Regular Coder

 
thesmart1's Avatar
 
Join Date: Dec 2005
Posts: 369
Thanks: 7
Thanked 3 Times in 3 Posts
thesmart1 is an unknown quantity at this point
Any ideas on what's not working?
thesmart1 is offline   Reply With Quote
Old 05-17-2007, 10:59 PM   PM User | #6
rwedge
Regular Coder

 
Join Date: Feb 2005
Posts: 679
Thanks: 0
Thanked 16 Times in 15 Posts
rwedge is on a distinguished road
What does 'comurl' look like when it is sent?
If it has the comment value appended to it correctly, then I would suspect the php script
rwedge is offline   Reply With Quote
Old 05-18-2007, 05:02 AM   PM User | #7
BonRouge
Regular Coder

 
BonRouge's Avatar
 
Join Date: Mar 2006
Location: Sendai, Japan
Posts: 328
Thanks: 0
Thanked 0 Times in 0 Posts
BonRouge is on a distinguished road
Your problem is here:
Code:
<input type="submit" value="Add Comment" id="postbutton" onclick="disablepostbutton();alert('Thank you! Your comment has been posted.');addcomment(name.value,comment.value);" />
On the other one you have - the rating - 'this' is used. That's fine, the browser/script/whatever always knows what 'this' is - it's the element that you're using. 'name.value' and 'comment.value' will not be known. You need to be more specific. 'document.name.value' and 'document.comment.value' might work for you, but I'd usually use DOM methods - i.e. document.getElementById('name').value. Of course, for this, you'll need to give your input elements 'id's.

You may be thinking that
Code:
<input type="submit" value="Add Comment" id="postbutton" onclick="disablepostbutton();alert('Thank you! Your comment has been posted.');addcomment(document.getElementById('name').value,document.getElementById('comment').value);" />
seems pretty long.

I'd agree.

What you could do is remove a lot of that and put it in your head like this:
Code:
window.onload=function() {
 document.getElementById('postbutton').onclick=function() {
  disablepostbutton();
  alert('Thank you! Your comment has been posted.');
  var theName=document.getElementById('name').value;
  var theComment=document.getElementById('comment').value;
  addcomment(theName,theComment);
 }
}
Then your html could look like this:
Code:
<form action="#"> <!-- the action attribute is required -->
<fieldset> <!-- to validate, your inputs need to be contained by something like 'p', 'div', or 'fieldset' -->
<legend>Add Comment</legend>
<label>Name: <input type="text" name="name" id="name" /></label> <!-- labels are good. You could make them 'display:block;' in your css to get the line-break effect -->
<label>Comment: <textarea name="comment" id="comment"></textarea></label>
<input type="submit" value="Add Comment" id="postbutton" />
</fieldset>
</form>
I hope that helps (and I haven't forgotten/missed anything important).
__________________
bonrouge
BonRouge is offline   Reply With Quote
Old 05-23-2007, 06:08 PM   PM User | #8
glenngv
Supreme Master coder!


 
glenngv's Avatar
 
Join Date: Jun 2002
Location: Los Angeles, CA Original Location: Philippines
Posts: 10,241
Thanks: 0
Thanked 112 Times in 111 Posts
glenngv will become famous soon enough
You should escape the name and comment in the URL in order for them to be processed properly.
Code:
var comurl="add_comment.php?movie=<?php echo $_GET['movie']; ?>&name="+escape(name)+"&comment="+escape(comment);
__________________
Glenn
_____________________________________________
Play Tower of Hanoi Android app (Ad-FREE!)
Play Tower of Hanoi Android app (FREE!)
Go to Tower of Hanoi Leaderboard
Play Tower of Hanoi Facebook app
glenngv is offline   Reply With Quote
Old 08-04-2007, 10:51 PM   PM User | #9
thesmart1
Regular Coder

 
thesmart1's Avatar
 
Join Date: Dec 2005
Posts: 369
Thanks: 7
Thanked 3 Times in 3 Posts
thesmart1 is an unknown quantity at this point
OK, sorry about bumping an old topic, but I hadn't gotten a chance to try everything until just recently. I took both of your suggestions, and it still does what it's always been doing. it just goes to "thenameofthefile.php?name=the+name+entered&comment=the+comment+entered".

And BonRouge, I took your first suggestion, since I already had everything there.

I'm wondering now if I should just put the whole comments area in an iframe and have it load a whole new page to post comments. Because I've seen AJAX fail a lot (not just on my site). I think it might just be safer to use the more reliable and widely-supported iframes... Any thoughts?

Last edited by thesmart1; 08-04-2007 at 10:54 PM..
thesmart1 is offline   Reply With Quote
Old 08-04-2007, 11:31 PM   PM User | #10
rwedge
Regular Coder

 
Join Date: Feb 2005
Posts: 679
Thanks: 0
Thanked 16 Times in 15 Posts
rwedge is on a distinguished road
Your input type="submit" will reload the page, try using type="button"
rwedge is offline   Reply With Quote
Old 08-05-2007, 12:03 AM   PM User | #11
thesmart1
Regular Coder

 
thesmart1's Avatar
 
Join Date: Dec 2005
Posts: 369
Thanks: 7
Thanked 3 Times in 3 Posts
thesmart1 is an unknown quantity at this point
OK, thanks! It's not redirecting now. However, it's still not posting anything to the database. I'm positive the problem isn't add_comment.php (the page that AJAX loads), because I tried opening it in a browser with GET variables in the URL, and it does add to the database.

EDIT: And I just noticed that if I just hit enter (in the text input, not the textarea), it redirects to the same place it was going to before.

Does anyone else think I should just put it all in an iframe like I mentioned before?

Last edited by thesmart1; 08-05-2007 at 12:12 AM..
thesmart1 is offline   Reply With Quote
Old 08-05-2007, 01:01 AM   PM User | #12
rwedge
Regular Coder

 
Join Date: Feb 2005
Posts: 679
Thanks: 0
Thanked 16 Times in 15 Posts
rwedge is on a distinguished road
Add <form action="#" onsubmit="return false">
to keep the form from submitting from the textfield.
You do not need an iframe.

Untested:
Code:
<script type="text/javascript">
            var xmlHttp
            function GetXmlHttpObject(){
                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;
            }
          function stateChanged () {
                 if (xmlHttp.readyState == 4) {
                      if (xmlHttp.status == 200) {
                        alert('Good Response : '+xmlHttp.responseText);
                   } else {
                        alert('Error : '+xmlHttp.statusText);
                     }
                 }
             }
             function addcomment(name,comment,str){
             var q, url = (name || comment)? 'add_comment.php':'add_user_rating.php';
              q = (typeof name != 'undefined')? q = '?name='+escape(name):'?name='
              if(comment) q+='&comment='+escape(comment) // required entry
              else if (str) q='?rating='+str
              else { alert('Did you forget to enter a comment"');
              return;
             }
              // alert(url+q);  // uncomment to check
              xmlHttp=GetXmlHttpObject()
              if (!xmlHttp){
                   alert("Your browser doesn't support the technology required for this function.")
                   return
               }
              xmlHttp.onreadystatechange=stateChanged
              xmlHttp.open("GET",url+q,true)
              xmlHttp.send(null)
          }
        </script>


modifications to form function arguments in red to 
work with addcomment function

<form id="f"  action="" onsubmit="return false">
<p>name:<br />
<input type="text" id="name" value="" size="" maxlength="60" /></p>
<p>Comments:<br />
 <textarea id="comment" cols="25 rows="5" /></textarea></p>
<p>
<select id="rating" size="1" onchange="addcomment('','',this.options[this.selectedIndex].value)">
<option id="a" value="1">1</option>
<option id="b" value="2">2</option>
<option id="c" value="3">3</option>
</select> Rating</p>
<input type="button" id=".btn" value="Submit" onclick="addcomment(form.name.value,form.comment.value,'')" />
</form>

Last edited by rwedge; 08-05-2007 at 06:32 PM..
rwedge is offline   Reply With Quote
Old 08-05-2007, 04:18 AM   PM User | #13
thesmart1
Regular Coder

 
thesmart1's Avatar
 
Join Date: Dec 2005
Posts: 369
Thanks: 7
Thanked 3 Times in 3 Posts
thesmart1 is an unknown quantity at this point
Hmm, that didn't work either...
thesmart1 is offline   Reply With Quote
Old 08-05-2007, 05:04 AM   PM User | #14
rwedge
Regular Coder

 
Join Date: Feb 2005
Posts: 679
Thanks: 0
Thanked 16 Times in 15 Posts
rwedge is on a distinguished road
Give it another try, with my example form. I fixed an error and it tests ok for me
rwedge is offline   Reply With Quote
Old 08-05-2007, 05:20 PM   PM User | #15
thesmart1
Regular Coder

 
thesmart1's Avatar
 
Join Date: Dec 2005
Posts: 369
Thanks: 7
Thanked 3 Times in 3 Posts
thesmart1 is an unknown quantity at this point
I tried it with your example form and got "Error : Not Found". I uncommented "alert(url+q)" and saw that it was the right URL, and I know the file is there.
thesmart1 is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:36 AM.


Advertisement
Log in to turn off these ads.