0

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":"paulanselmendoza@gmail.com","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"}

  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – 31piy Jun 18 '18 at 08:34
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Sebastian Simon Jun 18 '18 at 08:35
  • You’re returning data from an async function so indefined gets returned. Read https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – user3210641 Jun 18 '18 at 08:37
  • Please get the source of `include "../includes/connect.php";` – Praveen Kumar Purushothaman Jun 18 '18 at 08:41
  • You are getting your response as a string. Are you calling `JSON.parse(arrayedUserData)` somewhere and did not post it? – Mr Glass Jun 18 '18 at 08:49

2 Answers2

1

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";
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

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);
    });
});
Supun Praneeth
  • 3,087
  • 2
  • 30
  • 33