使用 AJAX 和 PHP 提交表单并带有成功响应文本而不刷新页面

Posted

技术标签:

【中文标题】使用 AJAX 和 PHP 提交表单并带有成功响应文本而不刷新页面【英文标题】:Submitting form with AJAX&PHP with success response text without refreshing the page 【发布时间】:2021-04-07 18:53:15 【问题描述】:

这是我在这里的第一个问题,希望我做对了。 我是这个“编码世界”的初学者,并且已经使用此处找到的答案取得了一些进展!

今天我遇到了通过 AJAX 和 php 提交表单的问题。如果我省略了 AJAX 部分。插入表单效果很好,可以做它应该做的事情,但是当我尝试使用 AJAX 提交它时,它除了刷新页面之外什么也没做。我想使用 AJAX 在 html 部分设置错误 div 而无需刷新页面。

这里是使用的代码:

HTML:

<form class="form" action="../actions/insertUser.php" method="post" id="createUserForm">
    <div class="row">
        <div class="col">
            <div class="row">
                <div class="col">
                    <div class="form-group">
                        <label>Gebruikersnaam</label>
                        <input 
                        class="form-control"
                        id="userGebruikersnaam" 
                        type="text" 
                        name="userGebruikersnaam" 
                        placeholder="JODO"
                        value=""
                        maxlength="4"
                        pattern="[A-Za-z]4"
                        title="Maximaal 4 letters"
                        required>
                        <div id="form-info"></div>
                        <small class="small-form-text">Eerste 2 karakters Voornaam &amp; Eerste 2 karakters Achternaam<hr></small>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col">
                    <div class="form-group">
                        <label>Voornaam</label>
                        <input 
                        class="form-control"
                        id="userVoorNaam" 
                        type="text" 
                        name="userVoorNaam" 
                        placeholder="John" 
                        value=""
                        required>
                        <div id="form-info"></div>
                    </div>
                </div>
                <div class="col">
                    <div class="form-group">
                        <label>Achternaam</label>
                        <input 
                        class="form-control"
                        id="userNaam" 
                        type="text" 
                        name="userNaam"
                        placeholder="Doe" 
                        value=""
                        required>
                        <div id="form-info"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col">
                    <div class="form-group">
                        <label>Email</label>
                        <input 
                        class="form-control"
                        id="userMail"
                        type="email" 
                        name="userMail"
                        placeholder="Joe.doe@mail.com" 
                        value=""
                        maxlength="50"
                        pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]2,$"
                        title="Controleer het opgegeven Emailadres"
                        required>
                        <div id="form-info"></div>
                    </div>
                </div>
            </div>
            <div class="row" style="width:60%">
                <div class="col-md-4">
                    <label for="userGender">Geslacht:</label>
                </div> 
                <div class="col-md-3 genderRadio">
                    <div class="form-group">
                        <label>
                            <input type="radio" id="userGender" name="userGender" value="man" required>
                                Man
                            </label>
                        </div>
                    </div>
                    <div class="col-md-3 genderRadio">
                    <div class="form-group">
                            <label>
                            <input type="radio" id="userGender" name="userGender" value="vrouw" required>
                                Vrouw
                            </label>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-2">
                    <label for="userAfdeling">Afdeling:</label>
                </div>
                <div class="col-md-6">
                    <select class="form-control form-control-sm" name="userAfdeling" id="userAfdeling" required>
                        <option value=""></option>
                        <option value="Administratie">Administratie</option>
                            <option value="After-Sales">After-Sales</option>
                            <option value="Carrosserie">Carrosserie</option>
                            <option value="Sales">Sales</option>
                            <option value="Tweedehands">Tweedehands</option>
                    </select>
                </div>
            </div><br>
            <div class="row">
                <div class="col-md-2">
                    <label for="userRole">Machtiging:</label>
                </div>
                <div class="col-md-6">
                    <select class="form-control form-control-sm" name="userRole" id="userRole" required>
                        <option value=""></option>
                        <option value="gebruiker">Gebruiker</option>
                            <option value="admin">Admin</option>
                    </select>
                </div>
            </div>
            <div class="row">
                <div class="col d-flex justify-content-end">
                    <button class="btn btn-primary" type="submit" name="createUser" id="submit_btn" value=""><i class="fas fa-fw fa-user-plus"></i> Creëer
                    </button>

                </div>
            </div>
        </div>
    </div>
</form>

PHP:

