如何使用php和jquery验证向导表单?

时间:2017-09-03 13:33:27

标签: php jquery session cookies

简要解释这个简单的jQuery向导如何工作

  • 会话用于保存每个步骤的数据。
  • 包含一个会话变量,用于保存我们的步骤。
  • 由用于存储表单数据的会话变量组成。
  • 每次我们更改步骤时,我们都会使用ajax请求保存表单数据和会话步骤。
  • 如果数据已更新,则会从会话中检索数据。

此向导表单包含3个步骤。

我可以纠正错误并使用php验证表单,如果有一个没有数据的字段,请不要进入下一步,直到用户完成表单的所有字段。

每个文本输入中的每个表单字段都有警告错误,向我显示警告消息。

  

注意:未定义的索引:第229行 C:\ xampp \ htdocs \ prueba \ wizar.php中的datos_form

我想在保存步骤的会话中添加一个cookie,以避免在浏览器错误关闭的情况下删除存储在会话中的数据,创建一个验证时间为30天的会话cookie。

现在要从用户保存的数据中删除cookie,创建一个取消按钮,取消按钮将删除cookie,包括保存在会话中的数据。

  

我的完整代码:

wizar.php

<?php

session_start();

// check if there is a previous step.
if ( !empty($_SESSION['datos_form']['__paso__']) ) {
    $paso = $_SESSION['datos_form']['__paso__'];
}
// if there is no previous step we set step 1.
else{
    $paso = '1';
}

?><!DOCTYPE html>
<html>
<head>
    <title>Form por pasos</title>
<style type="text/css">
.backdrop {
    position: absolute;
    width: 630px;
    height: 16px;
    background: url(//drh.img.digitalriver.com/DRHM/Storefront/Site/avast/cm/images/avast/2014/breadcrumb-3.png) no-repeat;
    list-style-type: none;
    text-transform: uppercase;
}

.step {
    padding-top: 30px;
    display: none;
}

.step-1 {
    display: block;
}

.setup {
    width: 100%;
    height: 100px;
    padding: 50px 0px 0px 50px;
    background-color: rgba(29, 36, 36, 0.25);
}


.process {
    position: absolute;
    top: -30px;
    color: #e8e8e8;
    font-size: 1.1em;
}

.process.item2 {
  padding-left: 190px;
}

.process.item3 {
  padding-left: 400px;
}

.process.item4 {
  padding-left: 580px;
}

.process.item5 {
  padding-left: 690px;
}

.process.item6 {
  padding-left: 790px;
}

ul li {
    margin: 0;
    padding: 0;
    border: none;
    list-style: none;
    list-style-type: none;
    white-space: nowrap;
}


.step{
    display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

    mostrar_paso(<?= $paso; ?>);        
});


function animacion(caso){
    switch(caso) {
        case 1:
            $(".backdrop").css("background-position", `0px 0px`);
            break;
        case 2:
            $(".backdrop").css("background-position", `0px -16px`);
            break;
        case 3:
            $(".backdrop").css("background-position", `0px -32px`);
            break;
        default:
            $(".backdrop").css("background-position", `0px 0px`);
    };
};

function mostrar_paso(paso)
{

    var data = $( "#form" ).serialize();

    var url = 'saveTemp.php?paso=' + paso;

    var valor_radio = $('input:radio[name=radio]:checked').next("label").text();


    $.ajax({
      type: "POST",
      url: url,
      data: data
    })
    .done(function( resp ) {

        $('.step').css( "display", "none" );

        $('#paso'+paso).fadeIn("slow");

        $('#div_producto').html(valor_radio);

        animacion(paso);
    });
};

</script>

</head>
<body>

<div class="setup">
    <ul class="backdrop">
        <li class="process item1">step 1</li>
        <li class="process item2">step 2</li>
        <li class="process item3">FINALIZE</li>
    </ul>
</div>


<form id="form" action="procesar.php">
    <div id="paso1" class="step">
        <input type="text" name="campo1" value="<?= $_SESSION['datos_form']['campo1']; ?>">

        <select class="form-select" name="sexo">
            <?php 
                if( !empty($_SESSION['datos_form']['sexo']) ) {
                    $sexo = $_SESSION['datos_form']['sexo'];
                    echo '<option value="'.$sexo.'" selected="selected">'.$sexo.'</option>';
                }
                else{
                    echo '<option disabled selected="selected">I am...</option>';
                }
            ?>
            <option value="Mem">Men</option>
            <option value="Woman">Woman</option>
            <option value="I prefer not to say">I prefer not to say</option>        
        </select>

        <?php 
            if( !empty($_SESSION['datos_form']['condiciones']) ) {
                echo '<input type="checkbox" name="condiciones" checked>';
            }
            else{
                echo '<input type="checkbox" name="condiciones">';
            }
        ?>
        ...


