This question already has answers here:
Loading local JSON file
(26 answers)
Closed 5 years ago.
I have a JSON file on my local computer and I want to read its contents and display it on the web browser by using pure javascript. Anything which refers to the server side will not work for me. It is required to be done purely on the Client Side. What are the possible solutions ?
Note: ajax and anything related to that should not be used.
If you don't wanna do an ajax to load the file, and let user select the file what he wanna load by <input type='file' />, maybe this way is working for you.
document.getElementById('show').addEventListener('click', function() {
var file = document.getElementById('myfile').files[0];
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = function(evt) {
document.getElementById('content').innerHTML = evt.target.result;
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="file" name="" id="myfile">
<div id="content"></div>
<button id="show">Show</button>
</body>
</html>
function readFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
var value = JSON.stringify;
// now display on browser :)
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
Related
I have a problem with a html file not 'loading' js and css files properly. This is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create new snippet</title>
<script src="static/js/send.js"></script>
<link rel="stylesheet" href="static/css/button.css">
</head>
<body>
<textarea id="code_snippet" placeholder="//write your code here"></textarea><br/>
<button type="submit" onclick="send()">Submit</button>
</body>
</html>
It is supposed to take some input into the textarea tag and send it to a database when you click on the button. However, the function send() doesn't work at all. Also, the linked CSS doesn't work as well. This is my project structure:
This is the send() function:
function send() {
let object = {
"code": document.getElementById("code_snippet").value
};
let json = JSON.stringify(object);
let xhr = new XMLHttpRequest();
xhr.open("POST", '/api/code/new', false)
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.send(json);
if (xhr.status != 200) {
alert("Something went wrong!");
} else if (xhr.status == 200){
alert("Success!");
}
}
This function works fine when I put it inside of script tag
You should make sure the links are relative or absolute to the home directory.
/absolute path
and use without "/" for relative path
try to access css and js file links from browser.
I am attempting to make a reusable AJAX base to be used in other function within same file. The main purpose with the reusable AJAX base is to minimize the AJAX code, thus reuse the base in other functions.
It works fine when having lines without calling variables. (see lines marked with "these lines works". When attempting to call the AJAX base function from the other function, thus including a variable to pass to AJAX base, it does not work.
Question: Specific to AJAX, how is the correct way of calling external variables from within the AJAX function?
Index.json -file content:
{
"firstName": "John",
"lastName": "Doe"
}
Index.js -file content:
/************************************/
/* Ajax base to fetch external json */
/************************************/
function ajaxBase() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = JSON.parse(xhttp.responseText);
//document.getElementById("boxOne").innerHTML = response.firstName; // This line works.
//document.getElementById("boxTwo").innerHTML = response.lastName; // This line works.
document.getElementById("boxOne").innerHTML = response.[fname];
document.getElementById("boxTwo").innerHTML = response.[flname];
}
};
xhttp.open("GET", "index.json", true); // Define source json data file.
xhttp.send();
}
function changeFirstName() {
ajaxBase(fname = "firstName"); // Passing in variable into function.
}
function changeLastName() {
ajaxBase(lname = "lastName"); // Passing in variable into function.
}
Index.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="index.css">
<title>Document</title>
</head>
<body>
<button type="button" name="button" onclick="changeFirstName()">Change first-Name</button>
<button type="button" name="button" onclick="changeLasttName()">Change last-Name</button>
<div id="boxOne" class="boxOne">First-Name[placeholder]</div>
<div id="boxTwo" class="boxTwo">Last-Name[placeholder]</div>
<script src="index.js"></script>
</body>
</html>
You could try defining two parameters on ajaxBase and checking them inside the function's body. When you call it, assign one of them to null to indicate which value does not need to change.
/************************************/
/* Ajax base to fetch external json */
/************************************/
function ajaxBase(fname, lname) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = JSON.parse(xhttp.responseText);
//document.getElementById("boxOne").innerHTML = response.firstName; // This line works.
//document.getElementById("boxTwo").innerHTML = response.lastName; // This line works.
if (fname !== null)
document.getElementById("boxOne").innerHTML = response.[fname];
if (lname !== null)
document.getElementById("boxTwo").innerHTML = response.[flname];
}
};
xhttp.open("GET", "index.json", true); // Define source json data file.
xhttp.send();
}
function changeFirstName() {
ajaxBase("firstName", null);
}
function changeLastName() {
ajaxBase(null, "lastName");
}
I am trying to implement an AJAX Example which perfectly works with the GET request, but I am not able to transmit via POST. What am I doing wrong ? The POST object received by PHP is always empty. Thanks for any advice!
HTML & JavaScript:
<html>
<head>
<title> Create a new user</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
function checkUser(){
xhttp = new XMLHttpRequest();
xhttp.open("POST","usercheck.php",true);
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var data = xhttp.responseText;
alert("Benutzer" + data);
}
}
xhttp.send("username=" + encodeURIComponent(document.getElementById("username").value));
}
</script>
</head>
<body>
<p>User:</p><br>
<input type="text" id="username" name="username">
<button onclick="checkUser();"> Check </button>
</body>
</html>
PHP Code:
<?php
$usernames = array("admin", "gast", "paul");
$validate_pattern = "/^[a-z0-9]{4,20}$/";
if (!isset($_POST["username"])) {
die("{valid:false,message:false}");
}
if (in_array($_POST["username"], $usernames)) {
die("{valid:false,message:'Username is used!'}");
}
if (!preg_match($validate_pattern, $_POST["username"])) {
die("{valid:false,message:'Username wrong.'}");
}
echo "{valid:true,message:false}";
?>
I found the bug in the code. I missed to set the request header, which was not part of the tutorial unfortunately:
xhttp.setRequestHeader('Content-Type','x-www-form-urlencoded');
On one page i have several DIVs that get filled with data from XMLHttpRequests to different php pages. To keep the UI responsive i started experimenting with webworkers. It seemed however that a faster page kept waiting after a slower page, i.e. the web worker didn't work concurrently.
I've simplified the pages for testing purposes, see code below. It seems that when the 2 back end php pages that provide the data have if (!isset($_SESSION)) session_start(); in them, one page is qeued after the other.
In the example below, there are 2 buttons that each invoke a different web worker that in turn invokes a different php script. PhpA is 10sec slower than phpB. So when you click on button wwA and then on wwB in the main (test.php) script, you should first get a response from phpB. When if (!isset($_SESSION)) session_start(); is in phpA and in phpB this is not the case. Why is this so?
test.php
<?php if (!isset($_SESSION)) session_start();?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"/>
<title>test</title>
<script language="JavaScript" type="text/javascript">
<!--
function launchWebWorkerA() {
var worker = new Worker('webWorkerA.js');
worker.addEventListener('message', function(e) {
document.getElementById('outputA').innerHTML = e.data.text;
worker.terminate();
}, false);
worker.postMessage();
}
function launchWebWorkerB() {
var worker = new Worker('webWorkerB.js');
worker.addEventListener('message', function(e) {
document.getElementById('outputB').innerHTML = e.data.text;
worker.terminate();
}, false);
worker.postMessage();
}
//-->
</script>
</head>
<body>
<input type="button" onClick="launchWebWorkerA()" value="wwA" />
<input type="button" onClick="launchWebWorkerB()" value="wwB" />
<div id="outputA">outputA</div>
<div id="outputB">outputB</div>
</body>
</html>
webWorkerA.js
// JavaScript Document
self.addEventListener('message', function(e) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
self.postMessage({'text': xmlhttp.responseText});
}
}
xmlhttp.open('POST','phpA.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send();
}, false);
webWorkerB.js
// JavaScript Document
self.addEventListener('message', function(e) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
self.postMessage({'text': xmlhttp.responseText});
}
}
xmlhttp.open('POST','phpB.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send();
}, false);
phpA.php
<?php if (!isset($_SESSION)) session_start();
sleep(10);
echo 'phpA response3';
?>
phpB.php
<?php if (!isset($_SESSION)) session_start();
echo 'phpB response3';
?>
Starting a session will block all other scripts attempting to start the exact same session (based on the cookie). This is one reason why you need to minimize the amount of time a session is opened for. Arguably you could use a database or something like memcache to kludge inter-script communication but it's not really what PHP is about.
Source: ajax multi-threaded
I am trying to get a piece of data from server using JSP technology. I am using JSON object to do so. On client side i am using XMLHttpRequest to get the data.
To check whether it works properly, i wrote a piece of code as follow:
<head>
<script type="text/javascript">
function test(data) {
if(data){
var jsonObj= eval('(' + data + ')');
var Question= jsonObj.Question;
document.write(Question);
}
}
function handler() {
if(this.readyState == 4 && this.status == 200) {
// so far so good
if(this.responseText != null && this.responseText)
// success!
test(this.responseText);
else
test(null);
} else if (this.readyState == 4 && this.status != 200) {
// fetched the wrong page or network error...
test(null);
}
}
function xyz(){
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("POST", "fetch.jsp", true);
client.send();
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<br><br><input id="Q" type="button" onclick="xyz()" >
</body>
on server side i did as follow:
<%#page import="net.sf.json.JSONObject"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<% JSONObject jsonObj= new JSONObject();
jsonObj.put("Question","What is your name?");
jsonObj.put("Opt1","ji");
jsonObj.put("Opt2","ji");
jsonObj.put("opt3","ma");
jsonObj.put("opt4","sa");
String str= jsonObj.toString();
response.setContentType("text/plain");
response.getWriter().write(str);
%>
Unfortunately i am not able to get the response.
You are writing your JSON into the body of an HTML document, and then sending the HTML document as the response.
Don't do that. The response should be just the JSON.
You need to write with content type application/json.
Also don't use eval in test function.
When the data is json the test function can access the data as the json object!
In the event of parsing a string use.
JSON.parse(string).
But don't use eval