Paul Ansel Mendoza
Paul Ansel Mendoza

Reputation: 47

Cannot retrieve data from PHP array, which is returned by a function() that uses JQuery Ajax

I have this "click Listener" that calls and sends a userId parameter to the function-"getModalData" which then returns an array value to the variable-"arrayedUserData".

$('body').on('click', '.openModal', function () {
        var userId = $(this).val(),
            btnText = $(this).text(),
            btnClass = '',
            colorCode = '',
            arrayedUserData = getModalData(userId);

        if (btnText === "Delete") {
            btnClass = 'danger';
            colorCode = '#d9534f';
        } else {
            btnClass = 'warning';
            colorCode = '#f0ad4e';
        }

        $('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
        $('#modalTitle').text('Confirm ' + btnText);
        $('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
        $('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);

    });

This is the function-"getModalData". The returned php array from the Ajax's "success" will then be passed to the variable-"UserData" that is then returned by the function.

function getModalData(passedUserId) {
        var UserData;
        $.ajax(
            {
                type: "POST",
                url: "get/get_modal_data.php",
                data: { passedUserId: passedUserId },
                dataType: "json",
                success: function (data) {
                   UserData = data;
                }
            }
        );
        return UserData;
    }

this is the "get_modal_data.php".

<?php
    include "../includes/connect.php";

    if (isset($_POST['passedUserId'])) {
        $UserId = mysqli_real_escape_string($con, $_POST['passedUserId']);

        $getUserData = mysqli_query($con, "SELECT * FROM tblUserAccounts WHERE uaUserId = '".$UserId."'");
        $uaRow = mysqli_fetch_assoc($getUserData);

        $UserDataArr = array("UserId" => $uaRow['uaUserId'],
                     "EmailAddress" => $uaRow['uaEmailAddress'],
                     "FirstName" => $uaRow['uaFirstName'],
                     "LastName" => $uaRow['uaLastName'],
                     "BirthDate" => $uaRow['uaBirthDate'],
                     "Address" => $uaRow['uaAddress'],
                     "Gender" => $uaRow['uaGender'],
                     "ContactNumber" => $uaRow['uaContactNumber'],
                     "BloodTypeId" => $uaRow['uaBloodTypeId'],
                     "AccountStatus" => $uaRow['uaAccountStatus'],
                    );


        echo json_encode($UserDataArr);
        exit();
    }
?>

this error appears on the console:

Uncaught TypeError: Cannot read property 'LastName' of undefined get_user_accounts.js:66

this is the line 66 of get_user_accounts.js, which is present on the "click listener".

$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);

but, I am confused because the php array appears on the browser's Network Response:

Successful Connection{"UserId":"1","EmailAddress":"[email protected]","FirstName":"Paul Ansel","LastName":"Mendoza","BirthDate":"1998-12-17","Address":"Phase 1B Block 8 Lot 20 Olivarez Homes South, Sto. Tomas, Binan City, Laguna","Gender":"Male","ContactNumber":"2147483647","BloodTypeId":"0","AccountStatus":"ACTIVE"}

Upvotes: 0

Views: 105

Answers (2)

Supun Praneeth
Supun Praneeth

Reputation: 3160

Because getModalData fucntion return the UserData before it asign by ajax(UserData = data;). use a callback function:

using callbacks

function getModalData(passedUserId,callback) {
        $.ajax(
            {
                type: "POST",
                url: "get/get_modal_data.php",
                data: { passedUserId: passedUserId },
                dataType: "json",
                success: function (data) {
                   callback(data);
                }
            }
        );
    }


$('body').on('click', '.openModal', function () {
    var userId = $(this).val(),
        btnText = $(this).text(),
        btnClass = '',
        colorCode = '';

    getModalData(userId, function (arrayedUserData) {

        if (btnText === "Delete") {
            btnClass = 'danger';
            colorCode = '#d9534f';
        } else {
            btnClass = 'warning';
            colorCode = '#f0ad4e';
        }

        $('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
        $('#modalTitle').text('Confirm ' + btnText);
        $('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
        $('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
    });
});

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Did you see that you get: Successful Connection before the JSON data? You have to remove that, if not it will be an invalid JSON response. The code you have shared doesn't have the particular stuff.

I believe you have to check your database connection, where on successful connection, it is set to output Successful Connection, which breaks your response. Please remove that bit of code.

include "../includes/connect.php";

It can be something like:

$conn = mysqli_connect() or die("Error");
echo "Successful Connection";

Upvotes: 1

Related Questions