if (isset($_POST['createUser'])) 

    $userGebruikersnaam = strtoupper($_POST['userGebruikersnaam']);
    $userVoorNaam       = htmlspecialchars(ucwords($_POST['userVoorNaam'])); 
    $userNaam           = htmlspecialchars(ucwords($_POST['userNaam']));
    $userMail           = filter_var($_POST['userMail'], FILTER_SANITIZE_EMAIL);
    $userGender         = htmlspecialchars($_POST['userGender']);
    $userAfdeling       = htmlspecialchars($_POST['userAfdeling']);
    $userRole           = htmlspecialchars($_POST['userRole']);
    $userActief         = 0;
    $userCreateDate     = date("Y-m-d");
    /*Random Wachtwoord met Hash*/
    $wachtwoord = randomPassword();
        $optie = ['cost' => 11];
    /*HashedWachtwoord*/
    $userWachtwoord = password_hash($wachtwoord, PASSWORD_DEFAULT, $optie);

    $sql_user = "SELECT * FROM gebruikers WHERE gebruikersnaam ='$userGebruikersnaam'";
    $sql_email = "SELECT * FROM gebruikers WHERE email='$userMail'";
    $res_user = mysqli_query($con, $sql_user);
    $res_email = mysqli_query($con, $sql_email);

    if (mysqli_num_rows($res_user) > 0 ) 
        http_response_code(400);
            echo "Gebruiker bestaat al!";
     elseif (mysqli_num_rows($res_email) > 0 ) 
            http_response_code(400);
            echo "Email bestaat al!";
         else
           // Prepare an insert statement
                $sql = "INSERT INTO gebruikers (gebruikersnaam, email, role, voornaam, naam, actief, 
                wachtwoord, gender, afdeling, datumCreatie) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                if($stmt = $con->prepare($sql))
                    // Bind variables to the prepared statement as parameters
                    $stmt->bind_param("sssssissss", $userGebruikersnaam, $userMail, $userRole, 
                     $userVoorNaam, $userNaam, $userActief, $userWachtwoord, $userGender, 
                     $userAfdeling, $userCreateDate);
                     $stmt->execute(); 
                     http_response_code(200);
                    echo "Records inserted successfully.";
                    // Close statement
                    $stmt->close();
                 else 
                    http_response_code(400);
                    echo "ERROR: Could not prepare query: $sql. " . $mysqli->error;
               
        
    
 ?>

jQuery:

$(function() 
    // 'Get' het reset formulier.
    //Aanpassing voor insertUser
    var form = $('#createUserForm');
    //Aanpassing voor insertUser
    var formMessages = $('#form-info'); //-->extra div voor text
    var formInputUser = $('#userGebruikersnaam');
    var formInputEmail = $('#userMail');

    // Opzetten van event listener voor het formulier
    $(form).submit(function(e) 
        // Voorkomen dat de browser het formulier verzend.
        e.preventDefault();

        // Serialiseren van de formulier data.
        var formData = $(form).serialize();

        // Verzenden van formulier met AJAX.
        $.ajax(
            type: 'POST',
            //url: $(form).attr('action'),
            url:"../actions/insertUser.php",
            data: formData
        )
        .done(function(response) 
            // Als het gekoppelde PHP script succesvol is box-succes en succes class toevoegen aan
            // formMessages(DIV #form-info) & formInputPass (INPUT #email)
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');
            $(formInputUser).removeClass('box-error');
            $(formInputUser).addClass('box-succes');
            $(formInputEmail).removeClass('box-error');
            $(formInputEmail).addClass('box-succes');

            // Zetten van antwoord tekst uit het php script.
            $(formMessages).text(response);

            // Formulier leegmaken.
            $('#userGebruikersnaam').val('');
            $('#userMail').val('');
            //window.location.replace("http://***.com");
            setTimeout(function() window.location.replace("https://www.patrick-smets-group.be/dashboard2/admin/createUser.php");, 2500);
        )
        .fail(function(data) 
            // Als het gekoppelde PHP script faalt box-error en error class toevoegen aan
            // formMessages(DIV #form-info) & formInputPass (INPUT #email)
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');
            $(formInputUser).removeClass('box-succes');
            $(formInputUser).addClass('box-error');
            $(formInputEmail).removeClass('box-succes');
            $(formInputEmail).addClass('box-error');


            // Zetten van antwoord tekst uit het php script.
            if (data.responseText !== '') 
                $(formMessages).text(data.responseText);
             else 
                $(formMessages).text('Oops! Er liep iets mis, probeer het nogmaals.');
            
        );
    );
);

【问题讨论】:

两件事,当你说“什么都没有发生”时,你有没有检查开发者控制台看是否有错误?您是否看到出站的网络请求和来自服务器的响应?次要项目是您的表单处理程序很容易被 sql 注入破坏。单独的问题,但您应该查看参数化的 sql 查询。 欢迎来到堆栈溢出。我留下了以 else // Prepare an insert statement 和悬空关闭处理指令(??&gt;)开头的代码缩进不一致供您清理。 【参考方案1】:

在您的 jquery 中注释这行代码并检查开发者控制台是否有任何输出。如果您的 jquery 代码工作正常而没有任何语法错误,则这行代码可能正在重新加载页面。否则,语法有问题只需重新加载页面并检查开发者控制台是否有任何错误

