can someone show me how to send an variable to my php file out of that construct? i am new at ajax/javascript and i try to figure out my style for writing JS code. atm i like and understand that kind of version.
var ajax = new XMLHttpRequest();
var method = "POST"
var url = "data.php" //erweitern - später
var asynchronous = true
var button = document.getElementById("count")
var counter = 0;
button.onclick = function() {
counter += 2;
showMoreFood(counter)
};
ajax.open(method, url, asynchronous)
ajax.send()
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText)
var html =""
//for (var a = 0; a < data.length; a++) {
for (var a = 0; a < 2; a++) {
var firstname = data[a].name
var preis = data[a].preis
html += "<tr>"
html += "<td>" + firstname + "</td>"
html += "<td>" + preis + "</td>"
html += "</tr>"
}
document.getElementById("data").innerHTML = html
} // if
} // onready
what i tried:
var data = "variable1"
ajax.open(method, url, asynchronous, data)
in data.php
-----------
$variableA = $_POST['variable1'];
because i thought i could send the data within, but nope. thx and br
i got it. i just need to change that to
method = "GET"
url = "data.php?variable1=something"
and in the php file
$variableA = $_GET['variable1'];
and it works :) i dont think thats the right version to handle that but it works :)
Related
I'm trying to parse XML by using AJAX. However there were a few errors which i got saying my "html is not defined"
Basically what I want to do is to parse a specific amount of data from my XML codes and display it using HTML webpage .
The below is the list of bugs in console when I tried to run the script
at displayCountrylist (test2.html:136)
at handleStatusSuccess (test2.html:61)
at readyStateChangeHandler (test2.html:32)
at XMLHttpRequest.xhttp.onreadystatechange (test2.html:16)
I tried to do everything to debug but still failed. Any one help please?
<html>
<script>
function makeAjaxQueryCountrylist()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
readyStateChangeHandler(xhttp);
};
xhttp.open("GET", "A3_CtryData_dtd_Sample.xml", true);
xhttp.send();
}
function readyStateChangeHandler(xhttp)
{
if (xhttp.readyState == 4)
{
if(xhttp.status == 200)
{
handleStatusSuccess(xhttp);
}else
{
handleStatusFailure(xhttp);
}
}
}
function handleStatusFailure(xhttp){
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
function handleStatusSuccess(xhttp)
{
var xml = xhttp.responseXML;
var countrylistObj = parseXMLCountrylist(xml);
displayCountrylist(countrylistObj);
}
function parseXMLCountrylist(xml)
{
var countrylistObj = {};
var countrylistElement = xml.getElementsByTagName("CountryList")[0];
var recordElementList = countrylistElement.getElementsByTagName("CountryRecord");
countrylistObj.recordList = parseRecordElementList(recordElementList);
return countrylistObj;
}
function parseRecordElementList(recordElementList)
{
var recordList = [];
for(var i=0; i < recordElementList.length; i++)
{
var recordElement = recordElementList[i];
var recordObj = parseRecordElement(recordElement);
recordList.push(recordObj);
}
return recordList;
}
function parseRecordElement(recordElement)
{
var recordObj = {};
var countrycodeElement = recordElement.getElementsByTagName("country-code")[0];
recordObj.countrycode = Number(countrycodeElement.textContent);
var nameElement = recordElement.getElementsByTagName("name")[0];
recordObj.name = nameElement.textContent;
var alpha2Element = recordElement.getElementsByTagName("alpha-2")[0];
recordObj.alpha2 = alpha2Element.textContent;
var alpha3Element = recordElement.getElementsByTagName("alpha-3")[0];
recordObj.alpha3 = alpha3Element.textContent;
var capitalcityElement = recordElement.getElementsByTagName("capital-city")[0];
recordObj.capitalcity = capitalcityElement.textContent;
return recordObj;
}
function displayCountrylist(countrylistObj)
{
for(var i=0; i < countrylistObj.recordList.length; i++)
{
var recordObj = countrylistObj.recordList[i];
html += "country-code: " + recordObj.countrycode;
html += "<br />";
html += "name: " + recordObj.name;
html += "<br />";
html += "alpha-2: " + recordObj.alpha2;
html += "<br />";
html += "alpha-3: " + recordObj.alpha3;
html += "<br />";
html += "capital-city: " + recordObj.capitalcity;
html += "<br />";
}
var displayDiv = document.getElementById("display1");
displayDiv.innerHTML = html;
}
</script>
<body>
<button onClick="makeAjaxQueryCountrylist()"> Region Info I (Format: region-fmt-1.xsl)</button>
<br /><br />
<div id="display1">
</div>
</body>
</html>
There isn't any problem with my XML codes so it has to be some error from here.
You got that error html is not defined because you are using html variable without declaring it. So, before the line
html += "country-code: " + recordObj.countrycode;
you have to write
let html = '';
I'm using two functions to get some data from an API :
The first one request the data for each cycle, the second check if the payment has been done for each cycle.
All the data are placed in a common table. It seems that my issue come from the fact that I use a function in another function. It the that the second function executes itself only after the first one is complete.
https://codepen.io/anon/pen/XQOVVB?editors=1001
var obj, obj2, dbParam,dbParam2, xmlhttp, xmlhttp2, myObj, myObj2, x, y, txt, txt2 = "";
obj = { table: "cycle", limit: 10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
// Get the value of the inputbox
// KT1 adress for trial KT19www5fiQNAiqTWrugTVLm9FB3th5DzH54
var KT1 = $('#KT1').val();
xmlhttp.onreadystatechange = function() {
obj2 = { table: "cycle2", limit: 100 };
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table><tr bgcolor=#000000 color=White>"
txt += "<th>Cycle</th>"
//txt += "<th>Reward</th>"
txt += "<th>Paid</th>"
txt += "</tr>"
// Get the data of every cycle using API 1
for (x in myObj) {
// force x to 11 to get the condition PaymentCycle = cycle
x = 11;
cycle = myObj[x].cycle;
//balance = myObj[x].balance/1000000;
//TotalReward = myObj[x].rewards/1000000;
//stakingBalance = myObj[x].staking_balance/1000000;
//Share = balance/stakingBalance*100;
//DelegatorReward = Share*TotalReward/100;
// create line of the table
txt += "<tr>";
txt += "<td width=10% align=center>" + cycle + "</td>";
//txt += "<td width=10% align=center>" + Math.round(DelegatorReward*100)/100 + "</td>";
// here the CYCLE CHANGE CORRECTLY from 106 to 87
console.log("Cycle before function: " + cycle);
//API2 request
dbParam2 = JSON.stringify(obj2);
xmlhttp2 = new XMLHttpRequest();
xmlhttp2.onreadystatechange = function() {
if (this.readyState == 4 && (this.status == 200 || this.status == 0)) {
myObj2 = JSON.parse(this.responseText);
// ERROR HERE - ALWAYS GET THE DATA OF THE LAST CYCLE (87) instead of every cycle check with API1
// It seems that this fonction xmlhttp2 is executed only after xmlhttp is complete giving to cycle the last value of saved for cycle (87)
console.log("Cycle after function: " + cycle);
for (var y = 0; y < 30; y++) {
// Get the Paiement cycle which varies from 106 to 90
Block = myObj2[y].type.operations[0].op_level;
PaiementCycle = Math.round(Block/4096);
PaiementCycle = PaiementCycle - 6;
// If the Data entered in the input box = of the destination adress of API 2 and the cycle of API1 and API2 is the same then
// Here cycle is always = 87 (Last value of the API1 reading (before the function the cycle change from 106 to 87).
// I really don't understand why
if (KT1 == myObj2[y].type.operations[0].destination.tz && PaiementCycle == cycle) {
console.log("Get one");
console.log("Paiement Cycle : " + PaiementCycle);
Paid = "/////////////////" + myObj2[y].type.operations[0].amount/1000000;
console.log("Paid : " + Paid);
txt += "<td width=10% align=center>Paiement :" + Paid + "</td>";
txt += "</tr>";
// All the data saved during this function is saved after the execution or the boucle for(x)
console.log("Txt /////: " + txt);
// document.getElementById("demo2").innerHTML = txt2;
} else {
}//
}
//return txt;
} else {
//console.log("Not Ok");
}
};
xmlhttp2.open("POST", "https://api6.tzscan.io/v3/operations/tz1XynULiFpVVguYbYeopHTkLZFzapvhZQxs?type=Transaction&number=100", true);
xmlhttp2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp2.send("x=" + dbParam2);
}
txt += "</table>";
console.log("Txt 2 : " + txt);
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("POST", "https://api6.tzscan.io/v3/delegator_rewards_with_details/" + KT1, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
You can see here my codepen, you can easily see that my function xmlhttp2.onreadystatechange = function() { only executes itself after xmlhttp.onreadystatechange = function() { instead of after getting each data from the JSON file
try to use JavaScript Promises.
A simple Promise is here
I am trying to read data from a xml file and display them in my html file, but when I am trying to display my values I get "undefined" values for all the values.
I am a really new with ajax and xml so excuse my code if its horrible! I will appreciate if someone got a really briefly answer.
Here's my xml file:
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2019-01-25">
<Cube currency="USD" rate="1.1346"/>
<Cube currency="JPY" rate="124.72"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="25.697"/>
<Cube currency="DKK" rate="7.4664"/>
<Cube currency="GBP" rate="0.86580"/>
....
My javascript code:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
returndata(this);
}
};
xhttp.open("GET", "rates.xml", true);
xhttp.send();
}
function returndata(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>currency</th><th>rates</th></tr>";
var x = xmlDoc.getElementsByTagName("Cube");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("currency")[0] +
"</td><td>" +
x[i].getElementsByTagName("rate")[0] +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
When I click the button I got the following result:
currency rates
undefined undefined
undefined undefined
undefined undefined
undefined undefined
.....
UPDATE Javascript code(fixed):
function returndata(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>currency</th><th>rates</th></tr>";
var x = xmlDoc.getElementsByTagName("Cube");
for (i = 2; i <x.length; i++) {
table += "<tr><td>" +
x[i].getAttribute("currency") +
"</td><td>" +
x[i].getAttribute("rate") +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
Okay now it works, thank you very much, i started my variable from the value 2 because when i am trying to have a while loop like (x!=null) my webpage it still loading forever and then breaks down..
i tried that one:
function returndata(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>currency</th><th>rates</th></tr>";
var x = xmlDoc.getElementsByTagName("Cube");
for (i = 0; i <x.length; i++) {
while (x!=null) {
table += "<tr><td>" +
x[i].getAttribute("currency") +
"</td><td>" +
x[i].getAttribute("rate") +
"</td></tr>";
}
}
document.getElementById("demo").innerHTML = table;
}
So in my code I created a table pulling from an XML file that displayed two columns of information about plants. The goal of my program is to be able to hover over the first and print out the other information about that plant and print it in another section to the right of my table. The issue is that I am not gettign any console errors and the hover affect is not printing any information.
window.addEventListener("load", link_events);
var xhr = false;
function link_events() {
xhr = new XMLHttpRequest();
if(xhr) {
xhr.addEventListener("readystatechange", ShowFile);
xhr.open("GET", "plants.xml", true);
xhr.send();
} else {
alert("XHR not supported.");
}
}
function ShowFile() {
var i;
var title;
var cover;
var plant_table = "<table><tr><th>Common Name </th><th>Botanical Name </th></tr>";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//here we have gotten the file correctly
//loop through it and print out cover and title
var plantlist = xhr.responseXML.getElementsByTagName("PLANT");
//booklist is an array and each element is an object sub i
//so you have to use getElementBy something in order to pull the information
for (i = 0; i < plantlist.length; i++) {
var Common = plantlist[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
var Botanical = plantlist[i].getElementsByTagName("BOTANICAL")[0].firstChild.textContent;
plant_table += "<tr>" +
"<td class =\"plant\">" + Common + "</td>" +
"<td>" + Botanical + "</td>" +
"</tr>";
}
plant_table += "</table>";
document.getElementById("outarea").innerHTML = plant_table;
}
var plants = document.getElementsByClassName("plant");
for (i=0; i < plants.length; i++) {
plants[i].onmouseover = HoverChoice;
}
}
function HoverChoice() {
var input = xhr.responseXML.getElementsByTagName("PLANT");
for (i = 0; i < input.length; i++) {
Common = input[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
var Zone = input[i].getElementsByTagName("ZONE")[0].firstChild.textContent;
var Light = input[i].getElementsByTagName("LIGHT")[0].firstChild.textContent;
var Price = input[i].getElementsByTagName("PRICE")[0].firstChild.textContent;
if (plants == this.innerHTML) {
document.getElementById("inarea").innerHTML =
"<h1>" + Common + "</h1>" + "<br />" + "<br />" +
"Zone: " + Zone + "<br />" +
"Light: " + Light + "<br />" +
"Price: " + Price;
}
}
}
}
you could try using addEventListener method instead and see whether it works?
plants.forEach(function(plant){
plant.addEventListener("onmouseover", HoverChoice);
});
or going with the original loop you made it would be
for (i=0; i < plants.length; i++)
{
plants[i].addEventListener("onmouseover", HoverChoice);
}
I'm not anything professional, a common problem I used to encounter in these kinds of event listening functions was that calling a global function sometimes fails but making the function on the spot inside the event listener would work like addEventListener("onmouseover" , function() { return 0; });
First of all thank you for reading this. I am having some trouble fetching the data given by the Linkedin sign-in API with javascript. Here is the script:
<script type="text/javascript">
function onLinkedInAuth() {
IN.API.Profile("me").fields(["firstName","lastName","headline","summary","location","educations","skills"]).result(displayProfiles);
}
function displayProfiles(profiles) {
member = profiles.values[0];
document.getElementById("name").value = member.firstName +" "+ member.lastName;
document.getElementById("pos").value = member.headline;
document.getElementById("city").value = member.location.name;
document.getElementById("sum").value = member.summary;
var i=0;
do {
var oldHTML = document.getElementById('para').innerHTML;
var newHTML = oldHTML + "<tr><td>" + member.educations.values[i].schoolName + "</td></tr>";
document.getElementById('para').innerHTML = newHTML;
i++;
}
while(i<=1);
var v=0;
do {
var oldHTML = document.getElementById('tara').innerHTML;
var newHTML = oldHTML + "<tr><td>" + member.skills.values[v].skill.name + "</td></tr>";
document.getElementById('tara').innerHTML = newHTML;
v++;
}
while(member.skills.values[v].skill.name);
document.getElementById("educ").value = member.educations.values[1].schoolName;
document.getElementById("skills").value = member.skills.values[0].skill.name;
}
</script>
It's a very basic script to get the user infos and, among it, the educational and professional background of the user. The thing is that member.educations.values[i].schoolName and member.skills.values[v].skill.name can have multiple values and I want to gather them all.
It works as long as the specified fields are not empty but then it outputs an error saying that member.skills.values[v] is undefined and it does not run the second loop.
I know the error is really basic but I'm not that great in javascript.
Thanks for your help anyways, have a good day!
You should check the length of the returned values and then loop through them as needed. Something along the lines of:
var educations = member.educations;
if(educations._total > 0) {
for(var i = 0; i < educations._total; i++) {
document.getElementById("educ").value += (i > 0) ? ', ' : '';
document.getElementById("educ").value += educations.values[i].schoolName;
}
}