草庐IT

php - mySQL php AJAX 数据不从 AJAX js 文件插入

coder 2023-10-25 原文

尝试在我的网站上创建评论应用程序。 尽管数据“发布”到 AJAX javaScript 文件,但数据未正确插入。 这是主页:http://micromedia.vaniercollege.qc.ca/home/nortonb/php/

作品:

您可以使用已经注册的用户插入评论:sn@dot.com pass: sn (注:alert来自js/ajax.js)

  • 在主页上包含 db/comments.php 以显示评论
  • 包含到 js/ajax.js 文件
  • 提交时通过 ajax.js 文件将信息传递给 comment_ins.php

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

不起作用:

如果数据库中不存在用户的电子邮件,comment_ins.php 会显示另一个包含 firstName 和 lastName 输入的表单。

这使用相同的 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

提前致谢。 布鲁斯

这是我的 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);

    ?>

最佳答案

我对你现在的问题出在哪里有点困惑

所以可能需要你为我重述一下,这样我才能帮助你..

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

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

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

编辑:我看到发生了什么,你点击添加评论,注册表单出现,你点击加入我们,它调用 AJAX 但随后页面被刷新,因为 <input>类型为 submit这意味着这会在您单击时提交表单 这样您的页面就会重新加载...您需要将 comment_ins.php 中的那一行更改为:

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

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

关于php - mySQL php AJAX 数据不从 AJAX js 文件插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7955156/

有关php - mySQL php AJAX 数据不从 AJAX js 文件插入的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  7. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  8. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  9. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  10. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

随机推荐