data is not showing in dropdown - javascript

I am very new in javascipt infact this is my first program.
i have written html javascrpit code to shoow data in dropdown from python django databse but when i run it, it is not showing data my code is
<!DOCTYPE html>
<html>
<title>CP Project</title>
<head>
</head>
<body>
Country : <select class="country" onchange="changeCountry(this)">
</select><br/>
State :
<select class="state" onchange="changeState(this)">
</select><br/>
City :
<select class="city" onchange="changeCity(this)">
</select>
<script>
var country = document.querySelector(".country");
var state = document.querySelector(".state");
var city = document.querySelector(".city");
var countryList = {};
var stateList = {};
var cityList = {};
// Access-Control-Allow-Origin: http://127.0.0.1:8002/data/ ;
Access-Control-Allow-Methods: POST, GET, OPTIONS;
getCountryList(function(response){
countryList = response;
var tempStr = "";
/*for(var i in response.result){
tempStr+="<option value="+i+">"+response.result[i]+"</option>";
}*/
for(var i=0;i<response.length; i++){
tempStr+="<option value="+response[i].countryId+">"+response[i].country+"</option>";
}
country.innerHTML = tempStr;
});
function changeCountry(this_){
getStateList(this_.value, function(response){
stateList = response;
var tempStr = "";
/*for(var i in response.result){
tempStr+="<option value="+i+">"+response.result[i]+"</option>";
}*/
for(var i=0;i<response.length; i++){
tempStr+="<option value="+response[i].state_id+">"+response[i].state+"</option>";
}
http.open("GET", "http://127.0.0.1:8002/data/country/", true);
http.send();
state.innerHTML = tempStr;
});
}
function changeState(this_){
getCityList(this_.value, function(response){
cityList = response;
var tempStr = "";
/*for(var i in response.result){
tempStr+="<option value="+i+">"+response.result[i]+"</option>";
}*/
for(var i=0;i<response.length; i++){
tempStr+="<option value="+response[i].cityid+">"+response[i].city+"</option>";
}
city.innerHTML = tempStr;
});
}
function getCountryList(callBackFun){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if (this.readyState === 4){
callBackFun(JSON.parse(this.responseText));
}
};
http.open("GET", "http://127.0.0.1:8002/data/country/", true);
http.send();
}
function getStateList(countryCode, callBackFun){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if (this.readyState === 4){
callBackFun(JSON.parse(this.responseText));
}
};
http.open("GET", "http://127.0.0.1:8002/data/state?count_id="+countryCode, true);
http.send();
}
function getCityList(stateCode, callBackFun){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if (this.readyState === 4){
callBackFun(JSON.parse(this.responseText));
}
};
http.open("GET", "http://127.0.0.1:8002/data/cities/?sta_id="+stateCode, true);
http.send();
}
</script>
</body>
</html>
it is showing two warning
1.SyntaxError: missing ; before statement
2.The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.

Well, you're probably missing a semicolon.
And adding
<meta charset="UTF-8">
should solve the bottom error.

Related

JSON print to HTML

