duangengruan2144 2011-01-27 17:27
浏览 73
已采纳

如何使用PHP和Ajax将表单数据插入MySQL数据库表?

I am having trouble inserting data into my database using PHP, not sure if I am missing something.

Firstly my code validates the data using ajax method, but the data is not inserted into the database.

Secondly have php validation as a fallback that works and the data is inserted successfully, please see code below

php

    if(isset($_POST['submit'])){
        if(trim($_POST['polltitle']) == ""){
            $errortitle = "<span class='error'>Please enter a poll question</span>";
            $hasError = true;
        }
        else{
            $polltitle = $_POST['polltitle'];
        }
        if(trim($_POST['answerone']) == ""){
            $erroropt_1 = "<span class='error'>Please choose a response name</span>";
            $hasError = true;
        }
        else{
           $answerone = $_POST['answerone'];
        }

        if(trim($_POST['answertwo']) == ""){
            $erroropt_2 = "<span class='error'>Please choose a response name</span>";
            $hasError = true;
        }
        else{
          $answertwo = $_POST['answertwo'];
        }

        if(!isset($hasError)){

        $sql = "INSERT INTO Poll (pollname, answer1 , answer2, answer3, active) VALUES ('".$polltitle."','".$answerone."','".$answertwo."','".$answerthree."','".$activatepoll."')";
        mysql_query($sql) or die(mysql_error());
        $successmg = "<p>1 record added</p>";
        }
    }
  ?>

<form method="post" id="postfrm">
                      <h2>Create a new poll question</h2>
                      <fieldset class="dataform" id="insertfrm">
                            <label for="qtitle">Question Title</label><input type="text" name="polltitle" value=""  id="qtitle" />
                            <?php print $errortitle;?>

                            <label for="opt1">Answer 1</label><input type="text" name="answerone" value="" id="opt1" />                      
                            <?php print $erroropt_1;?>

                            <label for="opt2">Answer 2</label><input type="text" name="answertwo"  value="" id="opt2"/>
                            <?php print $erroropt_2;?>

                            <label>Make question active</label><input type="checkbox" name="activatepoll" value="1" id="activepoll"/>
                            <span class="small-txt">If you want the poll to be visible please check the box</span>
                        <input type="submit" name="submit" value="Submit" id="addpoll"/>
                      </fieldset>
                    </form>
                    <?php print $successmg;?>


       $(document).ready(function() {
 $("#postfrm").submit(function(){
        $(".error").hide();
        var hasError = false;       
        var nameVal = $("#qtitle").val();
        var optVal1 = $("#opt1").val();
        var optVal2 = $("#opt2").val();
        var optVal3 = $("#opt3").val();
        var viewpoll = $("#activepoll").val();
        if(nameVal == '') {
            $("#qtitle").after('<span class="error">Please enter a poll question</span>');
            hasError = true;
        }
        if(optVal1 == '') {
            $("#opt1").after('<span class="error">Enter an answer</span>');
            hasError = true;
        }
        if(optVal2 == '') {
            $("#opt2").after('<span class="error">Enter an answer</span>');
            hasError = true;
        }
        if(hasError == false) {
            $(this).hide();
            $.ajax({
                type:"POST",
                url: "validatedata.php",
                data : ({
                    polltitle:nameVal,
                    answerone:optVal1,
                    answertwo:optVal2,
                    answerthree:optVal3,
                    $activatepoll:viewpoll
                }),
                success: function(){
                     alert("worked");
                    },
               error :function(){
                    alert("nope :( ");
               },
               complete : function(){
                   alert("thanks");
               }
                 });
        }

        return false;
    });

});
  • 写回答

2条回答 默认 最新

  • dongli2000 2011-01-27 17:32
    关注

    why is there a questionmark before activatepoll?

    data : ({
                        polltitle:nameVal,
                        answerone:optVal1,
                        answertwo:optVal2,
                        answerthree:optVal3,
                        $activatepoll:viewpoll
                    }),
    

    Further you should send the send the variable $_POST['submit']:

    data : ({
                            polltitle:nameVal,
                            answerone:optVal1,
                            answertwo:optVal2,
                            answerthree:optVal3,
                            activatepoll:viewpoll,
                            submit: 'yeahhh'
                        }),
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题