Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Trying to create a comment application on my website. Data is not inserted properly although it "posts" to the AJAX javaScript file. Here is the main page: http://micromedia.vaniercollege.qc.ca/home/nortonb/php/

Works:

You can insert a comment using an already registered user: [email protected] pass: sn (note: alert is from js/ajax.js)

  • include on main page to db/comments.php to display comments
  • include to js/ajax.js file
  • on submit passes info to comment_ins.php through ajax.js file

    <input name="submit" type="button" class="indent" value="add your comment" onclick="loadXMLDoc('db/comments_ins.php')">

Does not work:

If the user's email does not exist in the db, comment_ins.php displays another form with firstName and lastName inputs.

This uses the same ajax.js file but now db/comments_add_user.php to insert the new user, and then insert their comment in a related table.

(note: the parameters are being passed to the ajax.js file, but the info is not submitted in the database)

I have tried: -hard coding the data in db/comments_add_user.php works

-passing the info from a regular form but still using js/ajax.js works

http://micromedia.vaniercollege.qc.ca/home/nortonb/php/c_test.htm

Thanks in advance. Bruce

Here is the guts of my index.php file:

<h4>Comments</h4>
    <article id="comms">

    <form name="intro" action="" method="post">
        <fieldset> 
            <legend>Add your comment</legend> 
            <label for="comment">
                Comments:<br /><textarea name="comment" id="comment" cols="30" rows="5" class="indent"></textarea><br /> 
            </label>   
            <label for="email">
                Email:<br /><input name="email" id="email" type="text" size="32" class="indent"/>
                <span id="emailMessage"></span>
            </label><br />

            <label for="password">
                Password:<br /><input name="password" id="password" type="password" size="32" class="indent"/>
                <span id="passwordMessage"></span>
            </label><br />

                <input name="submit" type="button" class="indent" value="add your comment" onclick="loadXMLDoc('db/comments_ins.php')">

        </fieldset> 
    </form> 
    <?php include("db/comments.php"); ?>

    </article>

And here is the js/ajax.js file:

// JavaScript Document
function loadXMLDoc(xmlDoc){
    var xmlhttp;
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("comms").innerHTML=xmlhttp.responseText;
        }
    }


    var commentValue=encodeURIComponent(document.getElementById("comment").value);
    var emailValue=encodeURIComponent(document.getElementById("email").value);
    var passwordValue=encodeURIComponent(document.getElementById("password").value);

    var parameters="comment="+commentValue+"&email="+emailValue+"&password="+passwordValue;
    //if a new user then add these things
    if(document.getElementById("firstName")){ 
        var firstNameValue=encodeURIComponent(document.getElementById("firstName").value);
        var lastNameValue=encodeURIComponent(document.getElementById("lastName").value);
        //parameters are formatted in name=value pairs
        var parameters="firstName="+firstNameValue+"&lastName="+lastNameValue+"&comment="+commentValue+"&email="+emailValue+"&password="+passwordValue;

    }
    alert(xmlDoc + " parameters: "+parameters);
    xmlhttp.open("POST", xmlDoc, true);//true = asynchronous
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(parameters);

}

Here is the db/comments_ins.php (which seemingly works fine)

