且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-03 15:34:52

我可以更正错误并使用php验证表单(如果有) 没有数据的字段不要放到下一步,直到所有字段 表格的内容由用户填写.

As I can correct the errors and validate the form with php if there is a field without data do not let go to the next step, until all fields of the form are completed by the user.

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

You need to code validation rules under saveTemp.php something like this :

<?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调用:

and then check response under ajax call for status, so you need to change ajax call like this:


    $.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);            
        }
    });

请注意,我在您的ajax调用中添加了"dataType"并将其设置为json

notice that I add "dataType" to your ajax call and set it to json

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

There are warning errors in each of the form fields in each text input shows me a warning message.

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

that because you did not check for existence of variable before getting its value, the code you post is form.php but warning complain about wizar.php line number 229, check that line and use empty function just like the rest of your code

这是示例wizar.php,恕不另行通知/警告:

here is a sample wizar.php without notice/warning:

<?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 天.

I would like to add a cookie to the session where the steps are saved to avoid erasing the data stored in the session in case the browser is closed in error, create a session cookie with a validation time of 30 days.

PHP的本机会话,如果访问者浏览器支持cookie,则已经在使用cookie,并且可以通过设置

PHP's native session, already using cookie if visitor browser support cookie and the expiration time can be set in php.ini or at runtime by setting session.cookie_lifetime

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

now to remove the cookie from the data saved by the user create a cancel button, the cancel button will delete the cookie, including the data saved in the session.

最后使用 session_destroy 函数在过程中删除该cookie .php文件

And finally use session_destroy function to delete that cookie under procesar.php file