I am making a Pokedex API as a side project and I can not display the data needed to display in the different text boxes. I am using a GET request to request the height, weight, type, and ability.
<script>
$("button").click( function(){
var pokemonName = $('pokemon').val(pokemon);
event.preventDefault();
getPokemonData(pokemonName);
})
function getPokemonData(pokemonName){
var request = new XMLHttpRequest()
//GET request with link
request.open('GET','https://pokeapi.co/api/v2/pokemon/' + pokemonName, true);
// request for data
request.onload =function(){
var data = JSON.parse(this.response)
if(request.status >= 200 && request.status <= 400)
{
// outputs data
$(pokemonheight).val(response.height)
$(pokemonweight).val(response.weight)
$(pokemonAblity).val(response.ability)
$(pokemonType).val(response.type)
}
else
{
alert ("Error");
}
request.send();
}
}
</script>
</html>
I have tried setting a variable that would be equal to the response JSON element and then input that into the value of the textbox.
I do not have anything returned as expected or input displayed in the console if declared.
Issue(s)
There were a few issues with your code:
var pokemonName = $('pokemon').val(pokemon); you are setting the value of some element named pokemon (not valid) here
var data = JSON.parse(this.response); where is this.response being set? Shouldn't we be receiving response in the callback?
request.send(); is inside of the onload event, so the request never gets sent
Critiques
My main critique here is that you included a fairly large library (jQuery), and didn't utilize it to make the request. $.ajax is well documented and cleans up a lot of the intricacies of XMLHttpRequest.
The solution
$("button").click(function() {
var pokemonName = $('#pokemon').val();
//event.preventDefault();
getPokemonData(pokemonName);
})
function getPokemonData(pokemonName) {
var request = new XMLHttpRequest()
//GET request with link
request.open('GET', 'https://pokeapi.co/api/v2/pokemon/' + pokemonName, true);
// request for data
request.onload = function(response) {
var data = JSON.parse(response.currentTarget.response)
if (request.status >= 200 && request.status <= 400) {
// outputs data
console.log(data)
} else {
alert("Error");
}
}
request.send();
}
<input id="pokemon" value="12" />
<button>search</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Taking all the above issues into account, I was able to get a working example of what it should ultimately look like.
Hope this helps!
I have an HTML page with a button on it. When I click on that button, I need to call a REST Web Service API. I tried searching online everywhere. No clue whatsoever. Can someone give me a lead/Headstart on this? Very much appreciated.
I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.
The API includes a lot more, but start with the fetch() method. It takes two arguments:
A URL or an object representing the request.
Optional init object containing the method, headers, body etc.
Simple GET:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
Recreating the previous top answer, a POST:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
Your Javascript:
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "Your Rest URL Here", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
}
Your Button action::
<button type="submit" onclick="UserAction()">Search</button>
For more info go through the following link (Updated 2017/01/11)
Here is another Javascript REST API Call with authentication using json:
<script type="text/javascript" language="javascript">
function send()
{
var urlvariable;
urlvariable = "text";
var ItemJSON;
ItemJSON = '[ { "Id": 1, "ProductID": "1", "Quantity": 1, }, { "Id": 1, "ProductID": "2", "Quantity": 2, }]';
URL = "https://testrestapi.com/additems?var=" + urlvariable; //Your URL
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.open("POST", URL, false);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.setRequestHeader('Authorization', 'Basic ' + window.btoa('apiusername:apiuserpassword')); //in prod, you should encrypt user name and password and provide encrypted keys here instead
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.send(ItemJSON);
alert(xmlhttp.responseText);
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";
}
function callbackFunction(xmlhttp)
{
//alert(xmlhttp.responseXML);
}
</script>
<html>
<body id='bod'><button type="submit" onclick="javascript:send()">call</button>
<div id='div'>
</div></body>
</html>
$("button").on("click",function(){
//console.log("hii");
$.ajax({
headers:{
"key":"your key",
"Accept":"application/json",//depends on your api
"Content-type":"application/x-www-form-urlencoded"//depends on your api
}, url:"url you need",
success:function(response){
var r=JSON.parse(response);
$("#main").html(r.base);
}
});
});
I think add if (this.readyState == 4 && this.status == 200) to wait is better:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = xhttp.responseText;
console.log("ok"+response);
}
};
xhttp.open("GET", "your url", true);
xhttp.send();
If that helps anyone, if you are ok with an external library then I can vouch for Axios, which has a pretty clean API and rich documentation to deal with REST calls, here's an example below:-
const axios = require('axios');
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
});
Before we try to put anything on the front end of the website, let's open a connection the API. We'll do so using XMLHttpRequest objects, which is a way to open files and make an HTTP request.
We'll create a request variable and assign a new XMLHttpRequest object to it. Then we'll open a new connection with the open() method - in the arguments we'll specify the type of request as GET as well as the URL of the API endpoint. The request completes and we can access the data inside the onload function. When we're done, we'll send the request.
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function () {
// Begin accessing JSON data here
}
}
// Send request
request.send()
By far, the easiest for me is Axios. You can download the node module or use the CDN for your simpler projects.
CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Code example for GET/POST:
let postData ={key: "some value"}
axios.get(url).then(response =>{
//Do stuff with the response.
})
axios.post(url, postData).then(response=>{
//Do stuff with the response.
});
Without a doubt, the simplest method uses an invisible FORM element in HTML specifying the desired REST method. Then the arguments can be inserted into input type=hidden value fields using JavaScript and the form can be submitted from the button click event listener or onclick event using one line of JavaScript. Here is an example that assumes the REST API is in file REST.php:
<body>
<h2>REST-test</h2>
<input type=button onclick="document.getElementById('a').submit();"
value="Do It">
<form id=a action="REST.php" method=post>
<input type=hidden name="arg" value="val">
</form>
</body>
Note that this example will replace the page with the output from page REST.php.
I'm not sure how to modify this if you wish the API to be called with no visible effect on the current page. But it's certainly simple.
Usual way is to go with PHP and ajax. But for your requirement, below will work fine.
<body>
https://www.google.com/controller/Add/2/2<br>
https://www.google.com/controller/Sub/5/2<br>
https://www.google.com/controller/Multi/3/2<br><br>
<input type="text" id="url" placeholder="RESTful URL" />
<input type="button" id="sub" value="Answer" />
<p>
<div id="display"></div>
</body>
<script type="text/javascript">
document.getElementById('sub').onclick = function(){
var url = document.getElementById('url').value;
var controller = null;
var method = null;
var parm = [];
//validating URLs
function URLValidation(url){
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var x = url.split('/');
controller = x[3];
method = x[4];
parm[0] = x[5];
parm[1] = x[6];
}
}
//Calculations
function Add(a,b){
return Number(a)+ Number(b);
}
function Sub(a,b){
return Number(a)/Number(b);
}
function Multi(a,b){
return Number(a)*Number(b);
}
//JSON Response
function ResponseRequest(status,res){
var res = {status: status, response: res};
document.getElementById('display').innerHTML = JSON.stringify(res);
}
//Process
function ProcessRequest(){
if(method=="Add"){
ResponseRequest("200",Add(parm[0],parm[1]));
}else if(method=="Sub"){
ResponseRequest("200",Sub(parm[0],parm[1]));
}else if(method=="Multi"){
ResponseRequest("200",Multi(parm[0],parm[1]));
}else {
ResponseRequest("404","Not Found");
}
}
URLValidation(url);
ProcessRequest();
};
</script>
I have to make a chat with JSP, AJAX and Java and I have a problem: when I try to use my variable to store value of a input text, this variable is null.
If I add 'action' property to the form, the variable 'textParam' will have the value of the input text, but, if I do that I have to redirect with action to a page and I don't what that.
I need to process something bigger in the JSP page and then to reload in the HTML page (which is a JSP page) (the reload part is not on actual probem).
How I can make to populate 'textParam' with the input text value when I press the button?
PS: I need to make it with pure javascript, not with some libraries :)
The JSP which have to process is:
String textParam = request.getParameter("chatMessage");
System.out.println("textParam = " + textParam);
My form it look like that:
<form id="frmmain" name="frmmain" onsubmit="return blockSubmit();">
<input type="text" id="chatMessage" name="chatMessage" style="width: 447px;" />
<input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onclick="sendChatText();" />
</form>
The .js file it's this:
var request = getXmlHttpRequestObject();
var response = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function sendChatText() {
if(document.getElementById('chatMessage').value == '') {
alert("You have not entered a message");
return;
}
if (request.readyState == 4 || request.readyState == 0) {
request.open("POST", 'getChat2.jsp?chat=1&last=' + lastMessage, true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('chatMessage').value;
param += '&chat=1';
request.send(param);
document.getElementById('chatMessage').value = '';
}
}
function handleSendChat() {
clearInterval(mTimer);
getChatText();
}
function blockSubmit() {
sendChatText();
return false;
}
The problem is here:
String textParam = request.getParameter("chatMessage");
I was trying to get 'chatMessage' parameter, which it was only the name of the input. The solve is to get 'message' param which it was defined and requested in js:
String textParam = request.getParameter("message");
I want to upload a file trough a XMLHttpRequest. i have looked everywhere for examples and found quite a few. But i cant figer out what it is i am doing wrong. This is my code. The function is triggerd when a button is pressed. It not wrapped in from tags
function upl_kost() {
var url = "proces_data.php?ref=upload_kost";
var hr;
var file = document.getElementById("file_kost");
var formData = new FormData();
formData.append("upload", file.files[0]);
if (window.XMLHttpRequest) {
hr=new XMLHttpRequest();
} else {
hr=new ActiveXObject("Microsoft.XMLHTTP");
}
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "multipart/form-data");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
alert(return_data);
}
}
hr.send(formData);
}
and this function catches it.
if($_GET['ref'] == 'upload_kost') {
var_dump($_FILES);
}
My problem is that the $_FILES stays empty. When i look at the file.files variable in the js its loaded with the data from the file that i am trying to upload.
Thanks!
Reduce your JavaScript down to minimum required for this, then add in some helpful messages you can look in your console for
function upl_kost() {
var xhr = new XMLHttpRequest(),
url = 'proces_data.php?ref=upload_kost',
fd = new FormData(),
elm = document.getElementById('file_kost');
// debug <input>
if (!elm)
console.warn('Element not found');
else if (!(elm instanceof HTMLInputElement))
console.warn('Element not an <input>');
else if (!elm.files || elm.files.length === 0)
console.warn('<input> has no files');
else
console.info('<input> looks okay');
// end debug <input>
fd.append('upload', elm.files[0]);
xhr.addEventListener('load', function () {
console.log('Response:', this.responseText);
});
xhr.open('POST', url);
xhr.send(fd);
}
If you're still having a problem, it may be server-side, e.g. are you performing a redirect before trying to access $_FILES?
Your problem is that you're setting the content type of the request
hr.setRequestHeader("Content-type", "multipart/form-data");
If you ever saw a multipart/formdata post you'll notice the content type header has a boundary
Content-Type: multipart/form-data; boundary=----webko2354645675756
which is missing from your code.
If you do not set the content type header the browser will correctly set it and the required boundary. This will allow the server to properly parse the request body.
I have the following script, a few lines up from the bottom I have a window.location.href which posts the reults from my form though the address bar. This is very messy and I would like to use POST instead of GET, any ideas anyone ?
<script language="javascript">
function OnChangedUsername()
{
if(document.signup.newuserid.value == "")
{
document.signup.btnCheckAvailability.disabled = true;
}
else
{
document.signup.btnCheckAvailability.disabled = false;
}
}
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq() {
http.open('get', 'password_check.asp?emailaddress=<%Response.Write(emailaddress)%>&check=<%Response.Write(check)%>&password_check='+document.signup.newuserid.value);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if(http.readyState == 4){
var response = http.responseText;
var update = new Array();
if(response.indexOf('|' != -1)) {
update = response.split('|');
document.getElementById("username_chk").innerHTML = update[0];
if(document.getElementById("username_chk").innerHTML == "Ok") {
window.location.href='detailsupdate.asp?username=<%Response.Write(sUsername)%>&check=<%Response.Write(check)%>&EmailAddress='+document.signup.EmailAddress.value+'&Address='+document.signup.Address.value+'&Address1='+document.signup.Address1.value+'&Address2='+document.signup.Address2.value+'&City='+document.signup.City.value+'&PostalCode='+document.signup.PostalCode.value+'&Country='+document.signup.Country.value+'&WorkPhone='+document.signup.WorkPhone.value+'&HomePhone='+document.signup.HomePhone.value+'&MobilePhone='+document.signup.MobilePhone.value+'&FaxNumber='+document.signup.FaxNumber.value+'&AlternativePhone='+document.signup.AlternativePhone.value+'&OO='+document.signup.OO.checked+'&Workshop='+document.signup.Workshop.checked+'&Raised='+document.signup.Raised.checked+'&Ground='+document.signup.Ground.checked+'&pd='+document.signup.newuserid.value+'&Tram='+document.signup.Tram.checked;
}
}
}
}
</script>
The only way to make a POST request with the response rendered directly into the browser window is to use a form (which you generate with DOM) and submit it (which you can likewise do through DOM).
The alternative is to use XMLHttpRequest (or some other Ajax technique) and render the response with DOM.
There is no need to pass form data as GET data. You can specify the method as POST.
<form action="script.asp" method="post">
...
<input type="submit" value="submit">
</form>
You also should not be using window.location.href. This is very ugly. When you submit the form (click the submit button) it will POST your form data to script.asp.
Another way to submit your form is to submit it via DOM. document.forms[0].submit();