I have a problem with getting the specific data based on my id.
This is my main html.
<div class="container">
<div class="row">
<div class="col-md-12">
<button id="btn">Button</button>
<br>
<div id="id01"></div>
</div>
</div>
</div>
This is my main js
var btn=document.getElementById("btn");
btn.addEventListener("click", function(){
var ourRequest = new XMLHttpRequest();
var url = "url.../incident";
contentType="applicaton/json; charset=utf-8";
method="GET";
dataType= "json";
ourRequest.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
ourRequest.open("GET", url, true);
ourRequest.send();
});
function myFunction(response) {
var arr = JSON.parse(response);
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Address +
"</td><td><a href='lista.html?id="+arr[i].ID+"'>" +
arr[i].ID +
"</a></td><td>" +
arr[i].Category +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
This will show me only three data.
this is my lista.html
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="id02">
</div>
</div>
</div>
And this is my js for my lista.html.
var ourRequest = new XMLHttpRequest();
var url = "url../incident?id=";
contentType="applicaton/json; charset=utf-8";
method="GET";
dataType= "json";
ourRequest.onreadystatechange=function()
{
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
ourRequest.open("GET", url, true);
ourRequest.send();
function myFunction(response)
{
var arr = JSON.parse(response);
var out = "<table>";
out +="<tr><td>" +
arr.Address +
"</td><td>" +
arr.CaseID +
"</td><td>" +
arr.Category +
"</td><td>" +
arr.Date +
"</td><td>" +
arr.Description +
"</td><td>" +
arr.ID +
"</td><td>" +
arr.InputDate +
"</td><td>" +
arr.Latitude +
"</td><td>" +
arr.Longitude +
"</td><td>" +
arr.ReportedBy +
"</td><td>" +
arr.Subcategory +
"</td><td>" +
arr.Time +
"</td></tr>"
out += "</table>";
document.getElementById("id02").innerHTML = out;
}
So when I click on that arr[i].ID it should send me to th lista.html with the specific ID and specific data.
For example if i click on ID=1, the url look like lista.html?id=1, but nothing shows.
Just pass the id to the request url if the api you send request to expects that
var url = "url?id={your id here}"
In your table you have to use arr.Address instead of response.Address, since the arr is the parsed json object.
You can use console.log to see if the data you need is really there:
function myFunction(response) {
var arr = JSON.parse(response);
console.log(arr);
}
You don't need to read the location href with jQuery, since you already know the id of the request you sent!
So My mistake was like this instead of :
var url = "url../incident?id=";
I should have written :
var url = "url../incident?id="+getQueryVariable("id");
And write this function in the end of my js for my lista.html
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
Related
After using he JSON.stringify() method in JavaScript to allow JSON data render in the browser it outputs double quotations " " at either end of the property rendered in the browser - any idea how to resolve this?
Here is my code -
<li class="divider">Brown Eyes</li>
<div id="output1"></div>
<li class="divider">Green Eyes</li>
<div id="output2"></div>
<script>
var myContainer = "";
var a = new XMLHttpRequest();
a.open("GET", "https://api.myjson.com/bins/1dwnm", true);
a.onreadystatechange = function () {
console.log(a);
if (a.readyState == 4) {
var obj = JSON.parse(a.responseText);
for (i = 0; i < obj.length; i++) {
if (obj[i].eyeColor == 'brown') {
var myContainer = "<ul class='list'><li>" + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + "</li></ul>";
var myContainer = JSON.stringify(myContainer);
document.getElementById('output1').innerHTML += myContainer;
}
if (obj[i].eyeColor == 'green') {
var myContainer = "<ul class='list'><li>" + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + "</li></ul>";
var myContainer = JSON.stringify(myContainer);
document.getElementById('output2').innerHTML += myContainer;
}
}
}
}
a.send();
</script>
Because "<ul class='list'><li>Faye Garrett - brown</li></ul>" is not a valid JSON string.
Uncomment your stringify lines and it works.
I am trying to insert pictures to id "pokedex-view" by using Ajax GET. I think "spriteurl" is showing the correct path. But does not work correctly, and it cannot find the pciture for the local folder. Is there something wrong in this code. Thanks.
function populatePokedex() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all");
xhr.onload = function(){
if (this.status == 200) {
var picArr = this.responseText.split("\n");
for(var i=0; i < picArr.length; i++){
var eachName = picArr[i].split(":")
var spriteurl = "/Pokedex/sprites/" + eachName[1];
document.getElementById("pokedex-view").innerHTML += spriteurl
document.getElementById("pokedex-view").innerHTML += "<img src = spriteurl>";
}
} else {
document.getElementById("pokedex-view").innerHTML = "ERROR: Status: " + this.status + ", " + this.statusText;
}
}
xhr.onerror = function(){
document.getElementById("pokedex-view").innerHTML = "ERROR";
}
xhr.send();
}
Try to concatenate or to interpolate the way you assign the spriteurl as the src attribute:
document.getElementById("pokedex-view").innerHTML += '<img src="' + spriteurl + '">'
Or:
document.getElementById("pokedex-view").innerHTML += `<img src="${spriteurl}">`
I work with Twitch API. If the streamer streams I work with with property "Stream". But If he's not streaming, then I need refer to another link. Then I again turn to the function of the getJSON and pass there the necessary API link. And I'm working with her. However, the loop does not work as it should. It takes the last streamer out of the "channels" array, but it should all those who do not stream. I can not understand what the problem is. Help...
JSFiddle: https://jsfiddle.net/e7gLL25y/
JS Code:
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function() {
if(xhr.readyState == 4 && xhr.status == "200") {
callback(JSON.parse(xhr.responseText));
}
};
xhr.send();
};
var channels = ["summit1g", "esl_RuHub_CSGO", "Starladder1", "Senpai_Frozen", "tehvivalazz", "ESL_CSGO"];
var client_id = "hx3dea4ifwensxffoe8iwvekwvksnx";
var section = document.getElementById("main-section");
var streamer = [];
for(var i = 0; i < channels.length; i++) {
var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
getJSON(url_streams, function(response) {
if( response["stream"] !== null ) {
streamer[i] = document.createElement("div");
streamer[i].className = "streamer";
streamer[i].innerHTML = "<a target='_blank' href='" + response.stream.channel["url"] +
"'><img id='streamer-image' src='" +
response.stream.channel["logo"] +
"' alt='Av' /><h2 id='streamer-name'>" +
response.stream.channel["name"] +
"</h2><p id='stream-status'>" +
response.stream["game"] + "</p></a>";
section.appendChild(streamer[i]);
} else {
getJSON(url_channels, function(r) {
streamer[i] = document.createElement("div");
streamer[i].className = "streamer";
streamer[i].innerHTML = "<a target='_blank' href='" + r["url"] +
"'><img id='streamer-image' src='" +
r["logo"] +
"' alt='Av' /><h2 id='streamer-name'>" +
r["name"] +
"</h2><p id='stream-status'>Offline</p></a>";
section.appendChild(streamer[i]);
});
}
});
}
You are having a common misconception about JavaScript contexts.
Refer to my answer here to see details about this problem: https://stackoverflow.com/a/42283571/1525495
Simply, the getJSON response is called after all the array is looped, so i will be the last index in all the responses. You have to create another context to keep the i number so is not increased.
for(var i = 0; i < channels.length; i++) {
var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
(function(i) {
// i will not be changed by the external loop as is in another context
getJSON(url_streams, function(response) {
// Thingy things...
});
})(i);
}
I want to retrieve my database values and insert them into a table.
I am trying to iterate i onto an array.
However, it returns undefined and there is no output. Why is this so?
Could it be an issue with the script or the body tag?
Script
function getitemdetails() {
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/mycasefeed.php";
url += "?Case_ID=" + decodeURIComponent(getUrlVars()["Case_ID"]);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
getitemResult(xmlhttp.responseText);
};
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function getitemResult(response) {
var arr = JSON.parse(response);
var i;
for(i = 0; i < arr.length; i++) {
$("#mycase").append("<tr><td>" + arr[i].CaseDes +
arr[i].Case_Pic +
"<br>" + arr[i].categoryname +
"<br>" + arr[i].Caselat +
"<br>" + arr[i].Caselong +
"<br>" + arr[i].CaseTime +
"<br>" + arr[i].details + "</td></tr>");
}
$("#mycaseresult").table("refresh");
}
getitemdetails();
Body
<div id="SearchResult" class="ui-content">
<table data-role="table" data-mode="reflow" class="ui-responsive" id="mycaseresult">
<thead>
<tr>
*insert values here*
</tr>
</thead>
<tbody id="mycase">
</tbody>
</table>
</div>
the reason it is returned undefined is because the variable has no content.
In javascript, any empty variable (declared, but not defined) is undefined.
var a;
var b = {};
function foo(parameter) {
console.log(parameter);
}
console.log(a); // Outputs: `undefined`
console.log(b.cool); // Outputs: `undefined`
foo(); // Outputs: `undefined`
On your code, looks like you are trying to iterate on an array, but you don't have any iteration loop.
Try:
function getitemResult(response) {
var arr = JSON.parse(response);
for(var i=0; i < arr.length; i++) {
$("#mycase").append("<tr><td>" + arr[i].CaseDes +
arr[i].Case_Pic +
"<br>" + arr[i].categoryname +
"<br>" + arr[i].Caselat +
"<br>" + arr[i].Caselong +
"<br>" + arr[i].CaseTime +
"<br>" + arr[i].details + "</td></tr>");
}
}
I have this code from w3school works like a charm:
<!DOCTYPE html>
<html>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
but when I repeat the script like this it doesn't work:
<!DOCTYPE html>
<html>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
</script>
<h1>Buyers</h1>
<div id="id02"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id02").innerHTML = out;
}
</script>
</body>
</html>
What variable name should I change? I did the script once it worked but twice it didn't work.
I tried changing variable but it didn't work
I changed all the variable names.
Your two scripts exist in the same JS environment. They both create global variables with the same name and interfere with each other.
Wrap each script in an IIFE to create a new scope for each one to operate in.
<script>
(function () {
// Your code here
})();
</script>
It doesn't work because you're executing AJAX call across domains. You can't do an ajax call like that unless you are calling a page on the same domain. There are workarounds, but this is the problem in your case.
Instead create a local file to test your AJAX with.
This is why it works on the w3 Schools site, but not on your own code.