How convert JSON data to html table - html

I get real-time statistics for myself and the data in JSON format. The problem is, I can not figure how can I get this table in html web page.
Data can be found at: http://testinki.info/apidata/
I have tried something like this, but without success:
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://testinki.info/apidata/";
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].apikey +
"</td></tr>"
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
Any ideas? How to solve the problem?

AngularJS might be a good solution for the task. With data from your link, code will look something like this:
Api key: {{data.apikey}}
<br>
User:
<pre>{{data.data|json}}</pre>
<br>
<table>
<tr ng-repeat="member in data.Members">
<td>{{member.name}}</td>
<td>{{member.info}}</td>
</tr>
</table>
angular
.module("app", [])
.controller("ctrl", function ($http, $scope, $http) {
$http
.get("http://testinki.info/apidata/")
.then(function (res) {
$scope.data = res;
})
})
JSBin example. I've changed $http to $timeout and predefined data since your API does not allow cross-origin requests.

Related

How can i make the HTML file open in Chrome while the calling browser is Explorer

I have this HTML (attached).
It is called by a web app that still works on I.E (for at least one or two months) due to some problems we have with the vendor.
The web app calls this HTML and it is opened in I.E also.
I need this HTML to be opened in Chrome.
Is there a way i can do this by adding something to the HTML itself?
<html>
<head>
<script>
async function setSRC(){
try{
var xhr;
const params = new Proxy(new URLSearchParams(window.location.search),
{
get: (searchParams, prop) => searchParams.get(prop),
});
var docId = params.docId;
var url = "``http://wsp-exttest.lcardtest.corp:4440/rest.oms/MaxRestService/getPDF?docId=``" + docId;
let response = await new Promise(resolve => {
xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function(e) {
resolve(xhr.response);
};
xhr.onerror = function () {
resolve(undefined);
console.error("** An error occurred during the XMLHttpRequest");
};
xhr.send();
})
//
var j = JSON.parse(xhr.responseText);
var pdfData = j[0].content;
var letterFrame = document.getElementById("letterFrame");
letterFrame.src = "data:application/pdf;base64," + pdfData;
/*letterFrame.onreadystatechange = () => {
if (letterFrame.readyState === 'complete') {
alert(letterFrame.readyState);
letterFrame.src = "data:application/pdf;base64," + pdfData;
}
};*/
}
catch(e)
{
if(confirm("Load faile: " + e.message + "click ok to retry"))
setSRC();
}
}
</script>
</head>
<body onload="setSRC()">
<iframe id="letterFrame" width="1200px" height="800px" onload=""></iframe>
Reload
</body>
</html>
Reload

XMLHttpRequest ERROR in QML Blackberry 10

I'm trying to get movie data for BlackBerry 10 apps.
I don't know where I'm making a mistake.
Please, can you help me?
Thank you all.
import bb.cascades 1.4
Page {
onCreationCompleted: {
sendRequest();
}
function sendRequest() {
var data = "{}";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
xhr.send(data);
}
}
You need to use the onreadystatechange EventHandler.
Also, you don't need to pass data when making a GET request.
I have removed the withCredentials line as it isn't needed in this example.
You can learn more on XMLHttpRequest here :
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
onCreationCompleted: {
sendRequest();
}
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
var json = JSON.parse(xhr.responseText);
var results = json.results;
var count = results.length;
console.log("There are " + count + " results :");
json.results.forEach((value, index) =>
{
console.log(index + " - " + value.title);
});
}
};
xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
xhr.send();
}
Here's an example of using XMLHttpRequest I've made a long time ago :
https://github.com/RodgerLeblanc/Markup/blob/master/assets/main.qml

html <script> tag headers

I'm trying to require a script that is firewalled with a header authentication system and trying to find a way around it.
So far it's pretty evident that you can't add custom headers to the script tag its self but I have seen something about customizing the headers on the page before requesting or on the server side.
Until this point, I can't say I've seen any solid answers.
You can load it via xhr and eval() it in-page. For example with jQuery, you can use:
http://api.jquery.com/jquery.ajax/ - see beforeSend to set headers; use this to retrieve the file content.
Then use https://api.jquery.com/jquery.globaleval/ globalEval() to eval the gotten content in-page.
You could achieve the same with vanilla HttpRequest and eval(), but I was always too lazy to do it that way. Or maybe not... I just found a piece of code in the project I'm working:
var evalScript = function(e) {
var h = evalScript.node,
s = document.createElement("script");
s.type = "text/javascript";
s.text = e;
h.appendChild(s);
h.removeChild(s);
};
evalScript.node = document.getElementsByTagName("head")[0] || document.getElementsByTagName("*")[0];
// TODO: make async
function loadJs(js) {
var req = new XMLHttpRequest();
req.open("GET", js, false);
req.send(null);
evalScript(req.responseText);
}
Just add the headers to this.
Here's a simple Ajax function you could use to get the contents of the script:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
Since you need to set custom headers, you'd also use the request.setRequestHeader method, like this:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
// BEGIN: CUSTOM HEADERS
request.setRequestHeader("Header-Name", "header/value");
request.setRequestHeader("Other-Header", "other/value");
// END: CUSTOM HEADERS
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
And finally, you'd use the function, like this:
get("url/to/your/script", function(response) {
// perform checks...
window.eval(response);
});
WARNING: be very, VERY careful when using eval, don't ever eval something you don't trust and remember eval can be evil.

