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":"[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"}

5

2 Answers 2

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";
Sign up to request clarification or add additional context in comments.

4 Comments

Thank You for noticing that Mr. Praveen, all this time I thought that was displayed by the browser for the successful Ajax connection.
@PaulAnselMendoza So isn't this was the issue? Was the issue somewhere else?
Your were also correct Mr. Praveen, the echoed "Successful Connection" makes the JSON response invalid and at the same time I was not using the callback method for my function that causes it to return the value before it was assigned by AJAX.
@PaulAnselMendoza Thanks! :)
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);
    });
});

1 Comment

@PaulAnselMendoza your welcome, and check out Promise, it's the new way to do this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.