Not able to parse JSON file in JavaScript - json

I am using JavaScript to Parse the JSON file. But I am not able understand the error I am getting. Could anybody please help me on this topic.
**My Code:
Html file:
<title>JSON Parser</title>
<script type="text/javascript">
function webGLStart() {
var request = new XMLHttpRequest();
request.open("GET","test.json");
var my_JSON_object = JSON.parse(request.responseText);
alert (my_JSON_object.result[0]);
}
</script>
</head>
<body onload="webGLStart();">
</body>
</html>
test.json File:
{"result": [0,1,2,3,4] }
alert in above code does not show anything on the webpage.

It's straight forward with jQuery:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$.getJSON('test.json', function(data) {
$.each(data, function(key, val) {
console.log("key=" + key + " " + "val=" + val);
});
});
For more sample code look here: http://api.jquery.com/jQuery.getJSON/

Your code for making the Ajax request is not correct.
First, var request = new XMLHttpRequest(); will not work incase of IE 5, 6; i.e. you need to make cross-browser object of XMLHttp
Second, request.open("GET","test.json"); does not indicate this request to be asynchronous... i.e. you are missing the third boolean parameter (true / false)
Thirdly, you are not sending the request to the web server using:
request.send(null);
Try following link for Ajax:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
Try this link for Parsing JSON using Javascript:
http://json.org/js.html
Hope this helps.

Ajax is asynchronous. You are trying to read the response before it has arrived from the server. Oh, worse than that. You are opening the request but never actually sending it.
You need to use an event handler onreadystate change to run the code once the response has arrived, and you need to send the request to the server before you can get a response. There is a decent guide to using XHR here.

Related

Delay ajax GET function helps in this case?

I am using the following to save the html of a certain website in a string
function loadajax(dname) {
$.ajaxSetup({async: false});
$.get('https://www.example/?param=param1', function(response) {
var logfile = response;
//alert(logfile);
});
}
The problem is that in the html code there are some codes like {{sample}} which seems that there a not loaded yet when the Ajax call is getting the code. When I perform the operations manually I can clearly see HTML code instead of the " {{ }}'s ".
I have already tried {async: false}...

How to make Web page to not wait for a response after sending a GET request

I am trying to make this web site that resides in Google Drive control a LED(on/off) via esp8266 and arduino. Partially i've succeded in doing what i want by sending to the IP of the module that communicates with the arduino a GET request witch parses it and acts accordingly. ie GET /?LED1=on HTTP/1.1
Problem is that whenever i press a button in the web site it sends the GET request and then it waits for a response from the other end (arduino),and the browser keeps loading until eather I close the connection from the arduino or I reply something like HTTP/1.1 200 OK and then close the conection.
In the first case browser shows the message that was unable to load the page and in second case it simply shows a blank page.
<DOCTYPE html>
<html>
<head>
<title>LED Control</title>
</head>
<body>
<button>LED 1 On</button>
</body>
</html>
I just want to send that LED1=on string somehow without causing the page attempt to load anything back.
A reusable solution
Modify your HTML to be something like this:
<button class="get" data-url="http://78.87.xxx.xx:333/?LED1=on">LED 1 On</button>
Now add this JavaScript:
window.onload = function () {
Array.prototype.forEach.call(document.querySelectorAll('.get'), function(el) {
el.onclick = function () {
// Use this trick to perform CORS requests too
var req = new Image();
req.src = this.dataset.url;
// The following 7 lines are completely optional
req.onload = function () {
// Was successful
};
req.onerror = function (error) {
// Encountered an error
alert('An error occurred while performing the request. + ' error);
};
};
});
};
Now any element with the class "get" when clicked, will send a request to the URL. This won't change the page either. If

Get request within page

I've been looking around, but I'm not quite sure what to search for...
I want to have a webpage send a Get request to a python script when you first open the page, maybe with the option to refresh it with a button. Is there a way to send a request ("script.py?var=test") and display the results within the page?
What I tried to use earlier: (didn't work..)
Am I doing something stupid? I don't know anything about JavaScript
<p>Highscores:</p>
<p id='scores'>text</p>
<input type='button' onclick='changeText()' value='Change Text'/>
<script type="text/javascript">
function changeText(){
var request = new XMLHttpRequest();
request.open("GET", "../../cgi-bin/highScore.py?scoreMethod=load&game=ulama", true)
request.onreadystatechange = function(){
var done = 4, ok = 200;
if (request.readyState == done && requeset.status == ok){
document.getElementById('scores').innerHTML = request.responseText;
}
};
request.send();
}
</script>
Also, should I have the python script return a full page with the header and all? or just the relevant section?
Use a Jquery call in this case to clean up your code a little bit.
Also in this case you should use a post because of the nature of your 'beast' :)
function changeText(){
$.ajax({
method : "POST",
URL : "../../cgi-bin/highScore.py",
data : {
"scoreMethod" : "load",
"game" : "ulama"
},
success : function(data) {
$("#scores").html(data);
}
});
}
I'd also look into JSON and jquery being returned as its probaly going to be easier in the long term (Though ive never played with python.
why not using jquery for doing this?
$('#scores').load('../../cgi-bin/highScore.py?scoreMethod=load&game=ulama', function(responseText, textStatus) {
alert(textStatus);//check here whether textStatus equals 'success' or something else (maybe an error)
});

