I am attempting to query my Google custom search engine in my Chrome extension, and parse the returned JSON.
My goal is to utilize the current tab URL in my request to the CSE, so I tried to adapt the sample code from the Image Search example that Google provides, since it is somewhat similar.
The code uses an XMLHTTPRequest to communicate with the custom search server:
var x = new XMLHttpRequest();
x.open('GET', searchUrl);
// The Google image search API responds with JSON, so let Chrome parse it.
x.responseType = 'json';
x.onload = function() {
// Parse and process the response from Google Image Search.
var response = x.response;
alert(response);
if (!response || !response.responseData || !response.responseData.results ||
response.responseData.results.length === 0) {
errorCallback('No response from Google Image search!');
return;
}
Whenever I try to view the response var, it is undefined. I tried changing the
var response = x.responseText;, but was unsuccessful.
My question is, what is the correct way to use javascript to parse and process the JSON data, while abiding by the Chrome Extension guidelines?
Any help or guidance would be much appreciated.
Thanks,
Blaine
I suppose you didn't add the permission request to the manifest. Try setting it like here. When it comes to parsing, use JSON.parse(x.response). Also make sure you call x.send() (I can't see it in your code) after the end of onload callback.
Hope it helps
See the error inside your request...
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState === XMLHttpRequest.DONE) {
if(xhr.status === 200) {
var responseText = JSON.parse(xhr.responseText);
// Do what you want with responseText
}
}
};
x.open('GET', searchUrl);
Related
I am a beginning programmer and trying to convert a program in Actionscript to javascript.
So far I could do all the conversions I needed, but I am stuck on the following code below.
I understand that the variables fileName & test ID are sent to the script which is located at the url interfaceUrl + "operation=" + Test and the answer is stored back in lvReply.
Which code/function I would need in JavaScript to do the same.
I am looking at XMLHttpRequest but do not know if this is the right way to move forward. Any help in pointing me to the right direction would be appreciated.
var lv:LoadVars = new LoadVars();
lv.fileName = fileName;
lv.lpTestId = testId;
var lvReply:LoadVars = new LoadVars();
lv.sendAndLoad(interfaceUrl + "operation=" + Test, lvReply, "POST");
LoadVars just loads name / value pairs from the server, in the form of:
someText=testing&myVariable=123
For JavaScript, you can use:
XHR:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
to load the data, and then:
URLSearchParams to parse them:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
Here is some pseudo code to demonstrate:
let xhr = new XMLHttpRequest();
//load data, sending params to server via query string
xhr.open('GET', 'http://example.com/data?args1=boof&arg2=banana');
xhr.onload = function() {
if (xhr.status != 200) {
//check status code to see what happened
} else {
//data sent from server in the form of foo=bar&biff=bam
let data = xhr.response;
let params = URLSearchParams(data);
let foo = params.get(foo);
console.log(foo); // prints bar
}
};
xhr.onerror = function(err) {
//something went wrong
};
xhr.send();
A better solution would be just to send JSON from the server and parse it with JSON.parse()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Note, in the example above, it is also sending data to the server. You can also do that using XHR (either via GET or POST).
I've never touched on JSON, but I just need some bits clearing up so that I can research how to solve my problem properly.
I have
-HTML file
-JS file
-JSON file.
All are linked in the html file.
My challenge is to load the JSON file and add together some of the values that are located within it.
So far I'm struggling to find anything other than JQuery to open it... I can find things about parsing, but many examples use code inline and i'm lost as to whether they're coding on the js file or the JSON one!
I'm seeing AJAX mentioned too, but i plead ignorance to its use so far (i'm very new to JS).
so, what would you recommend to load it?
what should i research to see about obtaining the values and creating additions with them?
Loading a JSON file:
jQuery:
$.getJSON('/my/url', function(data) {
console.log(data);
});
Non-jQuery:
request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400){
// Success!
var data = JSON.parse(request.responseText);
console.log(data);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
note the console.log prints the contents of the JSON file to the javascript console. You can do whatever you want with the "data" variable.
I've just started to learn how to use APIs, but I'm having a little bit of trouble understanding exactly how to utilize them.
I was able to write the following code thanks to some online documentation, but I have some questions about how to add to it:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml", false); xhr.send();
console.log(xhr);
Now, when I run this code in my browser and I open the console, I get a dropdown with a whole bunch of stuff under it. First of all, how can I get the code to display JUST the response? I want the console to display just the XML to show when I run my code. Second of all, how do I parse the XML? Is there any way to get a value from an XML element and assign it to a JavaScript variable?
Thanks!
What you are printing is the XMLHttpRequest object itself, while what you actually want is the response from the request you've made. To get the response, you use
xhr.responseXML;
Which is a object of the type document. (See the MDN docs).
To exhibit the code, you can just
console.log(xhr.responseXML);
But to actually work with the response, you'll probably want to do as Josh suggested, and request from the API a JSON-formatted response (instead of a XML-formatted one).
You will probably want to do that asyncronously, too (see this). The page has a more robust example. Let's adapt it to show London's temperature:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=json", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
var response = JSON.parse(xhr.responseText);
console.log("Temperature(K): " + response.main.temp);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
Being async means that the xhr.onLoad function will be executed as soon as the response is received. Thus all of your code will be executed sequentially, and only when the response is received the onLoad will be executed.
You can get the response as a Document object.
Using your code above, you can reference xhr.responseXML and use the Document documentation to learn how to grab what data you need.
That dropdown is probably your browser formatting the response object in an interactive way for you.
xmlDoc=xhr.responseXML; will give you the actual resulting text
Alternatively: you could request a JSON object to make working with the data much easier.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=json", false); xhr.send();
var data= JSON.parse(xhr.responseText); //data is now a javascript object full of the API data
Note how the url now reads mode=json now.
var photo = 'http://cs323230.vk.me/u172317140/d_5828c26f.jpg';
var upload_url = 'http://cs9458.vk.com/upload.php?act=do_add&mid=62..';
var xmlhttp = getXmlHttp();
var params = 'photo=' + encodeURIComponent(photo);
xmlhttp.open("POST", upload_url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
var answer2 = xmlhttp.responseText;
console.log(answer2);
alert(answer2);
}
}
};
xmlhttp.send(params);
I need to change the photo URL on the contents of the file
./DirectoryImage/imagetest.jpg
and send contents of the file
./DirectoryImage/imagetest.jpg
on upload_url.
But I don't know how send the contents of the file on upload_url in javascript...
Is it possible?
Does anyone know how make it?
Yes, you can, but it's not easy. The trick is using the FileReader object. Here's some sample code I put together for uploading an image after it's dropped into a <div>.
I'm pretty sure you can do the same with any file, as long as you can make the FileReader object from whatever your user inputs.
YourNamespace.uploadImg = function(evt) {
// Get the first file, if a stack of files has been dropped
// (to transfer the whole stack just repeat the process)
var file = evt.dataTransfer.files[0];
// Make a FileReader object
var reader = new FileReader();
// Build an AJAX request to send the file once the browser has received it.
// The FileReader will call this onload event when it's finished.
reader.onload = function(evtLoad) {
var req = new XMLHttpRequest();
req.open('POST', '/foo/bar.php', true);
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
alert("success");
}
};
// Encode the file stream properly, set the appropriate header, and send.
var params = "foo=bar&data=" + encodeURIComponent(evtLoad.target.result);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(params);
};
// This starts the whole process: read in the file as a data URL.
// When it's finished it calls the onload() that was defined above.
reader.readAsDataURL(file);
};
The MDN pages are very helpful on this whole topic, such as the FileReader object API.
Also I seem to remember browser support is poor for the usual suspects (IE6-7, etc).
It's worth mentioning that this is difficult because Javascript in browsers was not designed to talk to the server, for security purposes. Javascript is usually client-side only. File transfers and such should usually be handled with a server-side script in PHP, Perl, Ruby, etc.
I am trying to parse some json on an external site but I am having trouble. It must be with JavaScript or JQuery, as it is for a chrome extension. To get to the point:
I need to get the number from an external URL with the json {"_visitor_alertsUnread":"0"} and set the number returned to a variable. How do I go about doing this?
I have tried several things such as JSON.parse but it isn't working:(
In short: How do I get the number from this json, which is on an external site, and set it to a variable?
You cannot get data from an external URL (in a different domain) in Javascript unless the site supports JSONP or Cross-Origin Resource Sharing. If it does, then use XMLHttpRequest to get the data and JSON.parse() to read it.
Script:
var xhr = new XMLHttpRequest();
xhr.open( 'GET', 'example.com/json', true );
xhr.onload = function () {
var unread = window.JSON.parse( xhr.responseText )._visitor_alertsUnread;
};
xhr.onerror = function () {
//process error
};
xhr.send();
Try this with http://api.jquery.com/jQuery.getJSON/
$.getJSON('your_url', function (jsonobj) {
var unread;
unread = jsonobj._visitor_alertsUnread;
});