JSON parse and stringify error - javascript

Please can you help -- why does this JSON not work
the head of my page looks like this
<script src="Scripts/json2.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/JScript.js" type="text/javascript"></script>
and my ajax looks like this
var p = { "myText": JSON.stringify(tableOBJ) };
$.ajax({
type: "POST",
url: "Default2AJAX.aspx",
data: p,
success: function (data) {
var obj = JSON.parse(data);
}
});
In firefox I get this error on the JSON
Error: syntax error
Source File: /Scripts/json2.js
Line: 4
Source Code:
<!DOCTYPE html>
In IE 7 I get JSON undefined
in ie 8 i get
SCRIPT1002: Syntax error json2.js, line 4 character 1
In ie 9 i get
SCRIPT1002: Syntax error json2.js, line 4 character 1
How do I fix this? as I have added json2.js but it appear if the browser doesnt need it it throws an error?

Change Scripts/json2.js to point to a real copy of json2.js. At the moment it is pointing to an HTML document (probably a 404 error page).

I am betting that the file "Scripts/JScript.js" does not exist on your server and that the Source Code: <!DOCTYPE html> is a 404 error page.

#Hello-Word & #Rocket Hazmat:
The file at github link is an html file. To solve the problem:
Download json2.js
Change the file extension to html
Open the file in a web browser
Scroll down the page, copy the javascript code portion, and save it to a new file as json2.js
BTW, thanks to Douglas for the json parser. Makes my life much easier.

There appears to be an error in the json2.js file you are using -- at least IE 8 & 9 agree that an error exists on line 4 of that file.

Related

Sibling text file string to blob in JavaScript - unavailable?

I have a text file (here big_buck_bunny_trailer_480p.srt), "sibling" to a html page (so when I run the html page locally, it is a local file - when I run it on server, it is a remote file) - the directory structure is:
.
├── big_buck_bunny_trailer_480p.srt
└── ttt.html
I'm trying to read the text file using XMLHttpRequest; that succeeds fine, and I can get the string content of the text file. But when I try to create a Blob out of it, in Firefox 60 console I get "unavailable".
This is my test file, ttt.html:
<script type="text/javascript">
function reqListener () {
console.log(this.responseText);
var myblob = new Blob([this.responseText], {
type: 'text/plain'
});
console.log(myblob);
}
var oReq = new XMLHttpRequest(); // "To read files that are siblings of the HTML document, use XMLHttpRequest"
oReq.addEventListener("load", reqListener);
oReq.open("GET", "big_buck_bunny_trailer_480p.srt");
oReq.send();
</script>
When I run it in Firefox 60, console prints out:
1 ttt.html:4:3
00:00:00,005 --> 00:00:03,800
The peach open movie project presents
(...)
<unavailable> ttt.html:8:3
The character encoding of the HTML document was not declared. ...
XML Parsing Error: syntax error
Location: file:///tmp/test/big_buck_bunny_trailer_480p.srt
Line Number 1, Column 1: big_buck_bunny_trailer_480p.srt:1:1
So, I get the string right - but why is the Blob <unavailable>? How can I get a Blob out of this string?
Bonus question: I get why the warning "The character encoding of the HTML document was not declared" appears, - after all, I don't even have <html> in my html file. BUt why does XML Parsing Error: syntax error appear? All I asked for was to read this file, not parse it? If the parsing is automatic, can I prevent it somehow - all I need are the string contents?
EDIT: reduced the example to this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
var myblob = new Blob([window.btoa("Hello world")], {
type: 'text/plain'
});
console.log(myblob);
</script>
</head>
</html>
... and accessed it by using python -m SimpleHTTPServer, so via http://127.0.0.1:8000/ttt.html; and the only printout I get in the console is:
<unavailable> ttt.html:22:3
So, how do I get an actual blob from a string?
your html tags may interrupt the xml parsing. That's why its throwing Syntax Error. That kind of error is very common in JSON or XML parsing. Before create Blob, encode the Response Data.
Try this,
new Blob([window.btoa(this.responseText)], {
type: 'text/plain'
});
And also, When you retrieve the data from Blob. You need to decode using window.atob().
There are many things that browsers won't allow to happen over the file:// protocol. This is probably one of them.
Instead of running it over the file:// protocol, it is better to use a small local server to run it over. There are lots of them out there, so lots of options. Many IDEs even have them built in. I like to write a quick 10-line version with Express and Node. Whichever you chose, it'll just serve up static files for you over the http:// protocol so you can avoid these issues.
Got it, finally - turns out, if you watch console.log(myblob); in Firefox 60 Browser Console (Ctrl-Shift-J, the one in standalone window), then you get <unavailable>; but if at the same time, you observe the Web Console (Ctrl-Shift-K, sits in a tab near the Inspector of Inspect Element right-click), then you get a proper printout; see .gif:
Here it is accessed via a local server, so through http://127.0.0.1:8000/ttt.html - but accessing it locally via file:// protocol yields the exact same results (the blob can be seen in Web console to be instantiated fine, regardless of protocol).
For reference, here is the final ttt.html I used while capturing the .gif video:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function reqListener () {
console.log(this.responseText.substr(0,60)+"...");
var myblob = new Blob([window.btoa(this.responseText)], {
type: 'text/plain'
});
console.log(myblob);
}
var oReq = new XMLHttpRequest(); // "To read files that are siblings of the HTML document, use XMLHttpRequest"
oReq.overrideMimeType("text/plain");
oReq.addEventListener("load", reqListener);
oReq.open("GET", "big_buck_bunny_trailer_480p.srt");
oReq.send();
</script>
</head>
</html>

