0

I'm trying to pass a PHP variable into an onclick() in a bootstrap button, here's the code, please note that it's in a PHP echo:

<button id="reportTopicButt" class="btn btn-danger" onclick="reportTopic('.$topicID.')">
<i class="fa fa-flag"></i></button>

$topicID is a PHP variable that I get from a query and it's declared inside a PHP function, that's why that code above is an echo statement.

Here's my reportTopic() JavaScript function:

   function reportTopic(aTopicID) {
        var topicID = aTopicID;

        $.ajax({
            url:"report-topic.php?topicID=" + topicID,  
            type: "GET", 

            success:function(data) {
                var results = data;  
                console.debug(results);

                alert('Thanks for reporting');
        }});
    }

The funny thing is that the Chrome console prints the ID I need out, but it gives me the following error:

Uncaught ReferenceError: CRFYLtWNDD is not defined
    at HTMLButtonElement.onclick 

CRFYLtWNDD is my $topicID PHP variable, so at least I know that the onclick() button gets it correctly, but I really can't figure out why it's not defined.

0

2 Answers 2

4

it is because $topicId is rendered as a variable to solve it set it as a string inside your php

<button id="reportTopicButt" class="btn btn-danger" onclick="reportTopic(\''.$topicID.'\')">
<i class="fa fa-flag"></i></button>
Sign up to request clarification or add additional context in comments.

Comments

3

Because you are passing a string to you function you should include it between ' ' if you dont do this javasript thinks you are passing a variable thats why you get the undefined error

Try this

onclick="reportTopic(\''.$topicID.'\')">

Comments

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.