Any idea what's the best way to get json from webhook to HTML?
I already got to the step where I can print the json from the webhook and a json in script and It looks THE SAME but the one from webhook gives "undefined".
<body>
<h2>Print from Integromat</h2>
<p id="demo"></p>
<script>
let xhr = new XMLHttpRequest();
xhr.open("POST", "https://hook.integromat.com/xyxyxyxyxyxyxyxyxyx", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function(e) {
// Error...
if (this.status != 200) return alert("Error")
// Success..
let json = JSON.stringify(this.response);
let text = "";
for(let i = 0; i < json.length; i++) {
let obj = json[i];
text += obj.firstname + "<br>";
text += obj.email + "<br><hr>"
}
document.getElementById("demo").innerHTML = text;
}
xhr.send(JSON.stringify({
//JSON to send
date: new Date(),
}));
</script>
</body>
Thanks a lot!

Returning the XML received on readystatechange - JavaScript

This is my first post here on Stack. I am trying to make a Get request which is succeeding but I am having trouble getting the responseXML into a variable for processing. I think I am supposed to be using a callback function, but I still can't get it quite right. I am hopeful that somebody can point me in the correct direction. Code below.
<script type="text/javascript">
function buildOptions() {
var data = null;
/*xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
callback.call(xhr.responseXML);
}
});*/ //This code block worked, but I couldn't figure out how to get the result back
getXML = function(callback) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
}
}
function XMLCallBack(data) {
alert(data); // These two functions were the most recent attempt but I'm still missing something
}
xmlDoc = getXML(XMLCallBack); // this is supposed to start the processing of the returned XML
console.log(xmlDoc);
var campaignName = xmlDoc.getElementsByTagName('self')[0]; //XMLDoc contains a null variable when I get to this line
console.log(campaignName);
var campaigns = ["","Freshman Campaign","Sophomore Campaign","Junior Campaign","Senior Campaign"]; //Code from here and below will be changing slightly once I can get XMLDoc to be correct
var sel = document.getElementById('campaignList');
for(var i = 0; i < campaigns.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = campaigns[i];
opt.value = campaigns[i];
sel.appendChild(opt);
}
}
</script>
I believe you should move open ---> send outside the onreadystatechange, like this:
getXML = function(callback) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
}
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
}
EDIT: This code should work:
<script type="text/javascript">
function buildOptions() {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = XMLCallBack;
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
function XMLCallBack() {
if (xhr.readyState == 4 && xhr.status == 200) {
xmlDoc = xhr.responseText;
var campaignName = xmlDoc.getElementsByTagName('self')[0];
var campaigns = ["","Freshman Campaign","Sophomore Campaign","Junior Campaign","Senior Campaign"];
var sel = document.getElementById('campaignList');
for(var i = 0; i < campaigns.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = campaigns[i];
opt.value = campaigns[i];
sel.appendChild(opt);
}
}
}
}
</script>
I haven't tried it so I might have made some mistakes. If you want to, you can move XMLCallBack() outside of buildOptions() and use this.readyState, this.status and this.responseText instead of xhr.readyState etc..

reference error can't find xmlhttp

Trying to get my code to connect to API and retrieve a list of local farmers markets but keep getting Reference error that xmlhttp is not defined on line 40. Haven't caught any spelling errors and have tried moving chunks of code to see if they work at different positions.
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<title>Markets</title>
<script>
window.onload = function() {
function myFunction(arr) {
out = "<h1>Markets</h1>";
var i;
for (i = 0; i < array.results.length; i++) {
out = out + "<em>" + item.marketname + "</em><br>" + details.marketdetails.Address + "</p>"
arr.results.forEach(printDetails)
}
document.getElementById("market_details").innerHTML = out;
}
var mybutton = document.getElementById("submit_btn")
mybutton.onclick = function() {
var xmlhttp = new XMLHttpRequest();
var zip = document.getElementById("zip").value
var url = "http://search.ams.usda.gov/farmersmarkets/v1/data.svc/zipSearch?zip=" + zip;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
itemsProcessed = 0
function printDetails(item, index, array) {
console.log(item.marketname)
var xmlhttp = new XMLHttpRequest();
var url2 = "http://search.ams.usda.gov/farmersmarkets/v1/data.svc/mktDetail?id=" + id;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myDArr = JSON.parse(xmlhttp.responseText);
details = myDArr
//console.log(myDArr.marketdetails)
};
xmlhttp.open("GET", url2, true);
xmlhttp.send();
itemsProcessed++
}
}
</script>
</head>
<body>
<h1> Find Your Local Market!<h1>
Enter Zip Code:<input id="zip"></p><br>
<button id = "submit_btn">Submit</button>
<div id="market_details"></div>
</body>
The first problem is that you define the xmlhttp inside the onclick handler and you use it outside the handler:
mybutton.onclick = function() {
var xmlhttp = new XMLHttpRequest(); //<-- This must be used from inside the current function
//Your code here
xmlhttp.open("GET", url, true); //<-- put this inside the function
xmlhttp.send(); //<-- put this inside the function
}
The second problem is that you open and send the XMLHttpRequest inside the onreadystatechange handler:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myDArr = JSON.parse(xmlhttp.responseText);
details = myDArr
//console.log(myDArr.marketdetails)
};
itemsProcessed++
}
xmlhttp.open("GET", url2, true);//<-- put this outside the onreadystatechange handler
xmlhttp.send();//<-- put this outside the onreadystatechange handler
I hope this will help you.

Value of list populated with javascript

