Zareidriel Zareidriel - 6 months ago 8
Javascript Question

Can't get AJAX calls or session to function

I have an extremely similar service like the one in this thread:

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

I would have asked there but since I don't have 50 reputation, I'll have to ask a new question.

To understand Ajax better I wanted to re-create rkmax's files and see if they would work. So I saved them as 5 separate files.

The SESSION does not seem to store any posted information. Added a

print_r($_SESSION);
to keep track of what's currently in there. Furthermore the
.blur
event to retrieve account information via the phone number doesn't work either.

Been banging my head against the wall for days with this one. It won't work when working either hosted locally via Apache/XAMPP or on an actual web server. All 5 files are in the same folder and titled exactly the same as rkmax's file titles.

I understand the logic behind each of the functions and can't seem to find a problem anywhere. I'm pretty new to coding so it could easily be something obvious like file structure or my own computer's settings?

Read a bunch of other StackOverflow threads with similar problems, but none of them seemed whatsoever applicable.

Thanks for your time.

Here's everything copied from rkmax's code:

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

Answer

Started from scratch working on my answer pretty much nonstop, but gotta go to work soon, here's what I've got so far; I'm currently stuck on successfully sending the SESSION data back to the javascript and decoding it and displaying it successfully. Once I have that working I think sending those to the appropriate forms as well as the POST will be trivial. If anyone has any suggestions to speed me through this last part I would appreciate it.

Edit: Edited with the final solution.

index2.php

    <?php

session_start();

if (!isset($_SESSION['customers'])) {
    $_SESSION['customers'] = array(
        '1111111' => '{"phone": "1111111", "fname": "Za", "lname": "Zo", "mi": "Z", "account": "1234"}',
        '2222222' => '{"phone": "2222222", "fname": "La", "lname": "Li", "mi": "L", "account": "4321"}',
    );
}

?>

<!DOCTYPE html>

<html lang="en">
<head> 
    <title> Assignment5 </title>
    <meta charset = "utf-8" />
    <script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type = "text/javascript" src = "scripts.js"></script>
</head>
<body>
    <form id="myform">
        <input placeholder="Phone Number" name="phone" type="text" id="phone" maxlength="7" autofocus>
        <input placeholder="First Name" name="fname" type="text" id="fname">
        <input placeholder="Last Name" name="lname" type="text" id="lname">
        <input placeholder="Middle Initial" name="mi" type="text" id="mi">
        <input placeholder="Account Number" name="account" type="text" id="account" maxlength="4">
        <input type="submit" value="Submit">
    </form>
</body>
</html>

scripts.js

    $(document).ready(function(){

    $("#phone").blur(function(){

        var session;
        var currentPhone = $("#phone").val();

        $.get("getPhone.php", {phone: currentPhone}, function(data) {

            for (var i in data) {
                if (data.hasOwnProperty(i)) {
                    $('#' + i).val(data[i]);
                }
            }
        });
    });

    $("form").submit(function(){

        var form = jQuery(this);

        $.post("postPhone.php", form.serializeArray(), function(data) {
            alert(data);
        });
    });
});

getPhone.php

 <?php

    session_start();

    $nowPhone = $_GET["phone"];

    if (array_key_exists($nowPhone, $_SESSION['customers'])) {
        header('Content-Type: application/json');
        echo $_SESSION['customers'][$nowPhone];
    } else {
        header('Content-Type: application/json');
        echo '{}';
    }

?>

postPhone.php

<?php

    session_start();

    if (isset($_POST["phone"]) && isset($_POST["fname"]) && isset($_POST["lname"]) && isset($_POST["mi"]) && isset($_POST["account"])) {

        echo ("Submitted");

        $customer = array(
            'phone' => $_POST["phone"],
            'fname' => $_POST["fname"],
            'lname' => $_POST["lname"],
            'mi' => $_POST["mi"],
            'account' => $_POST["account"],
        );

        $_SESSION['customers'][$_POST["phone"]] = json_encode($customer);
    }
    else
        echo ("All Information is Required");

?>