0

PHP:

<?php

    $user_info = getInformation(); // gets user's information and puts it into an array, $user_info[0] is their ID, $user_info[1] is their username, $user_info[2] is their display name

?>

JQuery:

$(document).ready(function() {
    $(document).on("click", ".btn", function(event) {
        event.preventDefault();
        var post = $(this);
        $.ajax({
            url: 'assets/script.php',
            type: 'POST',
            data: { user_id: <?php echo $user_info[0] ?>, display_name: <?php echo $user_info[2] ?> },
            success: function(data) {
                alert(data);
            }
        });
    });
});

However, when I click on the button (.btn), it shows the following error in the console:

ReferenceError: Test is not defined

Test being the display name of the user that's getting this error.

What's wrong?

1 Answer 1

2

Because you're missing the single quotes around the php variables you're echoing.

data: { user_id: '<?php echo $user_info[0] ?>', display_name: '<?php echo $user_info[2] ?>' }

The id worked because it's an integer, but test will be considered a variable. This is literally what javascript sees: display_name: test which means it's looking for a variable test. Keep in mind that you're trying to create display_name: 'test'.

However, I find all of this to be a terrible practice. I never generate js with php, but the alternative are beyond the scope of your question. You could at least move the insertion of these values to the beginning of your js so that they are isolated from the rest of the code. It would make it a lot easier on you in the future if you run into an issue like this.

Sign up to request clarification or add additional context in comments.

2 Comments

Can't believe I didn't do that. Thanks.
@Bagwell it happens :) also, see my updated answer for a little more detail.

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.