mySQL php AJAX数据无法从AJAX js文件中插入

3
尝试在我的网站上创建评论应用程序,尽管已经“发布”到AJAX JavaScript文件,但数据未正确插入。这是主页面:http://micromedia.vaniercollege.qc.ca/home/nortonb/php/ 工作:
您可以使用已注册用户的电子邮件地址sn@dot.com和密码sn添加评论(注:警报来自js/ajax.js)
在主页上包含db/comments.php以显示评论 在js/ajax.js文件中包含 在提交时通过ajax.js文件将信息传递给comment_ins.php 不工作:
如果用户的电子邮件地址不存在于数据库中,则comment_ins.php会显示另一个表单,其中包括名字和姓氏输入。
这使用相同的ajax.js文件,但现在使用db/comments_add_user.php插入新用户,然后将其评论插入相关表中。
(注:参数被传递到ajax.js文件,但信息未提交到数据库)
我尝试过:
-在db/comments_add_user.php中硬编码数据可行
-从常规表格中传递信息,但仍使用js/ajax.js,也可行 http://micromedia.vaniercollege.qc.ca/home/nortonb/php/c_test.htm 感谢您的帮助。 Bruce 以下是我的index.php文件核心内容:
<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>

这里是js/ajax.js文件:

// 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);

}

这是 db/comments_ins.php 文件(看起来运行良好)。
<?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);
    }
    ?>

以下是comments_add_user.php文件(当从js/ajax.js文件调用时不起作用,但从其他地方调用时可以正常工作):

<?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);

    ?>

你的 SQL 注入漏洞看起来很不错… 如果有人通过它们驾驶卡车进入你的服务器,那就太可惜了。 - Marc B
谢谢Mark B。在发布之前我就知道我应该先插上它们。 - Bruce.Norton
没有更多的卡车了。增加了一些斜杠和剥离操作。计划一旦完成此工作便添加准备好的语句。再次感谢马克·B。 - Bruce.Norton
1个回答

1

我有点困惑你目前的问题在哪里

所以可能需要你为我概括一下事情,这样我才能帮助你。

除此之外,我注意到你有一个<form name="intro" action="" method="post">

我只是想确保你做对了,action=""实际上是指向了index.php而不是db/comments_ins.php

我不知道那是否是你真正想要发生的...

编辑:我知道发生了什么,你点击添加评论,注册表单出现,你点击加入我们,它确实调用了AJAX,但是然后页面会刷新,因为的类型是submit,这意味着当你点击它时会提交表单。所以这会使你的页面重新加载...你需要改变comment_ins.php中的那一行为:

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

在我做了那个改变之后,我从添加用户文件中得到了输出...


感谢@DanyKhalife 问题是当我尝试注册用户时,AJAX不起作用。 如果电子邮件(和密码)不存在或不匹配,则由db/comments_ins.php创建新表单。您是正确的:action =“”指向index.php(在这种情况下为database.php文件)。正是通过onClick事件,$_POST通过onclick =“loadXMLDoc('db/comments_ins.php')”将信息发送。 - Bruce.Norton
所以你的注册表单出现了,但当用户点击“加入我们”时,什么也没有发生? 编辑:好的,我明白了,我会将其加载到我的服务器上为您调试。 - Dany Khalife
好的,我更新了我的答案,请告诉我是否解决了你的问题,并在解决后投票支持它 :) - Dany Khalife
耶!!! @Dany,非常感谢。 借用Roberto De Vicenzo不朽的话说... “我是多么愚蠢!”(附注:目前还不能投票...声望不够) - Bruce.Norton
呵呵,我很高兴能帮到你 :) 我们都有这样的时刻。 啊,我猜你可以接受打勾的答案吧?或者那也需要声望?顺便说一下,哈哈,我刚刚注意到你就在我住的旁边上CEGEP,这是多大的巧合啊 :D - Dany Khalife
1
真是太神奇了,这个世界真小。现在我有更多的评论了,我的声望值已经大于15,我可以投票并接受答案了。 此外,我已经将所有的PHP脚本更新为面向对象编程风格和预处理语句。 - Bruce.Norton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接