【问题标题】:Php: Form auto-fill using $_SESSION variables with multiple php filesPhp:使用具有多个 php 文件的 $_SESSION 变量自动填充表单
【发布时间】:2015-01-05 13:57:27
【问题描述】:

我已经搜索了一个小时来解决以下问题,但我找不到针对我的具体问题的答案。我有一些想法,在介绍问题后提出。

问题:

我在 php 文件中有一个 html 表单。您可以在该表单中输入姓名(名字、姓名、姓氏)、电话号码和帐号。如果添加了电话号码,则使用 电话号码 的输入字段上的 onblur 函数 (使用 javascript 文件 request.js) 自动填充其他 4 个字段,使用一个哈希,其中 keys电话号码,而 values 是一个 json 对象,它包含所有 4 个其他值。

如果输入的客户数据不存在于哈希中,则应通过再次使用 ajax 请求单击提交按钮来添加它。

下面显示了带有输入格式的文件:index.php:

<?php
   session_start();
// set the hash to session
// add the new item to the array/hash
// reset the array/hash back to session variable
//
?>
<html>
    <head>
        <script src="./jquery-2.1.1.min.js"></script>
        <script src="./request.js"></script>
    </head>
    <body>
        <div style="margin-left: 300px">
            <form id="dataForm" method="POST">
                Name: <input type="text" id="fname" name="fname" value="First Name" onfocus="this.value=''"/>
                <input type="text" id="mi" name="mi" value="Middle Initial"     onfocus="this.value=''"/>
                <input type="text" id="lname" name="lname" value="Last Name" onfocus="this.value=''"/><br />
                Phone: <input type="text" id="phone" name="phone" value="Phone number" onfocus="this.value=''"/> 
                <span style="margin-left:113px;">Account:</span> <input type="text" id="account" name="account" value="Account number" onfocus="this.value=''"/> <br />
                <input style="margin-left:230px" type="submit" name="submit"/>
                <input type="reset" name="clear"/>
            </form>
        </div>
    </body>    
</html>

下一个文件是 javascript 文件,它处理表单上的所有操作。 getCustomerInformation.php 应包含所有 Session 变量,可以使用 ajax 调用加载。

文件:request.js

$(document).ready(function(){
    $('#phone').blur(function(){
        console.log('on blur was called');

        $.ajax({
            url: './getCustomerInformation.php?code=0&phone=' + this.value,            
            success: function(response, status, jqXhr) {
                var info = JSON.parse(response);
                $('#fname').val(info.fname);
                $('#mi').val(info.mi);
                $('#lname').val(info.lname);
                $('#account').val(info.account);
                console.log("successful response");
            },
            error: function(xhr, status, error){
               alert("Error!" + xhr.status);
            }
        })
    });

    $('#dataForm').submit(function(){
        console.log('form submitted');
        var phone = $('#phone').value;
        var fname = $('#fname').value;
        var mi = $('#mi').value;
        var lname = $('#lname').value;
        var account = $('#account').value;

        $.ajax({
            url: './getCustomerInformation.php?code=1&phone=' + phone +'&fname='+fname+'&mi='+mi + '&lname='+ lname +'&account='+account,
            success: function(response, status, jqXhr) {
                console.log("successful SUBMIT response");
            },
            error: function(xhr, status, error){
               alert("Error!" + xhr.status);
            },
        })
    });
})

文件:getCustomerInformation.php

<?php 
  session_start();
  $_SESSION['1234567'] = '{"lname": "Berg", "mi": "M", "fname": "Thomas", "account": "1234"}';
  $_SESSION['1122334'] = '{"lname": "Jordan", "mi": "C", "fname": "Jacky", "account": "4321"}';

  $phone = $_GET['phone'];
  $fname = $_GET['fname'];
  $lname = $_GET['lname'];
  $mi = $_GET['mi'];
  $acc = $_GET['account'];

  if($_GET['code'] == 0){
    if(array_key_exists('phone', $_GET) &&  array_key_exists($phone, $_SESSION)){
        print $_SESSION[$phone];
      }
  } else {
    if (array_key_exists('fname', $_GET) && array_key_exists('lname', $_GET) && array_key_exists('account', $_GET)){
      $_SESSION[$phone] = '{"lname": "' + $lname+ '", "mi": "'+ $mi + '", "fname": "'+$fname+'", "account": "'+$acc+'"}';
    } else {
      // Data are not complete - not possible to add them to the Session.
    }
  }
?>

我的想法:

  1. 我尝试使用 POST 变量而不是 GET,但后来我什至无法在 getCustomerInformation.php 中访问它们。我在 ajax 方法中包含了 type: "POST",但它没有帮助。

  2. 我认为session_start()调用可能有问题,但我将它添加到两个php文件中,仍然没有变化。

  3. 首先,我想使用一个数组作为 Session 变量,并将其用作哈希,以便只需要一个 $_SESSION['hash'] 变量来保存所有存储的值,例如:

    $cust = array("1234567" => '{"lname": "Berg", "mi": "M", "fname": "Thomas", "account": "1234"}', "1122334" => '{"lname": "Jordan", "mi": "C", "fname": "Jacky", "account": "4321"}' ); $_SESSION['hash'] = $cust;

每次,用户输入新数据我从 $_SESSION['hash'] 加载数组并在写入后将其保存回来 ==> 效果不佳。

有谁知道,我如何更改代码以便能够使用 $_SESSION 变量/s 将数据保存在后端 (getCustomerInformation.php)(最好使用数组-哈希)?

抱歉,代码量很大,我希望它是可读的。但我认为,包含所有代码可能会更好

为了更好地理解。