onclick="mostrar_paso('numero de paso') -->
        <a href="#2" onclick="mostrar_paso(2)">continuar</a>
    </div>
    <div id="paso2" class="step">

        <?php
            $r =array(
                    1 => 'Product 1',
                    2 => 'Product 2',
                    3 => 'Product 3',
                );

            foreach ($r as $key => $value) 
            {
                if( $_SESSION['datos_form']['radio'] == $key ) {
                    echo '<input name="radio" type="radio" id="'.$key.'" value="'.$key.'"  checked="checked" >';
                    echo '<label for="'.$key.'" title="'.$value.'">'.$value.'</label>';
                }
                else{
                    echo '<input name="radio" type="radio" id="'.$key.'" value="'.$key.'" >';
                    echo '<label for="'.$key.'" title="'.$value.'">'.$value.'</label>';
                }
            }
        ?>

        <a href="#1" onclick="mostrar_paso(1)">Atras</a>
        <a href="#3" onclick="mostrar_paso(3)">continuar</a>
    </div>
    <div id="paso3" class="step">
        <div id="div_producto"></div><br>

        <input type="text" name="campo3" value="<?= $_SESSION['datos_form']['campo3']; ?>">
        <input type="submit" name="cancel">
        <a href="#2" onclick="mostrar_paso(2)">Atras</a>
        <input type="submit" name="Terminar">
    </div>
</form>

</body>
</html>

saveTemp.php

  

注意:此文件负责保存表单的步骤和数据。

<?php
session_start();
// We save the form data in a session variable
$_SESSION['datos_form'] = $_POST;
// we added the step also to the array, you can not use this name (__paso__) as name in the form
$_SESSION['datos_form']['__paso__'] = $_GET['paso'];

1 个答案:

答案 0 :(得分:0)

  

因为我可以纠正错误并使用php验证表单   没有数据的字段不会放到下一步,直到所有字段   表单由用户填写。

您需要在saveTemp.php下编码验证规则,如下所示:

<?php
session_start();
//form validation
switch($_GET['paso']){
    case 2:
        if(empty($_POST['campo1'])){//you may add any validation rule you want here
            die(json_encode(array('status' => FALSE,'message' => 'please fill campo ....')));
        }
        if(empty($_POST['sexo'])){
            die(json_encode(array('status' => FALSE,'message' => 'please select sexo ....')));
        }
        if(empty($_POST['condiciones'])){
            die(json_encode(array('status' => FALSE,'message' => 'please select condiciones ....')));
        }
        break;
    case 3: //step 2 validation here
        if(empty($_POST['radio'])){//you may add any validation rule you want here
            die(json_encode(array('status' => FALSE,'message' => 'please fill radio1 ....')));
        }
    break;
}

// We save the form data in a session variable
$_SESSION['datos_form'] = $_POST;
// we added the step also to the array, you can not use this name (__paso__) as name in the form
$_SESSION['datos_form']['__paso__'] = $_GET['paso'];

die(json_encode(array('status' => TRUE,'message' => 'Temporary saved....')));

然后检查ajax调用状态下的响应,所以你需要改变这样的ajax调用:

    $.ajax({
      type: "POST",
      url: url,
      data: data,
      dataType: 'json'
    })
    .done(function( resp ) {
        if(resp.status)
        {
            $('.step').css( "display", "none" );
            $('#paso'+paso).fadeIn("slow");
            $('#div_producto').html(valor_radio);
            animacion(paso);
        }else{
            var old_paso = paso-1;
            alert(resp.message);
            $('.step').css( "display", "none" );
            $('#paso'+old_paso).fadeIn("slow");
            $('#div_producto').html(valor_radio);
            animacion(old_paso);            
        }
    });

请注意我将“dataType”添加到您的ajax调用并将其设置为json

  

每个文本输入中的每个表单字段都有警告错误   向我显示一条警告信息。

因为你在获取它的值之前没有检查变量的存在,你发布的代码是form.php,但警告抱怨wizar.php行号229,检查该行并使用空函数就像你的其余部分一样代码

这是wizar.php示例,没有通知/警告:

<?php

session_start();

// check if there is a previous step.
if ( !empty($_SESSION['datos_form']['__paso__']) ) {
    $paso = $_SESSION['datos_form']['__paso__'];
}
// if there is no previous step we set step 1.
else{
    $paso = '1';
}

?><!DOCTYPE html>
<html>
<head>
    <title>Form por pasos</title>
<style type="text/css">
.backdrop {
    position: absolute;
    width: 630px;
    height: 16px;
    background: url(//drh.img.digitalriver.com/DRHM/Storefront/Site/avast/cm/images/avast/2014/breadcrumb-3.png) no-repeat;
    list-style-type: none;
    text-transform: uppercase;
}

.step {
    padding-top: 30px;
    display: none;
}

.step-1 {
    display: block;
}

.setup {
    width: 100%;
    height: 100px;
    padding: 50px 0px 0px 50px;
    background-color: rgba(29, 36, 36, 0.25);
}


.process {
    position: absolute;
    top: -30px;
    color: #e8e8e8;
    font-size: 1.1em;
}

.process.item2 {
  padding-left: 190px;
}

.process.item3 {
  padding-left: 400px;
}

.process.item4 {
  padding-left: 580px;
}

.process.item5 {
  padding-left: 690px;
}

.process.item6 {
  padding-left: 790px;
}

ul li {
    margin: 0;
    padding: 0;
    border: none;
    list-style: none;
    list-style-type: none;
    white-space: nowrap;
}


.step{
    display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('.step').css( "display", "none" );
    $('#paso'+<?= $paso; ?>).fadeIn("slow");
    $('#div_producto').html(valor_radio);
    animacion(<?= $paso; ?>);        
});