How to populate the select list with the values that I got with javascript?
I am sending a GET request to a .php site which gives me the respond in JSON format. Now I want to put those lines I got into the select list.
<select id = "list" name=log size=50 style=width:1028px>
<script type="text/javascript">
window.onload = function () {
var bytes=0;
var url = "/test/log.php?q='0'";
function httpGet(url)
{
var xhttp = new XMLHttpRequest();
var realurl = url + bytes;
xhttp.open("GET", url, true);
xhttp.onload = function (e) {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
console.log(xhttp.responseText);
var response=JSON.parse(xhttp.responseText);
var log = response.key;
bytes = log.length;
}
};
xhttp.onerror = function (e) {
console.error(xhttp.statusText);
}
};
xhttp.send();
}
var updateInterval = 2000;
function update() {
httpGet(url);
setTimeout(update, updateInterval);
}
update();
}
</script>
</select>
The response I get from log.php is "{"key":"whole log file"}". Now I want to store that reponse into a list and populate it every 2 seconds.
Loop over the contents of the returned string after JSON.parse-ing it. Create option elements from it, and insert those into the select.
var html = "";
var obj = JSON.parse(xhttp.responseText);
for(var key in obj) {
html += "<option value=" + key + ">" +obj[key] + "</option>";
}
document.getElementById("list").innerHTML = html;
See JSBin

JSON response returning null array

Please help i have been trying from 1 hours and not able to get whats wrong
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out = arr[i].ID + arr[i].Title + arr[i].Description;
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
I am trying to fetch details from http://it-ebooks-api.info/v1/book/2279690981 but it show only empty array being returned. What changes are required ?
Modification
I added [ ] on JSON object and it worked .. Please can someone explain me.
Thank in advance :)
The response does not contain an array, so the for loop is not needed and this should get you the result you are looking for:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myresponse = JSON.parse(xmlhttp.responseText);
myFunction(myresponse);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var out = "";
var i;
out = "<p>" + response.ID + response.Title + response.Description + "<p>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
If you use the full listing available from http://it-ebooks-api.info/v1/search/php, then you need the for loop to go through the array like this:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myresponse = JSON.parse(xmlhttp.responseText);
myFunction(myresponse.Books);
}
}
function myFunction(Books) {
var out = "";
for (var i = 0; i < Books.length; i++) {
out += "<p>ID: " + Books[i].ID + "</p>" + "<p>Title: " + Books[i].Title + "</p>" + "<p>Description: " + Books[i].Description + "</p>"
}
document.getElementById("id01").innerHTML = out;
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>
And to make it slightly more elegant, you could have a function that adds the book and if you get only one book you can call it directly from the onreadystatechange, and if you have the full listing, then you can loop it through, but still use the same function. So something like this:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = JSON.parse(xmlhttpo.responseText);
if (response.Books) { // If the response object has Books array, we pass it to the parseBooks functoin to add them all one by one.
parseBooks(response.Books)
} else {
addBook(response); // If there is no Books array, we assume that there is only one book and add it to the list with addBook function.
}
}
}
function addBook (Book) {
var text = document.getElementById("id01").innerHTML;
var body = "<p>ID: " + Book.ID + "</p><p>Title: " + Book.Title + "</p><p>Description: " + Book.Description + "</p>";
document.getElementById("id01").innerHTML = text + body; // Append the innerHTML with the new Book.
}
function parseBooks(Books) {
for (var i = 0; i < Books.length; i++) {
addBook(Books[i]) // Add all books in the array one by one
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>
You JSON feed is just a simple object and not an Array of objects. Note the opening curly braces in the returned feed: {}
You should then change your myFunction function so it goes through an object and not an array just by removing the for loop:
function myFunction(obj) {
var out = "",
id01 = document.getElementById("id01");
out = obj.ID + obj.Title + obj.Description;
id01.innerHTML = id01.innerHTML + out;
}
Edit:
You can use the same function then inside a for loop when you have to parse an Array of Objects.
Taking as a feed the JSON returned from http://it-ebooks-api.info/v1/search/php, you can retrieve the Books value and then loop through it:
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
var url2 = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var rslt = JSON.parse(xmlhttp.responseText);
console.log(rslt);
var books = rslt.Books;
for (var i = 0; i < books.length; i++)
{
myFunction(books[i]);
}
}
}
xmlhttp.open("GET", url2, true);
xmlhttp.send();

Categories

Resources