I have an external JSON file that I am trying to read into my ajax and parse through, but I'm missing something. I'm trying to read it into an XMLHttpRequest object. Any ideas on what I'm doing wrong. I get no results.
External file (mypeeps.json) contains:
[
{"name":"Frank","age":"23","image_url":"frank.gif"},
{"name":"Jim","age":"24","image_url":"frank.gif"},
{"name":"Tom","age":"21","image_url":"frank.gif"},
{"name":"Betty","age":"28","image_url":"frank.gif"},
]
My code is:
<script type="text/javascript">
function ajax_get_json() {
var p = new XMLHttpRequest();
p.open("GET", "mypeeps.json", true);
p.setRequestHeader("Content-type", "application/json");
p.onreadystatechange = function () {
alert("Im in...");
if (p.readyState == 4 && p.status == 200) {
alert("Let me know I've gotten this far");
var data = JSON.parse(p.responseText);
var results = document.getElementById("myDiv").innerHTML;
results.innerHTML = data.name;
} else {
document.getElementById("myDiv").innerHTML = "waiting...";
}
}
document.getElementById("myDiv").innerHTML = "processing...";
}
</script>
<div id="myDiv"></div>
<script type="text/javascript">
ajax_get_json();
</script>
Related
I am using javascript ajax to fetch data from the JSON API server and want to show these data in an HTML table.
But I get an undefined error in HTML data. That is
Name id
undefined undefined
There is my code
<html>
<body>
<table class = "src">
<tr><th>Name</th><th>id</th></tr>
<tr><td><div id="Name"></div></td>
<td><div id="Id"></div></td></tr>
</table>
</body>
</html>
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "https://jsonplaceholder.typicode.com/users";
xmlhttp.onreadystatechange = function(e) {
if (this.readyState == 4 && this.status == 200) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(this.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Id").innerHTML = jsonObj.id;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
What should I do to resove this? Thanks in advance.
The problem is that you are trying to access an object, but the output of the API is actually an array. You can get the first object by doing jsonObj[0], as follows:
<html>
<body>
<table class = "src">
<tr><th>Name</th><th>id</th></tr>
<tr><td><div id = "Name"></div></td>
<td><div id = "Id"></div></td></tr>
</table>
</body>
</html>
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "https://jsonplaceholder.typicode.com/users";
xmlhttp.onreadystatechange = function(e) {
if (this.readyState == 4 && this.status == 200) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(this.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").textContent = jsonObj[0].name;
document.getElementById("Id").textContent = jsonObj[0].id;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
See this codesandbox where the code is working.
Edit: As T.J. Crowder has mentioned, it is better to use textContent rather than innerHTML to avoid unwanted HTML to be rendered (never trust user input!).
I am currently trying to display data from a local JSON file (universities.json) into a table on a webpage. This is my current code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
</head>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "universities.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.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 += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
I have searched through so many questions on here and done countless google searches yet I cannot find out why this will not work. This is just one iteration of the code; I have tried various other ways too. I'm aware I don't have any code for a table included, but I have removed that until I can get the data pulling through in any format.
Any help would be much appreciated. Thanks
Your browser security is not allowing you to make this request, and you are getting CORS error, in order to bypass this, you have two following options.
1.Alter your browser security settings.
For example, in Chrome, you can do this by navigating to Chrome installation folder and Run chrome with the following command, then try to test again in the browser
chrome.exe --allow-file-access-from-files
2.Run a Webserver locally and put all your file in the same path.
The CORS error is due to browser security as Mahdi mentioned earlier.
If your HTML file is just opened from local drive in your browser (client-side only) and not hosted on a local nor remote web server, instead of using XMLHttpRequest(), you should try using FileReader() from pure JavaScript. Do something like this:
function fnUploadFile() {
var objFileReader;
var inputFile;
var flLocalFile;
if (window.File && window.FileReader && window.FileList && window.Blob) {
// All the File APIs are supported.
} else {
alert('A required API is not supported on this browser. You need HTML5 browsers!');
return; // abort execution
}
inputFile = document.getElementById('inLocallySelectedFile');
if (!inputFile) {
alert("File selector control not found!");
} else if (!inputFile.files[0]) {
alert("Have you selected a file yet? Select a file before clicking 'Process File'!");
} else {
// open and read file with JavaScript FileReader
flLocalFile = inputFile.files[0];
objFileReader = new FileReader();
objFileReader.onload = function(event) {
// event.target == FileReader
var contents = event.target.result;
fnConvertToJSON(contents);
};
objFileReader.readAsText(flLocalFile);
}
function fnConvertToJSON(results) {
var JSONData = JSON.parse(results);
var ctrlJSONDisplay = document.getElementById('JsonDataDisplay')
ctrlJSONDisplay.innerHTML = "<strong><u>" + JSONData['name'] +
"</u></strong> is <strong><u>" + JSONData['age'] +
"</u></strong> years old and from the <strong><u>" +
JSONData['country'] + "</u></strong>";
}
}
<form id="frmGetLocalFile" name="frmGetLocalFile" method="post">
<h1>Select Your File</h1>
<input type='file' accept="*" name='inLocallySelectedFile' id='inLocallySelectedFile'>
<input type='button' id='btProcessFile' name="btProcessFile" value='Process File' onclick='fnUploadFile();'>
</form>
<div>
<p>Assuming JSON File Content:</p>
<pre>
{
"name": "John",
"age" : 30,
"country" : "UK"
}
</pre>
<hr>
<p>JSON Data read from local file:</p>
<p id="JsonDataDisplay"></p>
</div>
See code in JSFiddle: https://jsfiddle.net/TechOnTheBeach/3gsa2y75/3/
Couldn't manage to serve files from within codesandbox.
However, following (serverside) codesample, does the trick:
const http = require("http");
http
.createServer((req, res) => {
if (req.method === "GET" && req.url == "/") {
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end(`<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
</body>
<script>
const getJson = () => {
let xhr = new XMLHttpRequest();
xhr.open('GET', '/getjson', true);
xhr.onload = () => {
if (xhr.readyState == 4 && xhr.status == 200)
json = JSON.parse(xhr.responseText);
jsons = [];
Object.values(json).forEach((value,index) => {
jsons.push('"'+Object.keys(json)[index]+'"');
});
jsons.forEach(item => document.querySelector('#id01').innerHTML += item+'<br>');
};
xhr.send();
};
getJson();
</script>
</html>`);
}
if (req.method === "GET" && req.url.match(/getjson/)) {
let json = `{ "Univ1": "https://univ1.edu", "Univ2": "https://univ2.edu", "Univ3": "https://univ3.edu" }`;
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(json);
}
})
.listen(8080);
https://codesandbox.io/s/j2yj6577q3
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();
I am calling a php file that queries my database and returns a result. I have verified that the php file accurately returns the data as needed, but my calling page is not updated from the JavaScript.
What do I need to alter in my syntax below so that the returned value is returned on page?
<script type="text/javascript">
function boostion()
{
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("data").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
EDIT
I have also opened Developer Options in Chrome and checked the Console and there are no errors or issues displayed, everything is a success!
Edit 2
I tried to use the JQuery approach below and used this syntax - but I get the error
Uncaught TypeError: $(...).load is not a function
Syntax:
<script src="https://code.jquery.com/jquery-3.1.1.slim.js"
integrity="sha256-5i/mQ300M779N2OVDrl16lbohwXNUdzL/R2aVUXyXWA="
crossorigin="anonymous" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
document.getElementById("data").innerHTML = data;
});
});
</script>
Edit 3
This is my php syntax that runs the sql syntax and echo result that I want to have returned from the javascript
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'host';
$option['user'] = 'user';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance( $option );
$result = $db->getQuery(true);
$result->select($db->quoteName(array('trackandfieldresults')));
$result->from($db->quoteName('[TrackData]'));
$db->setQuery($result);
$row = $db->loadRowList();
echo $row['0']
?>
Use xhr.send();
If it is a GET request, you have to apply the query string in in xhr.open and you dont have to set Content-type:application/x-www-form-urlencoded
first, the scripts should be inside the HTML before the ending body tag. then you open another file and write your code in it. JQUERY does not have script tag. Sp you are creating an external javascript file for the script. No script tag needed. Now use this format.
$(window).on('load', function(e){
e.preventDefault();
var dat = //the content you are trying to load
$.get('middleware.php', dat, function(data){
$('#selector').html(data)
});
})
I have a faster approach using JQuery.
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
//Do whatever you want here
});
});
This should do the Job. Your approach is old and kind of complicated to debug
Try this
function boostion(){
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.send();
xhr.onreadystatechange = function(){
console.log(xhr);
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("data").innerHTML = xhr.responseText;
}
}
}
<div id="data"></div>
<button onclick="boostion();">Load</button>
I am trying to retrieve data from JSON. I have written this code. It alerts "1" but doesn't alert "2".
<script type="text/javascript" src="jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
function ajax_get() {
var results = document.getElementByI("results");
var hr = new XMLHttpRequest();
hr.open("GET", "mylist.json", true);
hr.responseType = "JSON";
hr.setRequestHeader("Content-type", "application/json",true);
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
alert('1');
var data = JSON.parse(hr.response);
alert('2');
alert(data);
results.innerHTML = data.name;
}
}
hr.send(null);
results.innerHTML = "request ...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type="text/javascript">ajax_get();</script>
</body>
You have already set the response type as json on this line.
hr.responseType= "JSON";
So you need not parse the response again. it will be by default json.
Make sure your response is in json format and change your code like this.
var data = hr.response;