I'm trying to get data from a xml file and show inside inputs, but I need to get a parameter from a input.
This code is working when just click on the button, but it return the xml file with the parameter 'sbbr'
this is my code:
<script>
var icaocode = 'sbbr'
var client;
if (window.XMLHttpRequest) {
client = new XMLHttpRequest();
} else {
client = new ActiveXObject("Microsoft.XMLHTTP");
}
client.open('GET', 'https://mywebsite.com/api/?icaoCode=' + icaocode, true);
function buscarFunction() {
var xmlDoc = client.responseXML;
var heliponto = xmlDoc.getElementsByTagName("aisweb");
for (i = 0; i < heliponto.length; i++) {
data = heliponto[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
city = heliponto[i].getElementsByTagName("city")[0].childNodes[0].nodeValue;
org = heliponto[i].getElementsByTagName("rmkText")[0].childNodes[0].nodeValue;
}
document.getElementById('nome').value = data;
document.getElementById('cidade').value = city;
document.getElementById('org').value = org;
}
client.send();
</script>
<input id="icao"><button type="button" onclick="buscarFunction()">Buscar</button><Br>
<input id="nome"><br>
<input id="cidade"><br>
<input id="org">
I need to get this paramenter from here:
<input id="icao"><button type="button" onclick="buscarFunction()">Buscar</button>
but is not populating the variable icaocode, I have tryed this:
var icaocode = document.getElementById('icao').value;
client.open('GET', 'https://mywebsite.com/api/?icaoCode=' + icaocode, true);
Try putting your <script> below the <body> tag after all elements have finished rendering. I think what's happening is that document.getElementById('icao') is returning null because there is no element with ID icao yet.
I fixed, found a solution.
just needed to add the function onload and put all the code inside the main function like this:
<input id="icao"><button type="button" onclick="buscarFunction()">Buscar</button><Br>
<input id="nome"><br>
<input id="cidade"><br>
<input id="org">
<script>
function buscarFunction() {
var icaocode = document.getElementById('icao').value;
var client;
if (window.XMLHttpRequest) {
client = new XMLHttpRequest();
} else {
client = new ActiveXObject("Microsoft.XMLHTTP");
}
client.open('GET', 'https://mywebsite.com/api/?icaoCode=' + icaocode, true);
client.send();
client.onload = function () {
var xmlDoc = client.responseXML;
var heliponto = xmlDoc.getElementsByTagName("aisweb");
for (i = 0; i < heliponto.length; i++) {
data = heliponto[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
city = heliponto[i].getElementsByTagName("city")[0].childNodes[0].nodeValue;
org = heliponto[i].getElementsByTagName("rmkText")[0].childNodes[0].nodeValue;
}
document.getElementById('nome').value = data;
document.getElementById('cidade').value = city;
document.getElementById('org').value = org;
};
}
</script>
and after that storage the variable from the input:
var icaocode = document.getElementById('icao').value;
Related
I am very new to JS and I have a problem to create a searchable movie reviewer html page, it is very basic, I just want to know how to have the input box search the NYT API for the movie I am looking for, I wont have a problem putting the elements onto the page, I just want to know how to search properly. I expect I need a function that when the search button is clicked it requests from the site all movies with the words provided.
<div id="search">
<input type="text" id = "search">
<button onclick="search()">Search</button>
</div>
<textarea id="APIoutput" cols="90" rows="50"></textarea>
const ISFINISHED = 4;
const ISOK = 200;
var searchedMovie = document.getElementById("search").value;
function getJSONSync(url){
var response = "";
var xmlHttp = new XMLHttpRequest();
if(xmlHttp !== null){
xmlHttp.open("GET", url, false);
xmlHttp.send(null);
response = xmlHttp.responseText;
}
return response;
}
function getJSONAsync(url, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === ISFINISHED && request.status === ISOK) {
callback(this);
}
};
request.open("GET", url);
request.send();
}
function search(searchedMovie){
var my_api_url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json?query=" + searchedMovie + "&api-key=" + API;
return my_api_url;
}
function handleAPIresponse(response) {
var textArea = document.getElementById("APIoutput");
textArea.value = response.responseText;
}
getJSONAsync(my_api_url, handleAPIresponse);
ERRORS: Uncaught ReferenceError: my_api_url is not defined
Expected Results: (UNFORMATTED JSON THAT LOOKS LIKE THIS:)
{"status":"OK","copyright":"Copyright (c) 2021 The New York Times
Company. All Rights
Reserved.","has_more":false,"num_results":10,"results":[{"display_title":"The
Black Godfather","mpaa_rating":"TV-MA","critics_pick":0,"byline":"BEN
KENIGSBERG","headline":"‘The Black Godfather’ Review: The Music
Executive Who Made It All Happen"
i'm trying to make auto complete with pure javascript.
Scenario is when type to input some letters it will search movies from omdbapi.
I make it like that:
i have input which users can search movies, i have get data from input value:
<input type="text" class="form-control" id="searchMovie" value="">
and here i get movies and make html markup with javascript for show these results in html:
var searchInput = document.getElementById("searchMovie");
// get movie
searchInput.onkeydown = function() {
var searchData = document.getElementById("searchMovie").value;
if (searchData.length >= 3 ) {
var request = new XMLHttpRequest();
request.open('GET', 'http://www.omdbapi.com/?s=' + searchData + '&apikey=000000', true);
request.onload = function () {
// Begin accessing JSON data here
var data = JSON.parse(this.response);
const wrapper = document.createElement('div');
app.appendChild(wrapper);
var results = data;
if (request.status >= 200 && request.status < 400) {
console.log(data);
Object.keys(data.Search).map(function(key, index) {
console.log(data.Search[index].Title);
const searchResultsContainer = document.createElement('div');
searchResultsContainer.setAttribute('class', 'row');
const h1 = document.createElement('h1');
h1.textContent = data.Search[index].Title;
wrapper.appendChild(searchResultsContainer);
searchResultsContainer.appendChild(h1);
console.log(searchResultsContainer);
});
} else {
console.log('error');
}
};
request.send();
}
};
everything work well but problem is:
when i try to delete keyword which i wrote and write new one results not disappear from html, i want change
You need to capture the change in the text input. Adding your code to a function and binding the input to oninput function. When there is a change in the value of the input it will rerun the api call. Furthermore, you need to clear out the old result.
<input type="text" class="form-control" id="searchMovie" value="" oninput"apiCall()">
<script>
function apiCall(){
var searchInput = document.getElementById("searchMovie");
// get movie
searchInput.onkeydown = function() {
var searchData = document.getElementById("searchMovie").value;
if (searchData.length >= 3 ) {
while (document.getElementsByClassName('autoComplete')[0]) {
document.getElementsByClassName('autoComplete')[0].remove();
}
var request = new XMLHttpRequest();
request.open('GET', 'http://www.omdbapi.com/?s=' + searchData + '&apikey=000000', true);
request.onload = function () {
// Begin accessing JSON data here
var data = JSON.parse(this.response);
var wrapper = document.createElement('div');
wrapper.className = "autoComplete";
app.appendChild(wrapper);
var results = data;
if (request.status >= 200 && request.status < 400) {
console.log(data);
Object.keys(data.Search).map(function(key, index) {
console.log(data.Search[index].Title);
const searchResultsContainer = document.createElement('div');
searchResultsContainer.setAttribute('class', 'row');
const h1 = document.createElement('h1');
h1.textContent = data.Search[index].Title;
wrapper.appendChild(searchResultsContainer);
searchResultsContainer.appendChild(h1);
console.log(searchResultsContainer);
});
} else {
console.log('error');
}
};
request.send();
}
}
</script>
That should remove the wrapper element you added and its children and populate a new one with new data. I can't really test this to make sure it works as I can not see the rest of your code. But it should work. if not I can help you to figure out any errors.
Also, I would consider making wrapper just a hidden div that you can easily clear and unhide when needed. It would be much easier and you wouldn't need to add and remove so many elements. just wrapper.innerHTML = ""; then wrapper.innerHTML = newRowSet; and done
Instead of setting h1.textContent = data.Search[index].Title; update this to h1.innerHTML = data.Search[key].Title;
I am trying to input the value of the currency using the Value="AUD" as a starter. I am very new to JSON and AJAX. I cannot work out why there is an 404 error linked to JSON.parse and XMLHttpRequest, any advise of where I am going wrong would be much appreciated. Thanks in advance.
`enter code here`
<html lang="en">
<head>
</head>
<body>
<div id ="forex-info">
<p id="currencyList" class="currencyList" value ="AUD">Australia</p>
<p id="rateList" class="event"></p>
</div
<script type="text/javascript">
var tableContainer = document.getElementById("forex-info");
var ourRequest = new XMLHttpRequest();
var myData = "http://api.fixer.io/latest".rates;
ourRequest.open('GET', myData, true);
ourRequest.onload = function loading() {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
function renderHTML(data) {
var output = "";
for (var key in data)
{
output += "<p>" + key + output + "</p>"
}
}
};
</script>
</body>
The main issue is how your calling the api "http://api.fixer.io/latest".rates
You call rest endpoints by there address params or with query params.
Please see example below calling your specified endpoint. That should get you started
var myData = 'https://api.fixer.io/latest'
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let res = JSON.parse(xhttp.responseText)
Object.keys(res.rates).forEach((e)=>{
console.log(`${e}: ${res.rates[e]}`)
//Add your stuff here
})
}
};
xhttp.open("GET", myData, true);
xhttp.send();
This code is a part of my application, doesn't work on the tizen device while it work normally on the tizen simulator ... can anyone have a look and tell me why!! If it's a problem with the balise form or with the dom parser! Can anyone tell me how to solve it?
thx
<!DOCTYPE html>
<head>
</head>
<body>
<div id="result">
</div>
<div align="center">
<form name="myForm">
<button type="submit">go</button>
</form>
</div>
<script>
//var doc;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.sntri.com.tn/html_ar/result_tarif_horaire_sntri.php', true);
//xhr.setRequestHeader('Origin', 'www.sntri.com.tn');
//xhr.setRequestHeader('Allow-Control-Allow-Origin', '*');
xhr.send();
xhr.onreadystatechange = function() {
if(4 === xhr.readyState) {
if(200 === xhr.status) {
var parser = new DOMParser();
var doc = parser.parseFromString(xhr.responseText, 'text/html');
var myForm = document.forms.myForm;
//console.log(doc);
var selectDep = doc.getElementsByName('code_arret_dep')[0];
var selectArr = doc.getElementsByName('code_arret_arr')[0];
doc.getElementBy
//console.log(select);
myForm.appendChild(selectDep);
myForm.appendChild(selectArr);
//console.log(xhr.responseText);
myForm.onsubmit = function(e) {
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.sntri.com.tn/html_ar/result_tarif_horaire_sntri.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('code_arret_dep='+selectDep.value+'&code_arret_arr='+selectArr.value);
xhr.onreadystatechange = function() {
if(4 === xhr.readyState) {
if(200 === xhr.status) {
var parser = new DOMParser();
var doc = parser.parseFromString(xhr.responseText, 'text/html');
var result = document.getElementById('result');
var tablex = doc.getElementById('tablex');
//console.log(doc);
result.appendChild(tablex);
//console.log(xhr.responseText);
}
}
}
console.log(selectDep.value);
console.log(selectArr.value);
}
}
}
};
</script>
</body>
Do you add the internet privilege?
You can add the privilege in config.xml.
Open the config.xml on Tizen IDE.
Select the privileges tap.
Click the 'Add' button.
Select the http://tizen.org/privilege/internet
Run your application.
I have a multiple (and dynamic) number of inputs of type=file.
I want to create a FormData object out of them.
I need to manually append them to the object as I need access to their filenames for inserting into a database and therefore need to specify a filename is this format:
myFormData.append(name,file,filename);
HTML
<form id="my_form" enctype="multipart/form-data">
<input type="file" name="undefined" id="file_1" data-filename="image.jpg">
<input type="file" name="undefined" id="file_2" data-filename="image2.jpg">
<button>click</button>
</form>
jQuery
var myFormData = new FormData();
$(document).on("click", "button", function(e) {
e.preventDefault();
var inputs = $("#my_form input");
$.each(inputs,function(obj,v) {
var file = v.files[0];
var filename = $(v).attr("data-filename");
var name = $(v).attr("id");
myFormData.append(name, file, filename);
});
//alert(JSON.stringify(myFormData));
console.log(myFormData);
});
I don't think the object is being constructed properly and I haven't been able to correctly view the contents of the object to confirm this.
This is what I get in the console:
jsFiddle
http://jsfiddle.net/rwone/K7aMw/
There is no good way to see the contents of FormData. A trick would be to send it (POST) and look at the network status.
Example: http://jsfiddle.net/K7aMw/2/
$(document).on("click", "button", function (e) {
e.preventDefault();
var inputs = $("#my_form input");
$.each(inputs, function (obj, v) {
var file = v.files[0];
var filename = $(v).attr("data-filename");
var name = $(v).attr("id");
myFormData.append(name, file, filename);
});
var xhr = new XMLHttpRequest;
xhr.open('POST', '/echo/html/', true);
xhr.send(myFormData);
});
Then in the Network tab (F12) you'll see the added files when inspecting the headers.
//your files should be doing something here
var files = yourfileInput[type = file].files
//will upload
var formData = new FormData();
//other info request takes
formData.append("otherInfoKey", $("#otherInfoID").val())
//Now turn to files
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i])
}
//Request
var xhr = new XMLHttpRequest();
xhr.open("post", "/upload", true);
xhr.upload.onprogress = function(ev) {
var percent = 0;
if (ev.lengthComputable) {
percent = 100 * ev.loaded / ev.total;
//$("#yourprogress").width(percent + "%");
//or something like progress tip
}
}
xhr.onloadend = function(e) {
if (!/^2\d*$/.test(this.status)) {
alert(this.responseText)
}
}
xhr.onload = function(oEvent) {
if (xhr.status == 200) {
//go on
}
}
xhr.send(formData);