Skip to content Skip to sidebar Skip to footer

Php: Form Auto-fill Using $_session Variables With Multiple Php Files

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 th

Solution 1:

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

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

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><htmllang="es"><head><metacharset="UTF-8"><title>Document</title><scriptsrc="jquery.js"></script><scriptsrc="scripts.js"></script></head><body><divstyle="margin-left: 300px"><formid="dataForm"method="post"><fieldset><legend>User info</legend><labelfor="fname">First name</label><inputid="fname"type="text"name="fname"placeholder="First name"/><labelfor="mi">Middle inicial</label><inputid="mi"type="text"name="mi"placeholder="Middle Initial"/><labelfor="lname">Last name</label><inputid="lname"type="text"name="lname"placeholder="Middle Initial"/><labelfor="phone">Phone number</label><inputid="phone"type="text"name="phone"placeholder="000000"/></fieldset><fieldset><legend>Account info</legend><labelfor="account">Account</label><inputid="account"type="text"name="account"/></fieldset><inputtype="submit"name="submit"/><inputtype="reset"name="clear"/></form></div></body></html>

as I said before, helps a lot split logics

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 sentif (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_phoneif 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";

    functiongetCustomerInformation() {
        var phone = jQuery(this).val();

        if (!phone) {
            return;
        }

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

    functionpostCustomerInformation(event) {
        event.preventDefault();

        var form = jQuery(this);

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

    // set behaviors when document is readyjQuery(document).ready(functiondocument_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.

Post a Comment for "Php: Form Auto-fill Using $_session Variables With Multiple Php Files"