【问题讨论】:

  • 是否需要将信息存储在会话变量中?
  • 你能说清楚你要解决什么问题吗?
  • 您说“效果不佳”,但这是什么意思?
  • 如果我提交了一些客户数据,我希望能够通过在代码中输入相关电话号码 (onblur) 在同一会话中访问它们..所以示例:Jack M Daniels,电话:1234567,Acc:1234 在系统中,如果我在表单中输入电话号码 1234567,其他 4 个字段由 ajax 请求自动填充到后端,其中数据存储在 $ _SESSION 变量。现在,如果我提交客户的新数据,我希望能够通过在自动填写的表单中输入电话号码来获取新数据。这有帮助吗?
  • 我了解您想要达到的目标,但问题是哪里出了问题?

标签: javascript php jquery ajax session


【解决方案1】:

您问“我必须如何更改它才能使其正常工作”。好吧,我制作了您的脚本的副本(不是复制和粘贴)以进行测试,并将其拆分以便更好地理解,您必须做的第一件事是在存储客户和检索客户信息时拆分逻辑,其次您必须验证您的请求中存在电话号码(这是关键)

一个重要的事情是分离视图,另一个是使用命名空间来控制和分组值,最后但并非最不重要的是初始化值

如果你的前端控制器是 index.php 你必须在这里初始化你的存储

index.php

<?php

session_start();

if (!isset($_SESSION['customers'])) {
    $_SESSION['customers'] = array(
        '1234567' => '{"lname": "Berg", "mi": "M", "fname": "Thomas", "account": "1234"}',
        '1122334' => '{"lname": "Jordan", "mi": "C", "fname": "Jacky", "account": "4321"}',
    );
}

require __DIR__ . '/index_template.php';

index_template.php

<!doctype html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="jquery.js"></script>
    <script src="scripts.js"></script>
</head>
<body>
<div style="margin-left: 300px">
    <form id="dataForm" method="post">
        <fieldset>
            <legend>User info</legend>
            <label for="fname">First name</label>
            <input id="fname" type="text" name="fname" placeholder="First name"/>

            <label for="mi">Middle inicial</label>
            <input id="mi" type="text" name="mi" placeholder="Middle Initial"/>

            <label for="lname">Last name</label>
            <input id="lname" type="text" name="lname" placeholder="Middle Initial"/>

            <label for="phone">Phone number</label>
            <input id="phone" type="text" name="phone" placeholder="000000"/>
        </fieldset>

        <fieldset>
            <legend>Account info</legend>

            <label for="account">Account</label>
            <input id="account" type="text" name="account"/>
        </fieldset>

        <input type="submit" name="submit"/>
        <input type="reset" name="clear"/>
    </form>
</div>
</body>
</html>

正如我之前所说,对拆分逻辑有很大帮助

postCustomerInformation.php

session_start();

// example: converts $_POST['phone'] into $post_phone if exists
extract($_POST, EXTR_PREFIX_ALL, 'post');

// Validates that all required information was sent
if (isset($post_lname) && isset($post_fname) && isset($post_phone) && isset($post_account)) {
    $customer = array(
        'fname' => $post_fname,
        'lname' => $post_lname,
        'account' => $post_account,
        'mi' => isset($post_mi) ? $post_mi : '' // optional
    );

    $_SESSION['customers'][$post_phone] = json_encode($customer);
    // returns a valid json format header
    header('Content-Type: application/json');
    header("HTTP/1.0 204 No Response");
} else {
    // returns error
    header('Content-Type: application/json');
    header("HTTP/1.0 400 Bad Request");
}

getCustomerInformation.php

session_start();

// example: converts $_GET['phone'] into $get_phone if exists
extract($_GET, EXTR_PREFIX_ALL, 'get');

if (isset($get_phone) && isset($_SESSION['customers'][$get_phone])) {
    header('Content-Type: application/json');
    echo $_SESSION['customers'][$get_phone];
} else {
    header('Content-Type: application/json');
    echo '{}';
}

scripts.js

;(function () {
    "use strict";

    function getCustomerInformation() {
        var phone = jQuery(this).val();

        if (!phone) {
            return;
        }

        jQuery.ajax({
            type: 'get',
            url: 'getCustomerInformation.php',
            data: {
                phone: phone
            },
            success: function getCustomerInformation_success(data) {
                // for each returned value is assigned to the field
                for (var i in data) {
                    if (data.hasOwnProperty(i)) {
                        $('#' + i).val(data[i]);
                    }
                }
            }
        });
    }

    function postCustomerInformation(event) {
        event.preventDefault();

        var form = jQuery(this);

        jQuery.ajax({
            type: 'post',
            url: 'postCustomerInformation.php',
            data: form.serializeArray(),
            success: function postCustomerInformation_success() {
                alert("OK");
            },
            error: function postCustomerInformation_error() {
                alert("Error");
            }
        })
    }

    // set behaviors when document is ready
    jQuery(document).ready(function document_ready() {
        jQuery('#phone').blur(getCustomerInformation);
        jQuery('#dataForm').submit(postCustomerInformation);
    });
})();

此处发布的所有代码都经过测试,您可以直接复制和粘贴,但阅读和理解很重要。

【讨论】:

  • 非常感谢您的详细描述和您花时间写这个答案。它真的帮助我理解如何更好地分离获取和存储客户信息的逻辑。但是 postCustomerInformation 文件中是不是缺少一个 session_start() 来处理新数据的存储,因为如果缺少它,数据将不会被保存?我把index.php和index_template.php切换了,因为html数据必须写在index.php中,否则表格不会显示在屏幕上。
  • 是的,你是对的,我忘记了 postCustomerInformation.php 文件中的 session_start()
猜你喜欢
  • 2011-08-14
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多