Search code examples
javascriptjqueryjsongetjsonjson-api

GetJSON data from an API is NOT working when passing api url as a variable


This function below is working 100% fine,

     function myFunction() {
        $(function () {
            $.getJSON('abc/url', function (data) {
                console.log(data);
            });
        });
    }

But, when I try this (below) then it is not working even it does not show any errors. Can anyone tell why is it so? or the API url will always be hard coded?

<!DOCTYPE html>
<html>

<head>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>

<script>
     function myFunction() {
         var URL = document.getElementById('textboxID').value;
        $(function () {
            $.getJSON(URL , function (data) {
                console.log(data);
            });
        });
    }
 </script>
</head>

<body>
<form>
    link:
    <input id="textboxID" type="text">
    <input onclick="myFunction()" type="submit">
</form>
</body>

</html>

Solution

  • It works by removing form tag,

    <head>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>
    
    <script>
     function myFunction() {
         var URL = document.getElementById('textboxID').value;
        $(function () {
            $.getJSON(URL , function (data) {
                console.log(data);
            });
        });
    }
     </script>
    </head>
    
    <body>
    link:
    <input id="textboxID" type="text">
    <input onclick="myFunction()" type="submit">
    
    </body>
    
    </html>