PHP:使用$ _SESSION变量和多个php文件自动填充表格 [英] Php: Form auto-fill using $_SESSION variables with multiple php files

查看:93
本文介绍了PHP:使用$ _SESSION变量和多个php文件自动填充表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I already searched for an hour to solve the following problem, but I couldnt find an answer for my specific problem. I have some ideas, which I propose after the introduction to the problem.

问题:

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

I have an html form in a php file. You can enter a name (first,mi,last) a phone number and an account number to that form. If a phone number is added, then the onblur function (using javascript file request.js) on the input field of phone number is used to auto fill the other 4 fields using a hash, which keys are the phone numbers and the values are a json-object, which holds all 4 other values.

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

If the entered customer data doesn't exist in the hash, then it should be added by clicking on the submit-button using an ajax-request again.

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

the following shows the file with the input form: 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调用来加载.

the next file is the javascript file, which handles all actions on the form. The getCustomerInformation.php shall include all Session variables, which can be loaded using the ajax calls.

文件: 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" ,但这没有帮助.

  1. I tried to use POST variables instead of GET, but then I wasn't even able to access them in getCustomerInformation.php. I included type: "POST" in the ajax methods, but it didn't help.

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

I thought there might be something wrong with the session_start() call, but I added it to both php files, still no change.

首先,我想将数组用作Session变量,然后将其用作哈希,以便只需要一个$ _SESSION ['hash']变量即可保存所有存储的值,例如:

First I wanted to use an array as a Session variable and I used it as a hash in order to only need one $_SESSION['hash'] variable which holds all stored values, like:

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

$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'] 加载数组,并在写==>后将其保存回去.

Everytime, users enter new data I loaded the array from $_SESSION['hash'] and save it back after writing ==> didn't work as well.

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

Does anyone have an idea, how I can change the code in order to be able to save the data in the backend (getCustomerInformation.php) using $_SESSION variable/s (better with the array-hash)?

很抱歉,我需要阅读大量代码.但是我认为,最好包含所有代码

Sorry for the large amount of code, I hope it's readable. But I thought, it might be better to include all code

以便更好地理解.

推荐答案

您问为了使它正常工作,我必须如何对其进行更改".好吧,我为您的脚本制作了一个副本(而不是复制并粘贴)以对其进行测试,并进行拆分以更好地理解,您要做的第一件事是在存储客户和检索客户信息时拆分逻辑,其次您必须验证是否您的电话号码存在于请求中(这是密钥)

you asked " how do I have to change it in order to get it to work". Well i made a copy (not copy & paste) of your script for test it, and split it for better understand, the first thing you must do is split the logic when are storing customer and retrieving customer info, second you must validate if your phone number exist in the request (it's the key)

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

One important thing is to separate the view, another is to use namespaces for well control and group values, and last but not least is to initialize values

如果前端控制器是index.php,则必须在此处初始化商店

if you front controller is the index.php you must initialize your store here

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

正如我之前说的,

有助于许多拆分逻辑

as I said before, helps a lot split logics

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);
    });
})();

此处发布的所有代码均已通过测试,您可以复制&直接粘贴,但是阅读和理解很重要.

all code posted here was tested you can copy & paste directly but it is important to read and understand.

这篇关于PHP:使用$ _SESSION变量和多个php文件自动填充表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