Good evening, I am a beginner, I am on an application where the client has to download one of the xml files, but when the file is in local folder it downloads it and when it is elsewhere, it says:
GET https://localhost/dossier/data.xml 404 (Not Found).
How to make it accept the file no matter where it is?
This is the code:
<form id="parcourir">
<input type="file" id="real-file" hidden="hidden" />
<button type="button" id="custom-button">Parcourir</button> <br>
<span id="custom-text">Aucun fichier selectionné</span>
</form>
<script>
const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");
customBtn.addEventListener("click", function () {
realFileBtn.click();
})
realFileBtn.addEventListener("change", function () {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value.match(/[\/\\]([\w\d\s\.\-\(\)]+)$/)[1];
console.log(location.href);
console.log(customTxt.innerHTML);
myFunction(this);
} else {
customTxt.innerHTML = "no file choosen yet";
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", customTxt.innerHTML, true);
xhttp.onload = (response) => {
console.log(xhttp.response);
}
xhttp.send();
})
function myFunction(xml) {
var xmlDoc = xml.responseXML;
console.log(xmlDoc);
}
</script>
Related
Im currently trying to parse JSON data from this api in JS but im not sure how to. As of right now when I press any buttons to give me the data, it prints the arrays out rather than the specific data I want. Ive tried to use the JSON Parse function to retrieve the specific data but it seems its not working. Any help would be greatly appreciated! URL to the API docs: https://www.balldontlie.io/#get-all-players
//Loads Player Data
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("players").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
var data = JSON.parse(xhttp.responseText);
console.log(data["last_name"])
xhttp.send();
}
//Loads Game Data
function loadGames() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("games").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/games", true);
xhttp.send();
}
//Loads Team Data
function loadTeams() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("teams").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/teams", true);
xhttp.send();
}
<!DOCTYPE html>
<html>
<body style="background-color:peachpuff;" >
<center>NBA STATS</center>
<center><marquee behavior="scroll" direction="right" scrollamount="12.5">Data Extracted From BDL API</marquee></center>
<center> View API Docs </center>
<script src="main.js"></script>
<div id="players">
<button type="button" onclick="loadPlayers()">View Players</button>
</div>
<div id = "teams" >
<button type="button2" onclick="loadTeams()">View Teams</button>
</div>
<div id ="games">
<button type="button3" onclick="loadGames()">View Games</button>
<div>
</body>
</html>
You should parse JSON in xhttp.onreadystatechange, that's a callback when request data success.
For the players data as example, it is an object with data and meta, and the players is in data key which is an Array, so you need to loop inside the array to print the values that you needed.
Here's the example for loadPlayers(). You can apply the same concept to loadGames and loadTeams, please let me know if you still having questions.
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// parse JSON after response
var players = JSON.parse(this.responseText);
// get 'data' key inside response
var playersData = players.data;
// loop all the players
for (var player of playersData) {
// print last_name to the #players element
document.getElementById("players").innerHTML += "<br />" + player['last_name'];
}
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
xhttp.send();
}
In function loadPlayers()
data is an array not object
I'm a good back dev, but have a huge problem at front. So, i have a form that download photo to send it to server.
<form name="Forma" id="photoForm" method="POST" enctype="multipart/form-data">
<input type="button" class="btn btn-secondary" name="btn_file" id="loadFileXml" value="Выбрать фото" onclick="document.getElementById('file').click();" />
<input type="file" id="file" style="display:none" name="photo" required accept="image/jpeg,image/png,image/gif " />
<button type="submit " class="btn btn-primary " hidden id="Test1">Проверить</button>
</form>
And here is a function that should send data to server, for getting JSON response (i'm not sure with it,
var fileuploadinit = function(){
$('#file').change(function(){
var pathwithfilename = $('#file').val();
var filename = pathwithfilename.substring(12);
console.log(this.value);
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').removeAttr("hidden");
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(file.files[0]);
});
};
$("#imgInp").change(function() {
readURL(this);
});
$(document).ready(function () {
fileuploadinit();
});
$('#file').on('change', function() {
if (this.value) {
console.log("Оппа, выбрали файл!");
console.log(this.value);
// $('#Test1').attr("disabled", "false")
$("#Test1").removeAttr("hidden");
$('#Test3123').attr("src", this.value);
$("#info").removeAttr("hidden");
} else { // Если после выбранного тыкнули еще раз, но дальше cancel
console.log("Файл не выбран");
}
})
var button = document.getElementById("Test1")
button.onclick = handleButtonClick;
function handleButtonClick() {
alert("Вы нажали на кнопку");
var xhr = new XMLHttpRequest();
var url = "/api/upload";
xhr.open("Post", url, true);
xhr.setRequestHeader("Content-type", "multipart/form-data");
xhr.setRequestHeader("Access-Control-Allow-Origin", "url/");
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 & xhr.status == 200){
var json = JSON.parse(xhr.responseText);
console.log(json.name);
}
};
var data = new FormData(photoForm)
xhr.send(data);
}
So, i spent on it for like 2 days, and absolutely don't know how to get photo from form to server. i tried literally everything, i think. It works, then i use action at html form method.
I have a form like this:
function nametst(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("namevalidity").innerHTML = this.responseText;
}
};
xmlhttp.open("POST", "nametst.php?=namerequest" + str, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
function mailtst(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("mailvalidity").innerHTML = this.responseText;
}
};
xmlhttp.open("POST", "mailtst.php?=mailrequest" + str, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
function submittst(){
nametst(document.getElementsByName('name')[0].value);
mailtst(document.getElementsByName('email')[0].value);
return xls;
}
var xls;
function submittes(callback){
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
callback(httpRequest.responseText);
}
};
httpRequest.open('POST', "submitform.php", true);
httpRequest.send();
}
submittes(function (result) {
if (result === "yes"){
xls = true;
document.getElementById("submitanswer").innerHTML = "true";
}
else{
xls = false;
document.getElementById("submitanswer").innerHTML = "false";
}
});
<form method="POST" onsubmit= "return submittst();" action = "welcome.html">
Name: <input type="text" name="name" onblur="nametst(value)">
<span id="namevalidity"></span> </p>
email: <input type="text" name="email" onblur="mailtst(value)">
<span id="mailvalidity"></span> </p>
<input type="submit" value="submit">
<p> form validity: <span id="submitanswer"></span> </p>
and if the name and email are valid, submitform.php returns "yes".
When I type wrong name or email the errors will appear. So far, so good. But the form validity is always false, and it won't change even when I click "submit" button. When I set default value for name and email and they are valid, the form validity remains true.
Why does this happen?
And how can I solve it?
so, I knew that the problem was because of callback method. since there was no answer to my question, I'll use synchronous mode without these callbacks.
I am using third party WYSIWYG editor in my web application. I want to load the content from a file. How can I load the content? (javascript or React js)
var filecontent;
function selection(){
var filevalue=document.getElementById('files').value;
if(filevalue=="A"){
fetchDetailsA();
}
}
function fetchDetailsA() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
filecontent = this.responseText;
document.getElementById('NicEdit').innerHTML = filecontent;
document.myForm.NicEdit.value += "Hello";
alert(document.myForm.NicEdit.value)
}
};
xhttp.open("GET", "Textfiles/Sample1.json", true);
xhttp.send();
}
<form name="myForm">
<textarea id="NicEdit" cols="80" rows="5"></textarea>
</form>
You can use the fetch api introduces in javascript to make this much easier.
fetch('Textfiles/Sample1.json')
.then(response => response.text())
.then(text => {
document.getElementById('NicEdit').innerHTML = text;
document.myForm.NicEdit.value += "Hello";
})
In the current DEMO you can search one thing at a time.
If you search either values (1001, 1002, 1003) and a JSON property feature will be pulled.
So if I search: 1001
I get: RANK_BY_CD: 26
I've tired a fuzzy-search library - http://fusejs.io/ but I don't think what is needed since I need a series of EXACT matches
var data = [];
$(document).ready(function () {
$("#button").click(function (any_function_variable_name) {
var searchId = String($('#searchBox').val());
data.features.forEach(function (any_function_variable_name) {
if (any_function_variable_name.properties.CDUID == searchId) {
$("ul")
.append('<li> <strong>RANK_BY_CD: </strong>' + any_function_variable_name.properties.RANK_BY_CD);
}
});
});
});
function getdata() {
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/6oj58";
//var data = [];
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
getdata();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="searchBox" type="text"></textarea>
<button id="button">
Search
</button>
<div>
<ul></ul>
</div>
I want to have the ability to copy paste multiple strings (separated by line break) into the textarea like so:
1001
1002
1003
and get:
RANK_BY_CD: 26
RANK_BY_CD: 212
RANK_BY_CD: 248
Also, I don't want the code to just be limited to these 3 options.
As JSON file gets bigger I want to recognize all the CDUIDs
So a key legend will be inefficient in this case
This is the external JSON file url - https://api.myjson.com/bins/6oj58
You can create a Set which stores the list of ids and then check that against the CDUID of each item in data.features:
var data = [];
$(document).ready(function () {
$("#button").click(function (any_function_variable_name) {
var searchIds = new Set($('#searchBox').val().split(',').map(s => s.trim()));
data.features.forEach(({ properties: { CDUID, RANK_BY_CD } }) => {
if (searchIds.has(CDUID)) {
$("ul")
.append(`<li> <strong>RANK_BY_CD: </strong>${RANK_BY_CD}`);
}
});
});
});
function getdata() {
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/6oj58";
//var data = [];
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
getdata();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="searchBox" type="text"></textarea>
<button id="button">
Search
</button>
<div>
<ul></ul>
</div>