<?php
    //comments_ins.php adds new comments to the database
    //if the user has already registered, the comment is displayed
    //else a form is displayed for new users keeping the comment and email from the original comment form

    //to do list:
    // ??? should I combine this into comments.php?
    // ??? should I separate the forms into a separate .php file with a conditional for new users?
    //fix scrolling issue? 
    //jQuery? AJAX?
    include  'includes/mysqli_connect.php';
    //get the posted info
    echo("comments_ins.php<br />");
    if(isset($_POST["comment"])){
        $password = trim($_POST["password"]);
        $hashedPassword = hash(sha256,$password);
        $email = trim($_POST["email"]);
        $comment = trim($_POST["comment"]);
        //see if user exists
        $query = "select * from users where email = '$email' and password = '$hashedPassword' limit 1";//adding limit 1 speeds up the query on big tables
        $result = mysqli_query($link, $query);
        //get response from database    
        if($result = mysqli_query($link, $query)){
            $numrows = $result->num_rows;
            //echo ('found '.$numrows.' user: <br>'. $firstName.'<br>');
            while ($row = $result->fetch_object()) {    
                $userArray[] = array('userID'=>$row->userID,
                    'firstName'=>$row->firstName, 
                    'lastName'=>$row->lastName,
                    'email'=>$row->email
                );//line breaks for readability
            }
            $verifiedUserID = $userArray[0]['userID'];//get userID for insert below
            //echo("\$verifiedUserID: ".$verifiedUserID);
        }else{
            // This means the query failed
            echo("errr...");
            echo $mysqli->error;
        } 

        //if the user already exists...
        if($numrows > 0){//should add something if numrows > 1 i.e. for duplicate users!!
            //echo("user is registered <br />");
            $commentQuery="INSERT INTO comments (comment, userID) VALUES ('$comment', '$verifiedUserID')";
            $commentResult = mysqli_query($link, $commentQuery);
            //get response from database
            $commentNum =  mysqli_affected_rows($link);
            echo(mysqli_error());
            //echo ('<br />inserted '.$commentNum.' record: <br />'. $comment.'<br />');
            include("comments.php");
        }else{//if the user does not exist
            echo("Please register to display your comment: <br />");
            ?>
            <form name="intro" action="" method="post">
                <fieldset> 
                    <legend>Register to share your comment:</legend> 
                      <label for="firstName">
                        First Name: <br />
                        <input name="firstName" id="firstName" type="text" class="indent" size="32" />
                        <span id="firstMessage"></span>
                      </label>
                      <br /> 
                      <label for="lastName">
                        Last Name:<br />
                        <input name="lastName" id="lastName" type="text" class="indent" size="32" />
                        <span id="lastMessage"></span>
                      </label>
                      <br />  
                      <label for="email">
                        Email:<br />
                        <input name="email" id="email" type="text" size="32" class="indent" value="<?php echo($email); ?>"/>
                        <span id="emailMessage"></span>
                      </label>
                      <br />
                      </label>
                      <label for="password">
                        Password:<br />
                        <input name="password" id="password" type="password" size="32" class="indent"/>
                        <span id="passwordMessage"></span>
                      </label>
                      <br />
                      <label for="comment">
                        Edit your comment?<br />
                        <textarea name="comment" id="comment" cols="30" rows="5" class="indent"><?php echo($comment); ?></textarea>
                      </label> <br /> 
                      <input name="submit" type="submit" class="indent" value="join us" onclick="loadXMLDoc('db/comments_add_user.php')"/>
                    <p class="note">(Of course we will keep your stuff private!!)</p>
                </fieldset> 
            </form> 
        <?php   
        }//end else($numrows <=0)

        //close connection
        mysql_close($link);
    }
    ?>

