Daniel
Daniel

Reputation: 393

Javascript function is not defined in script?

I know this question has been asked before but I have tried numerous solutions from stackoverflow and I could not find the problem.I receive the error in the browser console that the function that I defined in the script tag is not defined.This is the code:

<html>
<body>
    <input type="text" id="input_1"/>
    <button type="button" value="Click" onclick="cd()" id="getDatabaseData">Click!</button>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
        function cd() {
            var inbtn = {};
            inbtn.input = $('#input_1').val();

            console.log('Started...');

            $.ajax({

                type: 'post',
                url: '<%: Url.Action("Trial") %>',
                data: inbtn,
                success: function er() {
                    console.log("Succes!")
                },
                error: function err() {
                    console.log("Error!")
                }
            })
        }   
    </script>
</body>
</html>

I tried to add $document.ready and also to add a separate event listener(not onclick function)

 $(document).ready(
        document.getElementById("getDatabaseData").addEventListener("click", cd, false));

It did not worked.I also replaced the whole function with a simple function:

function cd(){
console.log("Message");
}

and I still receive the same error:

Uncaught ReferenceError: cd is not defined
    at HTMLButtonElement.onclick

Upvotes: 0

Views: 1380

Answers (2)

John Dahl
John Dahl

Reputation: 31

To clarify what has already been said, but not specifically called out... a script tag can EITHER contain a src attribute to pull in an external script file OR it can contains the script content. A single script tag cannot contain both.

Upvotes: 2

ousecTic
ousecTic

Reputation: 1925

Just a small mistake

You need to make another script tag and put the function cd inside

<html>
<body>
    <input type="text" id="input_1"/>
    <button type="button" value="Click" onclick="cd()" id="getDatabaseData">Click!</button>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">

    </script>
    <script>
    function cd() {
            var inbtn = {};
            inbtn.input = $('#input_1').val();

            console.log('Started...');

            $.ajax({

                type: 'post',
                url: '<%: Url.Action("Trial") %>',
                data: inbtn,
                success: function er() {
                    console.log("Succes!")
                },
                error: function err() {
                    console.log("Error!")
                }
            })
        } 
    </script>
</body>
</html>

I am assuming this is the result you want , because the cd is now defined

enter image description here

Upvotes: 1

Related Questions