Cannot get local file from XMLHttpRequest - javascript

Im trying to get an local txt file from calling a XMLHttpsRequest() method. But it keeps sending me a 404 error message in the console. Please help me out.
here is my html file
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Ajax1</title>
</head>
<body>
<button id="button" type="button" name="button">Get text files</button>
<script type="text/javascript">
document.getElementById("button").addEventListener('click', loadText)
function loadText(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
if(xhr.status === 200){
console.log(xhr.responseText)
}
}
xhr.send(null);
}
</script>
</body>
</html>
Local txt file is not inside any folder.
I dont know whether this is important or not but here is my app.js file
const express = require('express')
const app =express()
app.use(express.static("public"))
app.get('/', function(req, res){
res.sendFile(__dirname+'/ajax1.html')
})
app.listen(3000, function(){
console.log('server is runing')
})

here is my directory tree
`>Ajax-beginning
>node_modules
•Ajax.html
•app.js
•package-lock.jason
•package.jason

Related

JavaScript and CSS files won't work in html (spring boot app)

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.

Ajax vanilla Js sent post request is showing a blank body

I'm trying to print the data which has been received at the server side but it always
shows a blank body output printing req={}
I've been trying for days and I can't find the answer, any help would be greatly appreciated!!!
the server side code:
const express= require('express');
const app=express();
const data_itself = require('./data.js');
app.use(express.static('public'));
app.use(express.urlencoded({extended:true}));
app.listen(3100,()=>{
console.log('sever listening at port 3100...')
});
app.set('view engine','ejs');
app.set('views','public');
app.get('/',(req,res)=>{
res.redirect('/home');
});
app.post('/',(req,res)=>{
var random_data='recived post request!'
res.send(random_data);
console.log('req=',req.body); //this outputs to req={}
});
The client side code:
<!DOCTYPE html>
<head>
<title>Sample Site</title>
</head>
<body>
<button onclick="send_info()">Submit data</button>
<div id="stat"></div>
</body>
<script>
data=['xyz'];
function send_info(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("stat").innerHTML =
this.responseText;
}
};
xhr.open("POST",'/', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
}
</script>
</html>
You need to have your express server use the JSON parser middleware. Add the following line to your server file.
app.use(express.json())
An explanation of the middleware is available at this link: http://expressjs.com/en/api.html

Unable to access form data on serverside

I am making a put request from frontend for which I have been using XMLHttpRequest and FormData API request but server side I would not get any data like req.params, req.body and req.query all are empty
Front-end Code
var reportSub = () => {
var report = document.getElementById('report');
var formData = new FormData(report)
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.response)
}
}
var queryString = new URLSearchParams(formData);
xhr.open("PUT", '/threads/edit', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.send(queryString)
}
var reportsub = document.querySelector('#repsub');
reportsub.addEventListener("click",(e)=>{
e.preventDefault();
reportSub();
})
Server Side code
router.put('/threads/edit',(req,res)=>{
let board = req.body.board;
let id = req.body.id;
console.log(req.query,req.body)
Board.findById({_id: ObjectId(id)},(error,data)=>{
if(error)
res.send(error)
if(data!==null){
data.Reprot = true;
data.save((error,sd)=>{
if(error)
res.send(error)
res.send(sd);
})
}
else{
res.send({"Error":"Id does not exist "})
}
})
})
There is one solution would be where you add data in url which again hard coded each in every variable and data you had to pass.
So thats I want use FormData interface for sending data.
I think you are missing a library for parsing the FormData request. You could also send the data using JSON as it is text-only, this would simplify parsing. A minimal example could look like the following:
server.js
const express = require("express");
const multer = require("multer");
const upload = multer();
const app = express();
app.use(express.static('public'))
app.post('/data', upload.none(), function (req, res) {
console.log(req.body.favoriteNumber);
res.send('42 is the only real choice');
});
app.listen(3000, function () {
console.log('App listening on port 3000!');
});
public/index.html
<!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">
<title>Document</title>
</head>
<body>
<form id="textForm">
<p>Your favorite number:</p>
<input type="text" value="42" name="favoriteNumber" />
</form>
<button id="send">Send</button>
<script>
const sendButton = document.getElementById("send");
const form = document.getElementById("textForm");
sendButton.addEventListener("click", () => {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.response);
}
}
const formData = new FormData(form);
xhr.open("POST", '/data', true);
xhr.send(formData);
})
</script>
</body>
</html>
You do not have to set the header manually. It is set automatically and does include boundary - a parameter you cannot know while writing the application. The header could look like the following:
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryuzeaYvzY77jzcFeA

Read JSON file data on client side with pure javascript [duplicate]

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");

Phonegapped Android application not working as compared to HTML5 app

I made a HTML5 app, which accessess JSON data from a web service. The app works fine when opened in a browser on desktop computer, but when it is "phonegapped" into Android application it is not working. I have added following line on the PHP server to enable CORS:
header("Access-Control-Allow-Origin: *");
Following is the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<style>
img {
height: 100px;
float: left;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="images"></div>
<script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
function onMyClick() {
console.info(new Object("Hello"));
var url = 'http://example.com/mobile/index.php?tag=getAllById&catid=60';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
xhr.onload = function() {
var responseText = xhr.responseText;
console.info(responseText);
// process the response.
};
xhr.onerror = function() {
console.info('There was an error!');
};
xhr.send();
console.info(new Object("Hello 4"));
}
</script>
<input type="button" value="OK" onclick="onMyClick()"/>
</body>
</html>
Not working as Android app means that I am getting, "There was an error!" message as the above line in onerror event prints, instead of the JSON data as response text, in the console of eclipse. Please could anyone help me get this working as Android application also.
With the above example I can't see what is wrong but there are multiple possibilities.
The domain you are accessing might not be white listed in your config.xml? To allow everything include the following:
<access origin="*" />
See docs about white list for more info here
Another thing which comes to mind, your app needs internet connection to work, do you have the required permissions setup in AndroidManifest.xml?
You need to find the<uses-permission android:name="android.permission.INTERNET" /> declaration.

Categories

Resources