My code doesn't work on CodePen or JsFiddle when I upload it but works fine in my browser. Would anyone be able to help me please?

I am new to codePen. I am probably doing a stupid mistake but would any one be able to point it out please?
function initialDraw(e) {
var surfaceContext = surface.getContext('2d');
surfaceContext.drawImage(wheel, 0, 0);
}
http://codepen.io/hTeeML/pen/RPJemx
Dropbox doesn't serve the raw js file but a html document displaying the javacript. This is legitimately seen by the browser as wrong and therefore unusable.
See here:
https://www.dropbox.com/s/dbt9dzsepaie0tp/winwheel_1.2.js?dl=0
Output from the firefox console when loading the CodePen page:
SyntaxError: expected expression, got '<' winwheel_1.2.js:1:0
Dropbox file start:
<!DOCTYPE html>
Sidenote
Your javascript contains occurences of this pattern:
var wheelImageName = url("http://i60.tinypic.com/t9f7s1.png");
This will not only fail because it is interpreted as a function but also because this is the wrong data format for the src attribute of an img tag.
Fixed code:
var wheelImageName = "http://i60.tinypic.com/t9f7s1.png";

Uncaught SyntaxError: Unexpected token < in JQuery UI Maps plugin? Works locally, not on the server

I'm working on a fairly simple site using Twitter Bootstrap. I'm having an issue with getting my Google Maps plugin to work. On localhost using Apache, it works fine. On the server, also Apache, it does not. I get this error:
Uncaught SyntaxError: Unexpected token <
On the first line of this file (jquery.ui.map.min.js):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html><head>
<title>Menu for /assets/js/jquery.ui.map.min.js</title>
</head><body>
<h1>Menu for /assets/js/jquery.ui.map.min.js</h1>
<hr />
<pre> jquery-ui-map</pre>
<pre> d[e]}];e=function(){return'\\w+'};c=1;};while(c--)if(k[c])p=p.replace(new</pre>
</body>
</html>
Here is a link to see the problem:
http://jhfc-law.com/contact.html
Again, the map and everything work fine locally. I'm sure the server is reading that DOCTYPE line as an issue due to the opening <, but I'm unsure how to fix this. It's causing this error as well (since the first file is breaking, gmap isn't being initialized so I can't use this following line):
Uncaught TypeError: Object [object Object] has no method 'gmap'
Which is in this method in my scripts.js file (which is being loaded after the previous file):
jQuery(document).ready(function() {
var position = new google.maps.LatLng(31.22633, -85.39422);
$('.map').gmap({'center': position,'zoom': 15, 'disableDefaultUI':true, 'callback': function() {
Uncaught TypeError: Object [object Object] has no method 'gmap'
var self = this;
self.addMarker({'position': this.get('map').getCenter() });
}
});
});
Any help is appreciated!
T
Your map javascript isn't on the server. This is what you're linking to: http://jhfc-law.com/assets/js/jquery.ui.map.min.js
Furthermore, it looks like the correct (?) link is broken as well: http://jhfc-law.com/assets/js/jquery-ui-map

JQuery .getJson wont load local file plus how to convert to JavaScript object.

Hey guys I am trying to learn how to use JSON files. I understand the basics but I am trying to grasp loading them into an HTML file and I am having a couple of difficulties.
The first difficulty I am having is that if I put in the full file extension to load the file I get an error 'expected hexadecimal digit'. I did some research on it and I think it is because in the file extension it is \u so it is expecting a hexadecimal but I am not sure how to work around it.
The second problem I am having is that if I just use the file extension users.json it works in my editor but not in a browser. It is not loading the file at all, the code is fine (I believe). I think it is just not loading the file because of the file extenion.
Suggestions on how to fix my problems? Thanks in advance.
<body>
for output
<div id="forOutput"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var output;
$(document).ready(function(){
alert("JQuery loaded");
});
$.getJSON('C:\Users\Spencer\Desktop\JSJqueryTesting\JSONTesting\users.json', function(data) {
output = data;
for (var i in data.users) {
alert(data.users[i].firstName + " " + data.users[i].lastName+ " " + data.users[i].joined.month);
}
});
$("#forOutput").html("User 1 lastname: " + output.users[1].lastName);
</script>
The file extension is perfect (.json), however, you can't load local files (because of security reasons). If what you are trying to do, were possible, that would mean any website could access all your local files. Now that's really not such a good idea, and therefore (by default) only files that share the same domain(e.g. stackoverflow.com/*) are allowed. This is called Same Origin Policy.

jQuery .getJSON Firefox 3 Syntax Error Undefined

I'm getting a syntax error (undefined line 1 test.js) in Firefox 3 when I run this code. The alert works properly (it displays 'work') but I have no idea why I am receiving the syntax error.
jQuery code:
$.getJSON("json/test.js", function(data) {
alert(data[0].test);
});
test.js:
[{"test": "work"}]
Any ideas? I'm working on this for a larger .js file but I've narrowed it down to this code. What's crazy is if I replace the local file with a remote path there is no syntax error (here's an example):
http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?
I found a solution to kick that error
$.ajaxSetup({'beforeSend': function(xhr){
if (xhr.overrideMimeType)
xhr.overrideMimeType("text/plain");
}
});
Now the explanation:
In firefox 3 (and I asume only firefox THREE) every file that has the mime-type of "text/xml" is parsed and syntax-checked. If you start your JSON with an "[" it will raise an Syntax Error, if it starts with "{" it's an "Malformed Error" (my translation for "nicht wohlgeformt").
If I access my json-file from an local script - no server is included in this progress - I have to override the mime-type... Maybe you set your MIME-Type for that very file wrong...
How ever, adding this little piece of code will save you from an error-message
Edit: In jquery 1.5.1 or higher, you can use the mimeType option to achieve the same effect. To set it as a default for all requests, use
$.ajaxSetup({ mimeType: "text/plain" });
You can also use it with $.ajax directly, i.e., your calls translates to
$.ajax({
url: "json/test.js",
dataType: "json",
mimeType: "textPlain",
success: function(data){
alert(data[0].test);
} });
getJSON may be insisting on at least one name:value pair.
A straight array ["item0","item1","Item2"] is valid JSON, but there's nothing to reference it with in the callback function for getJSON.
In this little array of Zip codes:
{"result":[["43001","ALEXANDRIA"],["43002","AMLIN"],["43003","ASHLEY"],["43004","BLACKLICK"],["43005","BLADENSBURG"],["43006","BRINKHAVEN"]]}
... I was stuck until I added the {"result": tag. Afterward I could reference it:
<script>
$.getJSON("temp_test_json.php","",
function(data) {
$.each(data.result, function(i, item) {
alert(item[0]+ " " + i);
if (i > 4 ) return false;
});
});
</script>
... I also found it was just easier to use $.each().
This may sound really really dumb, but change the file extension for test.js from .js to .txt. I had the same thing happen with perfectly valid JSON data files with pretty well any extension except .txt (example: .json, .i18n). Since I've changed the extension, I get the data and use it just fine.
Like I said, it may sound dumb but it worked for me.
HI
I have this same error when testing the web page on my local PC, but once it is up on the hosting server the error no longer happens. Sorry - I have no idea of the reason, but thought it may help someone else track down the reason
Try renaming "test.js" to "test.json", which is what Wikipedia says is the official extension for JSON files. Maybe it's being processed as Javascript at some point.
Have you tried disabling all the Firefox extensions?
I usually get some errors in the Firebug console that are caused by the extensions, not by the webs being visited.
Check if there's ; at the end of the test.js. jQuery executes eval("(" + data + ")") and semicolon would prevent Firefox from finding closing parenthesis. And there might be some other unseen characters that prevents it from doing so.
I can tell you why this remote location working though, it's because it's executed in completely different manner. Since it has jsoncallback=? as the part of query parameters, jQuery thinks of it as of JSONP and actually inserts it into the DOM inside <script> tags. Try use "json/test.js?callback=?" as target, it might help too.
What kind of webserver are you running that on? I once had an issue reading a JSON file on IIS because it wasn't defined as a valid MIME type.
Try configuring the content type of the .js file. Firefox expects it to be text/plain, apparently. You can do that as Peter Hoffmann does above, or you can set the content type header server side.
This might mean a server-side configuration change (like apache's mime.types file), or if the json is served from a script, setting the content-type header in the script.
Or at least that seems to have made the error go away for me.
I had a similar problem but was looping through a for loop. I think the problem might be that the index is out of bound.
Kien
For the people who don't use jQuery, you need to call the overrideMimeType method before sending the request:
var r = new XMLHttpRequest();
r.open("GET", filepath, true);
r.overrideMimeType("text/plain");

Categories