AJAX request on Node.js server

I am unable to make an AJAX request from my .html page to my node.js server for a JSON file. I've been reading on AJAX requests, but all I am able to make out is how to display the servers responseText.
It would be great if you could help me out, it would be even better if you could link me some tutorials on this, anyway this is what I've got at this moment:
server.js
var express = require('express');
var fs = require('fs');
var app = express();
app.get('/test', function(req, res){
var arr = new Array();
var rd = readline.createInterface({
input: fs.createReadStream('info.json'),
output: process.stdout,
terminal: false
});
rd.on('line', function(line) {
arr.push(line);
}).on('close', function(){
res.send(arr);
});
});
app.get('/', function(req, res) {
fs.readFile('test2.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
});
app.listen(process.env.PORT || 3000);
test.html
<html>
<head>
<script>
function sendAjax(){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4 && xmlHttp.status == 200){
console.log(xmlHttp.responseText);
}
document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
}
xmlHttp.open("GET", "/test", true);
xmlHttp.send();
}
</script>
</head>
<body>
<input type="submit" onClick="sendAjax()" value="SendAjax" />
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
</body>
</html>
I know this may not look like much, I've been struggling with this, and the book I have (Node.js in Action) doesn't help me alot. But as I said, what I want is to display the .json info in the browser. Thx for reading
If I understand right, you may replace
document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
with
var parsed = JSON.parse(xmlHttp.responseText);
var html = '';
for (var i = 0; i < parsed.length; i++) {
html += '<div>' + parsed[i] + '</div>';
}
document.getElementById("myDiv").innerHTML = html;
You may also try to replace
res.send(arr);
with
res.json(arr);
Update
Or maybe you just forgot to write this line in the beginning of server.js:
var readline = require('readline');

Multiple File Upload in codeigniter using HTML5 and XHR

I'm working on multifile upload using html5 and xhr, as you can see I'm sending requests in loop which is a bad
concept but I'm not able to upload files when I send it outside the loop and only the last file gets upoaded.
Where am I going wrong?
$('#uploadimg').on('click', function(e) {
var files = document.getElementById('files').files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/ajaxuploader/upload/uploadimg');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('all done: ' + xhr.status);
} else {
console.log('Something went terribly wrong...');
}
};
xhr.send(formData);
}
// now post a new XHR request
});
Codeigniter
public function uploadimg (){
$config['upload_path'] = FCPATH . 'uploads/' ;
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc';
$config['remove_spaces'] = 'TRUE';
$this -> load -> library('upload', $config);
//$this->upload->initialize($config);
foreach ($_FILES as $k => $f) :
$this -> upload -> do_upload($k);
endforeach;
//$this->index();
}
Its seems the first thing you should look at is your js for loop. ID's should be unique so I would rule that approach out.
I would maybe loop each input field, check to see if the attr type == file, then append that to your formData object.
var inpts = document.getElementsByTagName('input');
for(var i=0; i < inpts.length; i++)
{
if(inpts[i].getAttribute('type') == 'file')
{
formData.append('myFiles[]', inpts[i].files[0]);
}
}
On the server side I would look at your foreach loop, maybe a for loop might suffice.
for($i=0; $i < count($_FILES); $i++){
$this->upload->initialize(); //new initialization for each file
$this->upload->do_upload($_FILES[$i]);
continue;
};
Hi guys i figured out the problem codeigniter is working fine, the problem is in the jquery. this is the line causing the problem. "formData.append(files[i].name, files[i]);" Thanks for all for takign efforts to solve my issue
$('#uploadimg').on('click', function(e) {
//console.log(files);
// files = document.getElementById('files').files;
var formData = new FormData();
$(files).each(function(i) {
formData.append(files[i].name, files[i]);
})
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/ajaxuploader/upload/uploadimg');
xhr.onload = function(data) {
console.log(xhr.responseText);
};
xhr.send(formData);
});