And here is the comments_add_user.php file (which doesn't work when called from the js/ajax.js file but does when called from

<?php
    include  'includes/mysqli_connect.php';
    //get the posted info
    echo("hi mom");
    $firstName = $_POST["firstName"];//"Two";//
    $lastName = $_POST["lastName"];//"Two";//
    $password = $_POST["password"];//"Two";//
    $hashedPassword = hash(sha256,$password);
    $email = $_POST["email"];//"Two";//
    $comment = $_POST["comment"];//"Two";//
    echo($firstName." from comments_add_user.php<br>");

    //since email does not exist, 
        $query="INSERT INTO users (firstName, lastName, password, email) VALUES ('$firstName', '$lastName', '$hashedPassword', '$email')";
        $result=mysqli_query($link, $query);
        //get response from database
        $num=  mysqli_affected_rows($link);
        echo(mysqli_error());
        echo ('inserted '.$num.' record: <br>'. $firstName.'<br>');
    //** add error checking ?!?

    //get the userID for the new user
        $userQuery = "select userID from users where email = '$email' limit 1";//adding limit 1 speeds up the query on big tables
        $userResult = mysqli_query($link, $userQuery);

        //get response from database    
        if($userResult = mysqli_query($link, $userQuery)){
            $numrows = $userResult->num_rows;
            echo ('found '.$numrows.' user: <br>'. $firstName.'<br>');
            while ($row = $userResult->fetch_object()) {
                $userArray[] = array('userID'=>$row->userID);//line breaks for readability
            }
            $newUserID = $userArray[0]['userID'];//get userID for insert below
            //echo("\$verifiedUserID: ".$verifiedUserID);
        }else{
            // This means the query failed
            echo("errr...");
            echo $mysqli->error;
        } 

    //now insert the comment
        $commentQuery="INSERT INTO comments (comment, userID) VALUES ('$comment', '$newUserID')";
        $commentResult=mysqli_query($link, $commentQuery);
        //get response from database
        $commentNum=  mysqli_affected_rows($link);
        echo(mysqli_error());
        echo ('inserted '.$commentNum.' record: <br>'. $comment.'<br>');


    echo('<br><a href="comments_display.php">display all comments</a><br />');
    //close connection
    mysql_close($link);

    ?>
share|improve this question
 
Nice SQL injection holes you've got there... be a shame if someone drove a truck through them into your server. –  Marc B Oct 31 '11 at 14:45
 
Thanks Mark B. I knew I should have plugged them before posting. –  Bruce.Norton Oct 31 '11 at 14:47
 
No more trucks. Added some slashing and stripping. Plan to add prepared statements once I get this working. Thanks again Mark B. –  Bruce.Norton Nov 1 '11 at 3:14
add comment

1 Answer

up vote 1 down vote accepted

I am a bit confused with where your problem is right now

So might need you to recap things for me so i can help you..

Other than that, i noticed that you have <form name="intro" action="" method="post">

I just want to make sure that you got this right, action="" means actually pointing to index.php and not db/comments_ins.php

I don't know if that's what you really want to happen...

EDIT: I see what's happening, you click add comment, the registration form appears, you click join us, it DOES call AJAX but then the page is refreshed because the <input> is of type submit which means that this submits the form when you click it So that makes your page reload... what you need is to change that line in comment_ins.php to :

<input name="submit" type="button" class="indent" value="join us" onclick="loadXMLDoc('db/comments_add_user.php')"/>

After i did that change, i am getting the output from the add user file...

share|improve this answer
 
Thanks @DanyKhalife Problem is that AJAX does not work when I try to register users. New form is created by db/comments_ins.php if email (and password) don't exist or don't match. You are correct: action="" points back to the index.php (or database.php file in this case). It is the onClick event that $_POSTs the info via: onclick="loadXMLDoc('db/comments_ins.php') –  Bruce.Norton Nov 5 '11 at 2:01
 
so your registration form appears but when the user clicks "Join Us" nothing happens ? EDIT: ok i see, i'll load that up on my server to debug it for you.. –  Dany Khalife Nov 5 '11 at 2:06
 
ok i updated my answer, let me know if that solves your problem and vote it up in case it does :) –  Dany Khalife Nov 5 '11 at 2:18
 
Yeah!!! @Dany, thank you so much. In the immortal words of Roberto De Vicenzo... "What a stupid I am!" (ps. can't vote it up yet... not enough rep) –  Bruce.Norton Nov 5 '11 at 12:52
1  
Crazy... it's a small world. And now that I have more comments... my rep is > 15 I am able to vote it up and accept the answer. Plus, I have updated all the php scripts to OOP style and prepared statements. –  Bruce.Norton Nov 7 '11 at 13:06
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.