HTTP Python server: javascript no longer works - javascript

I have some JavaScript code that I use to retrieve data from a json file and populate a dropdown list.
Everything was working fine.
I added some code and it went into an infinite loop.
I deleted this code but since then it no longer works on the HTTP server I setup using Python.
HOWEVER it works perfectly fine when I load it on a network server.
I deleted Python, reinstalled and still not working.
Logically it can't be the code because it works on the network server... I am totally lost. Any and all help much appreciated. I am getting now where fast. (I can't work from the network server so need this working locally.)
Below is the javascript
//this will hold the data from JSON
var teamSkillsData
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//retrieve data from the external json file
var response = JSON.parse(xhttp.responseText);
teamSkillsData = response.teamSkills;
var select = document.getElementById("teamList");
alert("nn");
//populate the teamList drop down menu
for(var i = 0; i < teamSkillsData.length; i++) {
//assign the team names
var opt = teamSkillsData[i].team;
var el = document.createElement("option");
el.textContent = opt;
el.value = i;
select.appendChild(el);
}​
// Typical action to be performed when the document is ready:
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", 'Data.json', true);
xhttp.send();
function teamChanged(teamSelected)
{
var skills = teamSkillsData[teamSelected].skillset;
for(var i = 0; i < skills.length; i++) {
skillsRequired = skills[i];
alert(skillsRequired);
}​
}

Related

Problem populating a select dropdown list using JSON

Hello I am trying to populate a select list using JSON and I am not getting any console errors however the list is not getting populated at all.
This is my html code
<select id="player_dropdown1">
</select>
This is my javascript code
var request = new XMLHttpRequest()
request.open('GET','https://cors-
anywhere.herokuapp.com/https://fantasy.premierleague.com/api/bootstrap-static/' , true)
request.onload = function() {
let dropdown = document.getElementById('player_dropdown1');
dropdown.length = 0;
let defaultOption = document.createElement('option');
defaultOption.text = 'Select a player';
dropdown.add(defaultOption);
dropdown.selectedIndex = 0;
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
let option;
for (let i = 0; i < data.length; i++) {
option = document.createElement('option');
option.text = data.elements[i].firstname + data.elements[i].secondname;
option.value = data.elements[i].secondname;
dropdown.add(option);
}
} else {
}
console.log(data);
}
request.onerror = function() {
console.error('An error occurred fetching the JSON');
};
request.send();
I am not sure why the dropdown list is not getting populated. The json is getting parsed successfully to the console.
If you have a document.getElementById(ID) returning null or undefined on a very obviously defined ID, it is because your DOM element having the ID in question does not exist when the javascript is loaded.
You have two solutions:
- Include the script after the DOM element having the ID is declared
- Delay the execution of your code until the document is loaded, see this question for plain javascript.
I would personally choose the first solution if there are no "obligations" (such as code pattern) to include the javascript before the end of the document. This is going to save you the lines of codes of the event handlers and performance-side it does not add any more operations during the loading of the webpage.

Trying to post to a .txt file fails but performing a get does work

My partner and I are trying to get a domain that I own, communicate with a ios app that is run on objective c to work via http. He is using the code that was provided by this link Sending an HTTP POST request on iOS.
He is able to do a GET to receive the data in my .txt page but when he performs a PUT to try and write to that file so that I can get that data it fails. We are both rather new to http so it is possible that we are missing something. A concern we have is that he doesn't have the privileges to write to this file. Any advice would help, thanks!
Here is the javascript I am using on my side. I added a header to my response to try and resolve the cors issue.
(function () {
window.onload = function () {
httpGetAsync("http://students.washington.edu/bharatis/distances.txt", processData)
//alert("hello inside onload");
document.getElementById("first").innerHTML = leader1;
document.getElementById("second").innerHTML = leader1;
document.getElementById("third").innerHTML = leader1;
//window.onbeforeunload = update;
}
function processData(responseText) {
//alert(responseText);
var txt = "";
var x = responseText.getElementsByTagName('Distance'); // Talk to alex about
for(i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue;
}
var result = parseDouble(txt);
alert(result);
}
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.send("response message");
}
})();

HTML Rename download link

I have a mp3 link like this :
http://example.com/932937293723.mp3
but i want to rename it when user downloads the file to be like this
http://example.com/Artist - Title.mp3
My code :
DOWNLOAD
The mp3 file stored in remote server. And i'm not the owner of that server.
HTML download attribute seem not good solution. because it's not cross-browser. Any cross-browser solution to solve this ? Javascript maybe :D
If you insist on working from the front end, try working with the following code. The getblob method is depreciated, but you need to update that side. Let me know.
function getBinary(file){
var xhr = new XMLHttpRequest();
xhr.open("GET", file, false);
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(null);
return xhr.responseText;
}
function sendBinary(data, url){
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
if (typeof XMLHttpRequest.prototype.sendAsBinary == "function") { // Firefox 3 & 4
var tmp = '';
for (var i = 0; i < data.length; i++) tmp += String.fromCharCode(data.charCodeAt(i) & 0xff);
data = tmp;
}
else { // Chrome 9
// http://javascript0.org/wiki/Portable_sendAsBinary
XMLHttpRequest.prototype.sendAsBinary = function(text){
var data = new ArrayBuffer(text.length);
var ui8a = new Uint8Array(data, 0);
for (var i = 0; i < text.length; i++) ui8a[i] = (text.charCodeAt(i) & 0xff);
var bb = new BlobBuilder(); // doesn't exist in Firefox 4
bb.append(data);
var blob = bb.getBlob();
this.send(blob);
}
}
xhr.sendAsBinary(data);
}
var data = getBinary("My music.mp3");
sendBinary(data,'http://www.tonycuffe.com/mp3/tailtoddle_lo.mp3');
In your back end code, you can fetch the file to your server, store it to a variable, rename it from there, define the corresponding headers, and return it. this could happen as an ajax call initiated on the javascript click.
Post further details about your backed and i can help you more.
You can use something like below (ASP.NET)
In ASPX
Download
In ASP.NET
Response.ContentType = "audio/mpeg3";
Response.AddHeader("content-disposition", "attachment;filename=New_file_name.mp3");
Server.Transfer(decoded_URL_of_MP3_file);
Look here for other MIME types
Update#1 - Using Javascript alone, you can try something like this, though I've not tested in different browsers
function Download(url, fancyFileName)
{
var file = document.createElement('a');
file.href = url;
file.target = '_blank';
file.download = fancyFileName;
var event = document.createEvent('Event');
event.initEvent('click', true, true);
file.dispatchEvent(event);
window.URL.revokeObjectURL(file.href);
}
Download('http://server.com/file.mp3','Artist_file.mp3');

AJAX loop, calling function onload vs. manually in the console/code

I have 2 functions:
function find_existing_widgets(){
xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', './_includes/check-load-user-settings.php', true);
xmlHttp.onreadystatechange = open_existing_widgets;
xmlHttp.send(null);
}
function open_existing_widgets(){
if(xmlHttp.readyState==4 && xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
root = xmlResponse.documentElement;
var widget_id = root.getElementsByTagName('widget_id');
var name = root.getElementsByTagName('name');
var type = root.getElementsByTagName('type');
var value = root.getElementsByTagName('value');
for(i= 0; i< name.length; i++)
{
nameText = name.item(i).childNodes[0].nodeValue;
widgetID = widget_id.item(i).childNodes[0].nodeValue;
//var value = name.item(i).firstChild.data;
alert(nameText);
nameText = nameText.replace(/\s+/g,'_');
//alert(value); WORKS
widget_creator();
load = "./widgets/"+nameText+"/index.php?widget_id="+widgetID;
//alert(load); WORKS
$('.wrapper:first .main_sec').load(load);
$('.wrapper:first').fadeIn(1000);
}
}
}`
4 scenarios:
one. running the function find_existing_widgets() onload on the <body> tag and works perfect. runs once and shows data accordingly
two. running same function before the </body> tag like: <script>find_existing_widgets()</scripts> and this causes an infinite loop.
three. running the same function as window.onload = find_existing_widgets(); in JS code. and this cause the same issue as two, infinite loop.
four. if I run it manually from the console it works perfectly.
Why the loop? what's the difference ?
Once there you'll see the execution that is looping. I am using AJAX, all the javascript can be seen in the dev tools in chrome.
Example:
josesebastianmanunta.com/animated3/login.php user: smanunta pass: password

XMLHttpRequest that is being Aborted

I'm looking over a bit of code that deals with XHR. It looks like the first XHR.send() is being done successfully and then the subsequent one is Aborted before it gets to it's .send()
Quick in dirty:
url = "http://192.168.1.1/cgi-bin/test.cgi";
data = "1235,123,21,1232,12321,432";
myXHR = new Array();
for(var i = 0; i < 2; i++) {
myXHR[i] = new XMLHttpRequest();
myXHR[i].open("POST", url, true);
myXHR[i].onerror = function() {
alert("Error occurred");
};
myXHR[i].onload = function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
};
// do some setting up of XHR headers
myXHR[i].send(data);
myXHR[i] = null;
}
What could be happening that would cause Firebug to show Abort before the second .send() is done?
Try this:
url = "http://192.168.1.1/cgi-bin/test.cgi";
data = "1235,123,21,1232,12321,432";
var myXHR = [];
for(var i = 0; i < 2; i++) {
myXHR[i] = new XMLHttpRequest();
myXHR[i].open("POST", url, true);
myXHR[i].onerror = function() {
alert("Error occurred");
};
myXHR[i].onload = function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
};
// do some setting up of XHR headers
myXHR[i].send(data);
myXHR[i] = null;
}
When I run this code I get TypeError: myXHR[i] is undefined (on the stock firefox 20 install on my mac... what version are you on)?
At any rate, I can see one issue with this (i.e. myXHR[i] will be undefined...) that might also apply to you, in particular with:
myXHR[i].onload = function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
};
Because this is triggered asynchronously i will have been incremented to 2, which is of course going to be outside the bounds of the two element myXHR array. Have you tried closing over the value of i, like so:
myXHR[i].onload = (function(i) {
return function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
}
})(i);
Because once I correctly save that i value in that function body this code will succeed for both calls.
I know this isn't the exact issue you're having, but I think it will be an issue regardless so you may as well give it a go right? It's not as though there have been a huge number of other answers unfortunately.
hope this helps..
Found out what was happening.
The XHR was being aborted because there was no return value from the webserver that the request was being sent to. The web server is a custom based one that we seem to be using the someone changed the code so that it wasn't sending a 200 Success OK even if the data sent to it had no data coming back.
All good now. Thanks for the help.

Categories

Resources