JSON and passing a URL value as a parameter - Chrome Extension

Ok, this is my final tango with this. Below I've listed the code. I'm able to get the value of the url and display it on screen for the current (active tab) in Google Chrome. Now all I have to do is pass that value as a parameter in the URL via JSON. My processing file resides on a our remote server - in php. Everything I've done with respect to this has worked to perfection. However, any attempts to pass the current url or any url as one of the parameters - e.g. ?format=json&url=http://something.com&callback=? - results in nothing. I'm not sure if what I'm doing is wrong or if it is even possible. The important thing to note is that all we are looking to do is pass the url to a remote server for storage, processing etc and send back results. I have everything working but I just can't seem to get the url to pass as a parameter.
<html>
<head>
<title>API JSON Test</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script>
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentLink').innerHTML = tab.url;
});
}
</script>
<script type="text/javascript">
$(document).ready(function(){
var timeService =
"http://api.ulore.com/api2.php?key=abce&url="+tab.url+"&format=json&callback=?";
$.getJSON(timeService, function(data) {
$('#showdata').html("<p>url_results="+data.post.url+"</p>");
});
});
</script>
<div id="showdata"></div>
</head>
<body>
</body>
</html>
Again, all the JSON works fine when I'm testing other code. Even if I put in a NON-URL value as a parameter for url=..... it throws the appropriate error. However, it will not accept a URL for some reason.
Any feedback will be greatly appreciated.
Thanks,
Ethan-Anthony
Try encoding and decoding the url.
http://www.w3schools.com/tags/ref_urlencode.asp
http://php.net/manual/en/function.rawurlencode.php
http://phpjs.org/functions/rawurlencode:501

Using jQuery.getJSON in Chrome Extension

I need to do a cross-domain request in a chrome extension. I know I can it via message passing but I'd rather stick to just jQuery idioms (so my javascript can also work as a <script src="">).
I do the normal:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data) {
console.log(data);
});
but in the error console I see:
Uncaught ReferenceError: jsonp1271044791817 is not defined
Is jQuery not inserting the callback function correctly into the document? What can I do to make this work?
(If I paste the code into a chrome console, it works fine, but if I put it as the page.js in an extension is when the problem appears.)
Alas, none of these worked, so I ended up doing the communication via the background.html.
background.html
<script src="http://code.jquery.com/jquery-1.4.2.js"></script>
<script>
function onRequest(request, sender, callback) {
if (request.action == 'getJSON') {
$.getJSON(request.url, callback);
}
}
chrome.extension.onRequest.addListener(onRequest);
</script>
javascripts/page.js
chrome_getJSON = function(url, callback) {
console.log("sending RPC");
chrome.extension.sendRequest({action:'getJSON',url:url}, callback);
}
$(function(){
// use chrome_getJSON instead of $.getJSON
});
If you specify "api.flickr.com" in your manifest.json file you will not need to use the JSONP callback, script injection style of cross domain request.
For example:
"permissions": ["http://api.flickr.com"],
This should work beautifully in you code. I would remove the querystring parameter "&jsoncallback" as there is no JSONP work needed.
The reason why your current code is not working is your code is injecting into pages DOM, content scripts have access to the DOM but no access to javascript context, so there is no method to call on callback.
My impressions it that this fails because the jQuery callback function is being created within the 'isolated world' of the Chrome extension and is inaccessible when the response comes back:
http://code.google.com/chrome/extensions/content_scripts.html#execution-environment
I'm using Prototype and jQuery for various reasons, but my quick fix should be easy to parse:
// Add the callback function to the page
s = new Element('script').update("function boom(e){console.log(e);}");
$$('body')[0].insert(s);
// Tell jQuery which method to call in the response
function shrink_link(oldLink, callback){
jQuery.ajax({
type: "POST",
url: "http://api.awe.sm/url.json",
data: {
v: 3,
url: oldLink,
key: "5c8b1a212434c2153c2f2c2f2c765a36140add243bf6eae876345f8fd11045d9",
tool: "mKU7uN",
channel: "twitter"
},
dataType: "jsonp",
jsonpCallback: callback
});
}
// And make it so.
shrink_link('http://www.google.com', "boom");
Alternatively you can try using the extension XHR capability:
http://code.google.com/chrome/extensions/xhr.html
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.example.com/data.json", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// JSON.parse does not evaluate the attacker's scripts.
var resp = JSON.parse(xhr.responseText);
}
}
xhr.send();
The syntax is a little off. There's no need for the callback( bit. This works flawlessly. Tested in the javascript console of Chrome on this StackOverflow page (which includes jQuery):
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data) {
console.log(data);
});
As many of you will know, Google Chrome doesn't support any of the handy GM_ functions at the moment.
As such, it is impossible to do cross site AJAX requests due to various sandbox restrictions (even using great tools like James Padolsey's Cross Domain Request Script)
I needed a way for users to know when my Greasemonkey script had been updated in Chrome (since Chrome doesn't do that either...). I came up with a solution which is documented here (and in use in my Lighthouse++ script) and worth a read for those of you wanting to version check your scripts:
http://blog.bandit.co.nz/post/1048347342/version-check-chrome-greasemonkey-script