setTimeout(function() window.location.replace("https://www.patrick-smets- group.be/dashboard2/admin/createUser.php");, 2500);

【讨论】:

【参考方案2】:

您正在检查您的后端 $_POST['createUser'] 但此值未传递到您的后端,这就是没有打印任何内容的原因。这是因为您使用了 $(form).serialize();,所以这里serialize() 不包含提交按钮作为参数本身。但是您可以附加createUser 参数,如下所示:

$(function() 
  var form = $('#createUserForm');
  $(form).submit(function(e) 
    e.preventDefault();
    var formData = $(form).serialize() + "&createUser=something";
    console.log(formData)
    //also you need to check for null values else when you click on submit button null values will get sended to backend..
  );
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form" action="../actions/insertUser.php" method="post" id="createUserForm">
  <div class="row">
    <div class="col">
      <div class="row">
        <div class="col">
          <div class="form-group">
            <label>Gebruikersnaam</label>
            <input class="form-control" id="userGebruikersnaam" type="text" name="userGebruikersnaam" placeholder="JODO" value="" maxlength="4" pattern="[A-Za-z]4" title="Maximaal 4 letters" required>
            <div id="form-info"></div>
            <small class="small-form-text">Eerste 2 karakters Voornaam &amp; Eerste 2 karakters Achternaam<hr></small>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <div class="form-group">
            <label>Voornaam</label>
            <input class="form-control" id="userVoorNaam" type="text" name="userVoorNaam" placeholder="John" value="" required>
            <div id="form-info"></div>
          </div>
        </div>
        <div class="col">
          <div class="form-group">
            <label>Achternaam</label>
            <input class="form-control" id="userNaam" type="text" name="userNaam" placeholder="Doe" value="" required>
            <div id="form-info"></div>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <div class="form-group">
            <label>Email</label>
            <input class="form-control" id="userMail" type="email" name="userMail" placeholder="Joe.doe@mail.com" value="" maxlength="50" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]2,$" title="Controleer het opgegeven Emailadres" required>
            <div id="form-info"></div>
          </div>
        </div>
      </div>
      <div class="row" style="width:60%">
        <div class="col-md-4">
          <label for="userGender">Geslacht:</label>
        </div>
        <div class="col-md-3 genderRadio">
          <div class="form-group">
            <label>
                        <input type="radio" id="userGender" name="userGender" value="man" required>
                            Man
                        </label>
          </div>
        </div>
        <div class="col-md-3 genderRadio">
          <div class="form-group">
            <label>
                        <input type="radio" id="userGender" name="userGender" value="vrouw" required>
                            Vrouw
                        </label>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-md-2">
          <label for="userAfdeling">Afdeling:</label>
        </div>
        <div class="col-md-6">
          <select class="form-control form-control-sm" name="userAfdeling" id="userAfdeling" required>
            <option value=""></option>
            <option value="Administratie">Administratie</option>
            <option value="After-Sales">After-Sales</option>
            <option value="Carrosserie">Carrosserie</option>
            <option value="Sales">Sales</option>
            <option value="Tweedehands">Tweedehands</option>
          </select>
        </div>
      </div><br>
      <div class="row">
        <div class="col-md-2">
          <label for="userRole">Machtiging:</label>
        </div>
        <div class="col-md-6">
          <select class="form-control form-control-sm" name="userRole" id="userRole" required>
            <option value=""></option>
            <option value="gebruiker">Gebruiker</option>
            <option value="admin">Admin</option>
          </select>
        </div>
      </div>
      <div class="row">
        <div class="col d-flex justify-content-end">
          <button class="btn btn-primary" type="submit" name="createUser" id="submit_btn" value=""><i class="fas fa-fw fa-user-plus"></i> Creëer
                </button>

        </div>
      </div>
    </div>
  </div>
</form>

【讨论】:

【参考方案3】:

尝试将表单提交按钮类型设置为按钮而不是提交。

<button class="btn btn-primary" type="button" name="createUser" id="submit_btn" value=""><i class="fas fa-fw fa-user-plus"></i> Creëer
            </button>

【讨论】:

以上是关于使用 AJAX 和 PHP 提交表单并带有成功响应文本而不刷新页面的主要内容,如果未能解决你的问题,请参考以下文章

无法通过 onSubmit 属性触发的 Ajax 响应阻止表单提交。

在 CSS 中使用 Ajax 成功数据显示带有在表单中输入的值的预览

带有单选按钮的 PHP 邮件表单使用 AJAX 发送

Ajax发布表单和下载文件作为响应

提交表单会触发 ajax 调用,该调用会在成功时发布到操作页面

以 onsubmit 形式调用 ajax 函数 [重复]