I am trying to have a user type in a username in a field on the HTML page. After they click submit I would like that variable to be used in an API payload. After that API call is made, I would like to output the JSON response on the HTML page.
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tool</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Tool</h1>
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<input id="submit" type="submit" value="Submit">
</form>
<script src="scripts.js"></script>
<div id="result"></div>
</body>
</html>
I am trying to add the username to the end of the API URL (https://classification.svc.com/v1/users/{{variable}})
FYI: The API key and URL are scrambled to stay confidential, but done correctly it will return a few JSON objects. I’m not worried about formatting. I just want it to be output to the HTML document.
Javascript:
document.getElementById('myForm').onsubmit = function() {
var thetext = (document.getElementById('username').value);
return false;
};
var settings = {
"url": "https://cors-anywhere.herokuapp.com/https://classification.svc.com/v1/users/" + thetext,
"method": "GET",
"timeout": 0,
"headers": {
"Accept": "application/json",
"x-api-key": "sh435ysdfgh"
},
};
$.ajax(settings).done(function (response) {
console.log(response);
});
2
Answers
The
.onsumbit
method is not synchronous, so you have to move the rest of the code into the function.Assuming you want to use the div with the "result" id to show the response.
With plain JavaScript:
With jQuery: