JSON Parse Javascript Issues - javascript

I am using the following to load a local txt file to convert it, the code is directly from W3c schools but the page loads nothing on screen and I have no errors on page or in the inspector. It wont work on MAMP or webserver. I am trying to learn vanilla JS so I don't want to use a library or jquery.
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "array.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for (i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>

Thanks for your help everyone, the issue was a clash with another function running on the page and the lack of 200 response from the local file.

Related

javascript from ajax doesn't get proper execution

Using Ajax, I've created a sort of console that allows me to execute some PHP functions dynamically.
It looks like this
The problem is that after a bunch of commands, the console becomes hard to read. So I've created a javascript function, named "wipe();", which clears the <div> containing the console.
I tested this function with the developpers tools of chrome (the javascript console) and it works perfectly.
But when I try to call this function by making the PHP-AJAX return a "<script>wipe();</script>", it doesn't work. It does nothing.
I've read on the internet that all the "<script></script>" works independently from each other, but that you can call a <script>function</script> from another <script></script> block.
So why is it failing to do that ?
here is the php code :
echo '<script>wipe();</script>';
and here is the the first <script> block:
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data="+data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML+escapeHtml(data)+'<br>'+xmlhttp.responseText+'<br><br>';
}
xmlhttp.send();
}
function wipe(){
span.innerHTML = '';
}
To avoid security issues ( like a cross-site scripting attack) HTML5 specifies that a <script> tag inserted via innerHTML should not execute.
A way to execute the script is to evaluate the html using eval() . Be warned: using eval can be dangerous.
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data=" + data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML + escapeHtml(data) + '<br>' + xmlhttp.responseText + '<br><br>';
evalJSFromHtml(span.innerHTML);
}
xmlhttp.send();
}
function wipe() {
span.innerHTML = '';
}
function evalJSFromHtml(html) {
var newElement = document.createElement('div');
newElement.innerHTML = html;
var scripts = newElement.getElementsByTagName("script");
for (var i = 0; i < scripts.length; ++i) {
var script = scripts[i];
eval(script.innerHTML);
}
}
}
Call the 'wipe' function as a callback function directly from the 'send' function. Check status = 200 for a success response.
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data="+data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML+escapeHtml(data)+'<br>'+xmlhttp.responseText+'<br><br>';
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
wipe(); // 'Wipe' callback function
}
}
xmlhttp.send();
}
function wipe(){
span.innerHTML = '';
}
But when I try to call this function by making the PHP-AJAX return a "wipe();", it doesn't work. It does nothing.
try create script tag and add to document rather than change inner html.
var spaScript = document.getElementById("spaScript");
var wraper = document.createElement("div");
wraper.innerHTML = xmlhttp.responseText;
var script = document.createElement("script");
script.innerHTML = wraper.getElementsByTagName("script")[0].innerHTML;
spaScript.appendChild(script);
Test if wipe() is in the input and if it is trigger it instead of the ajax call
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
if (data.indexOf('wipe()') == -1) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data=" + data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML + escapeHtml(data) + '<br>' + xmlhttp.responseText + '<br><br>';
}
xmlhttp.send();
}
} else {
wipe();
};
}
function wipe() {
span.innerHTML = '';
}
inserting a script tag directly inside an element should not work (and by the way generating an error in the console).
Using the native eval() function on the response text without speciying the tag attribute should solve the problem.
on server side
echo 'wipe()';
on client side
eval(xmlhttp.responseText)

How to count no. of image files in local folder using javascript

I am new to JavaScript and am trying simple web design. I have a doubt that how to get no.of image files stored in local image folder using js code.
I would like to get the no. of image files dynamically so that even if we are adding more images in folder any time that also will be displayed on web page.
function parenting {
var n=3;
for(var i=1; i<=n; i++) {
var img1 = document.createElement('img');
img1.src = 'images/parenting/'+i+'.jpg';
document.body.appendChild(img1);
}
}
In above code, i have given n=3 as default no. of image files but it should be taken from image folder by code.
If you enable directory browsing on your web server for your images location, then you can do an ajax request and iterate over the results:
$.ajax({
url: "images/parenting/",
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='images/parenting/" + filename + "'>");
});
}
});
Here's a vanilla JavaScript answer:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
var n = (xmlhttp.responseText.match(/jpg/g) || []).length;
for (var i = 1; i <= n; i++) {
var img1 = document.createElement('img');
img1.src = 'images/parenting/' + i + '.jpg';
document.body.appendChild(img1);
}
}
}
};
xmlhttp.open("GET", "images/parenting/", true);
xmlhttp.send();

Only one JavaScript function loading on page load.

I have a webpage with a few JavaScript functions set to load on document.ready.
However, if I have 4 of these, only the final one seems to load.
Here is the code I have.
$(document).ready(function ()
{
var nation = "ireland";
var irelandMatches = [];
var matchOrderReversed = false;
loadDoc();
showRSS("Irish Times");
loadWeather();
loadTwitter();
The loadDoc() and loadTwitter() methods load, but weather and showRSS do not. If I comment out loadTwitter(), then the weather loads fine.
If it makes any difference, all of these methods make use of an XMLHttpRequest, each of which is defined within each method, like so.
function loadYouTube()
{
var html = "";
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var ret = xmlhttp.responseText;
var spl1 = ret.split("~");
for (i = 0; i <= 10; i++)
{
var spl2 = spl1[i].split("*");
var current = "<a href='" + spl2[1] + "'><img src='" + spl2[2] + "' width='50' height='50'>" + "<a href='" + spl2[1] + "'>" + spl2[0] + "</a> <br/>";
html += current;
}
$("#yt").html(html);
}
}
xmlhttp.open("GET", "getyoutube.php?", true);
xmlhttp.send();
}
Thanks guys :)
It looks like when you define xmlhttp in your loadYouTube() example, you are doing so on the global scope due to the lack of var. So loadDoc() sets window.xmlhttp, then loadWeather() overwrites it shortly after, followed by loadTwitter().
Try something like this in your loading functions:
function loadYouTube()
{
var html = "";
// define xmlhttp in block scope
var xmlhttp;
// rest of function...
}

Need help displaying the contents of a JSON file

http://jsfiddle.net/hbrennan72/0urqaee9/
I have taken a very simple W3Schools JSON example and modified it ever so slightly. I am having trouble displaying just the contents contents of the JSON file. The external JSON file is referenced in the JS but I also copied the contents into the CSS frame on JSFiddle. Any help would be appreciated.
var xmlhttp = new XMLHttpRequest();
var url = "http://schwartzcomputer.com/ICT4570/Resources/USPresidents.json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].president + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
You need to iterate through arr.presidents.president
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.presidents.president.length; i++) {
out += JSON.stringify(arr.presidents.president[i]) + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
For the XML references, ex. xmlns:xsi, you will need to use bracket notation. You can reference the presidents list objects as you would any JavaSscript object.
Forked jsfiddle
You can display the properties in any format you like.
function myFunction(arr) {
alert(arr.presidents["xmlns:xsi"]);
alert(arr.presidents.president[0].number + ". " + arr.presidents.president[0].name);
...
}
EDIT
I have amended the jsfiddle to create a table. I did not include all the fields you specified, but will get the general idea.

Slow ajax for simple DB access

While testing out setInterval(), i had a slow load time for an ajax request. It was very simple and other pages with much more complex requests were terminating in less than a second while this very simple one is terminating after 10-12. Without using setInterval() it is still taking this long and it uses the same layout as the other pages.
Example of script:
document.getElementById("test").innerHTML = "Starting";
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("test").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/TestLive.cshtml", true);
xmlhttp.send();
Slow server page (ASP.NET):
Response.Expires = -1;
var db = Database.Open("mydb");
string query = "select Name from Game where ID='97';";
Response.Write(db.QuerySingle(query).Name);
Example of fast:
Response.Expires = -1;
string query = "select * from Season where Season.Game = 'Football' and Season.End > '" + DateTime.Now.Add(new TimeSpan(-8,0,0)).ToString("yyyy-MM-dd") + "';";
var db = Database.Open("mydb");
var result = db.Query(query);
Response.Write("<select id=\"chosenSeason\" onchange=\"setDraftSeason()\">");
Response.Write("<option selected=\"selected\">Choose a Season</option>");
foreach (var season in result)
{
Response.Write("<option value=\"" + season.ID + "\">");
Response.Write(season.Name);
Response.Write(" (" + season.Start.ToString("dd-MM-yyyy") + " - " + season.End.ToString("dd-MM-yyyy") + ")");
Response.Write("</option\">");
}
Response.Write("</select>");
EDIT: It seems to be related to using the layout page to access the script. all of the fast pages use the same setup though.

Categories