function animacion(caso){
    switch(caso) {
        case 1:
            $(".backdrop").css("background-position", `0px 0px`);
            break;
        case 2:
            $(".backdrop").css("background-position", `0px -16px`);
            break;
        case 3:
            $(".backdrop").css("background-position", `0px -32px`);
            break;
        default:
            $(".backdrop").css("background-position", `0px 0px`);
    };
};

function mostrar_paso(paso)
{

    var data = $( "#form" ).serialize();

    var url = 'saveTemp.php?paso=' + paso;

    var valor_radio = $('input:radio[name=radio]:checked').next("label").text();


    $.ajax({
      type: "POST",
      url: url,
      data: data,
      dataType: 'json'
    })
    .done(function( resp ) {
        if(resp.status)
        {
            $('.step').css( "display", "none" );
            $('#paso'+paso).fadeIn("slow");
            $('#div_producto').html(valor_radio);
            animacion(paso);
        }else{
            var old_paso = paso-1;
            alert(resp.message);
            $('.step').css( "display", "none" );
            $('#paso'+old_paso).fadeIn("slow");
            $('#div_producto').html(valor_radio);
            animacion(old_paso);            
        }
    });
};

</script>

</head>
<body>

<div class="setup">
    <ul class="backdrop">
        <li class="process item1">step 1</li>
        <li class="process item2">step 2</li>
        <li class="process item3">FINALIZE</li>
    </ul>
</div>


<form id="form" action="procesar.php">
    <div id="paso1" class="step">
        <input type="text" name="campo1" value="<?= (!empty($_SESSION['datos_form']['campo1'])) ? $_SESSION['datos_form']['campo1'] : '' ; ?>">

        <select class="form-select" name="sexo">
            <?php 
                if( !empty($_SESSION['datos_form']['sexo']) ) {
                    $sexo = $_SESSION['datos_form']['sexo'];
                    echo '<option value="'.$sexo.'" selected="selected">'.$sexo.'</option>';
                }
                else{
                    echo '<option disabled selected="selected">I am...</option>';
                }
            ?>
            <option value="Mem">Men</option>
            <option value="Woman">Woman</option>
            <option value="I prefer not to say">I prefer not to say</option>        
        </select>

        <?php 
            if( !empty($_SESSION['datos_form']['condiciones']) ) {
                echo '<input type="checkbox" name="condiciones" checked>';
            }
            else{
                echo '<input type="checkbox" name="condiciones">';
            }
        ?>
        ...


onclick="mostrar_paso('numero de paso') -->
        <a href="#2" onclick="mostrar_paso(2)">continuar</a>
    </div>
    <div id="paso2" class="step">

        <?php
            $r =array(
                    1 => 'Product 1',
                    2 => 'Product 2',
                    3 => 'Product 3',
                );

            foreach ($r as $key => $value) 
            {
                if( !empty($_SESSION['datos_form']['radio']) AND $_SESSION['datos_form']['radio'] == $key ) {
                    echo '<input name="radio" type="radio" id="'.$key.'" value="'.$key.'"  checked="checked" >';
                    echo '<label for="'.$key.'" title="'.$value.'">'.$value.'</label>';
                }
                else{
                    echo '<input name="radio" type="radio" id="'.$key.'" value="'.$key.'" >';
                    echo '<label for="'.$key.'" title="'.$value.'">'.$value.'</label>';
                }
            }
        ?>

        <a href="#1" onclick="mostrar_paso(1)">Atras</a>
        <a href="#3" onclick="mostrar_paso(3)">continuar</a>
    </div>
    <div id="paso3" class="step">
        <div id="div_producto"></div><br>

        <input type="text" name="campo3" value="<?= (!empty($_SESSION['datos_form']['campo3'])) ? $_SESSION['datos_form']['campo3'] : ''; ?>">
        <input type="submit" name="cancel">
        <a href="#2" onclick="mostrar_paso(2)">Atras</a>
        <input type="submit" name="Terminar">
    </div>
</form>

</body>
</html>
  

我想在保存步骤的会话中添加一个cookie   避免在浏览器出现的情况下删除存储在会话中的数据   错误关闭,创建一个验证时间为30的会话cookie   天。

PHP的本机会话,如果访问者浏览器支持cookie已经使用了cookie,并且可以在php.ini中设置过期时间,或者在运行时通过设置session.cookie_lifetime

  

现在从用户保存的数据中删除cookie创建一个   取消按钮,取消按钮将删除cookie,包括   保存在会话中的数据。

最后使用session_destroy函数删除procesar.php文件下的cookie