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;
});
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 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);
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.
Is there a method in javascript to load a page without actually show that page?
I want to load a php page which will handle the database insertion tasks.
Use AJAX to get/send data to the serverside?
Yes there is, you can use the XMLHttpRequest for this.
here is a example
function done() {
console.log(this.responseText); // The response from the server
};
var XHR = new XMLHttpRequest();
XHR.onload = done; // Set the onload function
XHR.open("get", "something.php", true); // Type & File
XHR.send(); // Send the request
Here is some documentation on that MDN XMLHttpRequest
On an html page I have an <object> that hosts a pdf.
I would need to access the binary data of the pdf via Javascript, but I cannot figure out how
to accomplish that. I get access to the object element itself but cannot think of a method for getting the data in it.
Is it possible at all?
You can not get the binary from an object tag, but you can make an AJAX request to the server and get it as ArrayBuffer by using the new responseType attribute:
var http = new XMLHttpRequest();
http.open("get", "somefile.pdf", true);
http.responseType = "arraybuffer";
http.onload = function(e)
{
if(http.response)
{
// http.response contains the file
}
};
http.send(null);
Note that this method only works in newer browsers and is obviously restricted by the Same-Origin-Policy.