簡體   English   中英

PHP:使用$ _SESSION變量和多個php文件自動填充表格

[英]Php: Form auto-fill using $_SESSION variables with multiple php files

我已經搜索了一個小時來解決以下問題,但是找不到我的具體問題的答案。 我有一些想法,是在介紹問題之后提出的。

問題:

我在php文件中有一個html表單。 您可以在該表格中輸入姓名(名字,名字,姓氏),電話號碼和帳號。 如果添加了電話號碼,則電話號碼輸入字段上的onblur函數(使用javascript文件request.js)用於使用哈希自動填充其他4個字段,其中電話號碼是json-object,其中包含所有其他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方法中包括了類型:“ 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(最好使用array-hash)將數據保存在后端( getCustomerInformation.php )中?

對不起,大量的代碼,我希望它是可讀的。 但我認為,最好包含所有代碼

以便更好地理解。

您問“為了使它正常工作,我必須如何對其進行更改”。 好吧,我為您的腳本制作了一個副本(不是復制並粘貼)進行測試,並進行拆分以更好地理解,您要做的第一件事是在存儲客戶和檢索客戶信息時拆分邏輯,其次您必須驗證是否請求中存在電話號碼(這是關鍵)

一個重要的事情是分離視圖,另一重要的是使用名稱空間來實現良好的控制和組值,最后但同樣重要的是初始化值

如果前端控制器是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);
    });
})();

這里發布的所有代碼都經過測試,可以直接復制和粘貼,但閱讀和理解很重要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM