What is wrong with this HTML, JavaScript and JSON code? - javascript

I have the following HTML code in a file called test.html. Both the HTML file and the JSON file below are stored on a server within the same directory.
<!DOCTYPE html>
<html>
<head>
<title>Shape Up</title>
<meta name="robots" content="noindex,follow">
<meta name="description" content="">
<meta name="keywords" content="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="JavaScript" type="text/javascript">
function ajax_get_json()
{
var hr = new XMLHttpRequest();
hr.open("GET", "game.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function()
{
if(hr.readyState == 4 && hr.status == 200)
{
var data = JSON.parse(hr.responseText);
var results = document.getElementById("results");
results.innerHTML = "";
for(var obj in data)
{
results.innerHTML += data[obj].title;
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script language="JavaScript" type="text/javascript">
ajax_get_json();
</script>
</body>
</html>
It pulls data from a file called game.json which is stored in the same directory.
{
"level_001":
{
"id":001,
"title":"Level 1",
"difficulty":0,
"comments":"this is how you complete level 1"
},
"level_002":
{
"id":002,
"title":"Level 2",
"difficulty":0,
"comments":"this is how you complete level 2"
}
}
The problem is that the results.innerHTML = ""; line is never reached. Why?
There are no errors in the browser, I've checked this on Firefox and on Safari.

According to jsonlint.com your JSON is invalid because of these properties:
"id":001
...
"id":002
You need to either remove the leading zeros:
"id":1
or make the numbers strings:
"id":"001"
For further details see the format rules spelled out at json.org
Presumably the line you mentioned is never reached because JSON.parse() gives an error about the above. (Do you not see an error in the browser's console?)

Related

UTF-8 Arabic in JavaScript

I read this, but it did not solve my issue, and as it is old, I'm posting a new question.
I've the below code, that is recieving a SSE from GoLang server, but the Arabic script is not encoded probely:
<!DOCTYPE html>
<html lang="ar-AR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script>
</head>
<body>
<div id="msg"></div>
</body>
<script src="socket.js" charset="utf-8" type="text/javascript"></script>
</html>
And
var source = new EventSource("http://localhost:1234/sse/signal");
source.onmessage = function (event) {
var message = event.data
document.querySelector('#msg').innerHTML = message;
}
And sample output I get is:
data: {
"IsFromMe": false,
"IsGroup": false,
"ID": "26DE3A6A0AEA98406D286E9C58C40114",
"PushName": "إدارة قطو٠و حلا",
"Timestamp": "2022-07-05T09:45:46+03:00",
}
The PushName above should be Arabic script!
As mentioned by #slebetman in his comments, the correct answer is to send the data from the server as utf-8 which is done in my case as I'm sending data as streaming, by sending the Content-Type as text/event-stream; charset=utf-8
My code in the GoLang server became:
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")

$.get() remote HTML causes unwanted requests for that page's resources

I am fetching a remote page's HTML and returning the HTML to review meta tags and I notice unexpected failed requests for all the remote assets in the other page's HTML whenever I assign that to a variable.
$.get(url, function(data, status) {
var dt = $(data);
}
By the time I've assigned that variable, it triggers all these remote requests.
How can I avoid the the fact that assigning this data to a variable in the DOM seems to trip a request for every image or resource on that remote page!
When you do $(data), jQuery ends up parsing the hTML and causes the requests to be made for the resources.
To get around it, use DOM parser so the resources are not fetched.
const myHTMLSource = `
<html>
<head>
<meta name="title" content="Foo Bar">
<meta name="description" content="FOO FOO">
<meta name="keywords" content="bar, egg, bacon">
<meta name="robots" content="index, follow">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="language" content="English">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"><\/script>
</head>
</body>
<h1>Test</h1>
<img src="http://placekitten.com/200/300" />
</body>
</html>`;
const parser = new DOMParser();
const testDoc = parser.parseFromString(myHTMLSource, "text/html")
const metaTags = testDoc.querySelectorAll("meta");
console.log(metaTags.length);
Since being asked how to use in in the jQuery Ajax request, it just uses data:
var request = $.ajax({
url: url,
method: "GET",
dataType: "text"
}).done(function( data ) {
const parser = new DOMParser();
const testDoc = parser.parseFromString(data, "text/html")
const metaTags = testDoc.querySelectorAll("meta");
console.log(metaTags.length);
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
So you claim: GETTING the html results in the requests inside the result are executed when doing $(data). So the issue is to NOT use $(data) but the raw HTML but that means some kind of split on </head> BEFORE creating a DOM fragment
Try this:
Uncomment the comments and remove the string I use for testing
//$.get(url, function(data, status) { // uncomment
// const dt = data.split("</head>")[0]
const fragment = document.createElement("div");
// fragment.innerHTML = dt;
// test
fragment.innerHTML = `<html>\n<head>\n<meta name="title" content="Foo Bar">\n<meta name="description" content="FOO FOO">\n<meta name="keywords" content="bar, egg, bacon">\n<meta name="robots" content="index, follow">\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<meta name="language" content="English">\n<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"><\/script>`;
[...fragment.querySelectorAll("meta")]
.forEach(meta => {
console.log([...meta.attributes]
.map(attr => `${attr.nodeName}: ${attr.nodeValue}`))
})
//}}

How to handle an "undefined" error while converting CSV file to JSON using Papa Parse framework?

So, this is my JS code:
function main(){
let myJSON = parseCSV();
console.log(myJSON);
let myCSV = transformCSV(myJSON);
console.log(myCSV);
}
function parseCSV(){
let parsedJSON;
let selectedFile = document.getElementById('fileIn').files[0];
Papa.parse(selectedFile, {
complete: function(results) {
parsedJSON = results.data;
console.log(results.data);
console.log(typeof(results.data));
}
});
return parsedJSON;
}
function transformCSV(JSONIn){
let csvOut = ""; // i will do something here later
let dCol = ""; // i will do something here later
let dRow = ""; // i will do something here later
for (let i = 0; i < JSONIn.length - 1; i++) {
// i will do something here later
}
return csvOut;
}
And this is my test html page:
<!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>
<script src=".\transformCSV.js"></script>
<script src=".\node_modules\papaparse\papaparse.js"></script>
<input type="file" id="fileIn">
<input type="button" value="click!" onclick="main()">
</body>
</html>
When I try to read length of myJSON, I get error message in Chrome console: Uncaught TypeError: Cannot read property 'length' of undefined. Why is it undefined? It is present in console! Why does this happen and how to fix it? How to work with resulted myJSON as a perfectly normal static JSON?
You set the value of parsedJSON in the complete callback function. This will probably be called AFTER your function parseCSV has returned the undefined value of parsedJSON. You need to rewrite it with a callback or promise.
parseCSV(function (myJSON) {
console.log(myJSON);
let myCSV = transformCSV(myJSON);
console.log(myCSV);
});
function parseCSV(callback){
let parsedJSON;
let selectedFile = document.getElementById('fileIn').files[0];
Papa.parse(selectedFile, {
complete: function(results) {
parsedJSON = results.data;
callback(parsedJSON);
}
});
}

Uncaught Error: Error calling method on NPObject.

am a newbie to JSON and i just cant's access to the object data.
this is the code :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ajax </title>
</head>
<body>
<p id="p"></p>
<script type="text/javascript" >
var r = new XMLHttpRequest()
r.open("GET", "d.json");
if(r.readyState ===4 && r.status ===200){
var data = JSON.parse(r.responseText);
var p = document.getElementById("p");
p.innerHTML = data.user;
}
r.send();
</script>
</body>
</html>
and this is the d.json file
{"user":"khaled","age":"20"};
i got that error : "Uncaught Error: Error calling method on NPObject. "
thanks.
if its a flash url ur dealing with then this link will help
npe flash
else
a general discussion in google comm
npe google

Simple way of displaying images from parse.com database using javascript

I was working on a very simple page which just pulls and displays images from a table in parse.com. I do not have much experience with javascript which might be evident from the code below.
I need the images to show up in a chronological order. With the current code, it works fine most of the times but is a little buggy.
There are 2 main problems:
1) Sometimes, randomly, one particular new image might not come on the top and instead show up somewhere in between.
2) This page works on Firefox and Chrome but NOT on IE.
Is there a better way to implement this or is there something that I should change? Any help would be appreciated.
Page source-
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js"></script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url;
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});
</script>
</body>
</html>
Internet Explorer blocks mixed content. Since Parse's JavaScript SDK requires SSL, you need to host your app using HTTPS as well in order to access it from IE.
Hey you made one mistake. it was not working for me. Then i found that it is url() not url.
The amendment is img.src = results[i].get("image").url();
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js">
</script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url();
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});

Categories

Resources