Json problem in fetching data - javascript

<script>
function jsonfunc(){
var data ="publick="+document.getElementById("publickeyval").value+"&privatek="+document.getElementById("privatekeyval").value;
var url="http://www.remoteapiserver.com/example_api/example_adcpatchaapi.php?"+data;
alert(url);
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
http_request.open( "GET", url, true );
http_request.onreadystatechange = function () {
if (http_request.readyState == 4){
alert(http_request.responseText+"#"); // showing only # //
my_JSON_object = JSON.parse( http_request.responseText );
}
};
http_request.send(null);
}
</script>
I was as asked my question as per comment i read Json and writing above code in my php page.But still this is giving problem.I am not getting fetched dada from remote server.I am getting only "#" in alert box.

I highly recommend a JavaScript Framework like jQuery for this kind of stuff. It definitely makes this a lot easier. jQuery lets you do cross-domain requests, if you use JSONP (take a look at the docs). The code would look something like this:
$.getJSON(yourUrlGoesHere, function(data) { // ready callback
// data is an object; no need to parse it manually.
});

Sometimes it't better use some library:
JQuery or Moootools: http://mootools.net/docs/core/Request/Request.JSON
Implement this in native JS is difficulty if we want use it in all browsers ;)

Related

How to receive data from XMLHttpRequest in chome extension via javascript?

I wanna to send request form a webpage to chrome extension, and then in chrome extenison receive data and read data, is there any way to this?
Ex:
In doman www.nope.com/sendRequest.html will sent data to chrome extension via url chrome-extension://xxxxxxx/getData.htm?isToken=abc, and then extension will receive and can read data "isToken".
Here is my code in sendRequest.html
<script type="text/javascript">
function sendRequest() {
document.write("Sending request");
var req = new XMLHttpRequest();
req.open("POST", "chrome-extension://xxxxxxxxxx/getData.htm?isToken=abc", true);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
alert(req.responseText);
document.write("OK");
}
}
};
req.send();
}
</script>
And in chrome extension file getData.htm, how can I get data?
(Edit: what type of data are you sending? Could you pass it through as a JSON encoded string, via GET? JSON.stringify() and JSON.parse() may be of use to you. :)
The following may be useful as a guide for accessing that POST/GET data. :) )
As far as I am aware, this is best done using some form of server side scripting. You could use window.location.search in JS, and split the string and perform the necessary functions, but I think server-side scripting may work best. :)
An example of a JS implementation could be as follows:
var url = window.location.search;
var params = url.substr(url.IndexOf("?") - 1, 30);
This would grab the parameters (starting at ? (inclusive), and continue for 30 chars. You could also use something like var params = url.substr(url.IndexOf("?") - 1, url.length); to get the whole parameters list.
How you use this from then on, is up to you, but you could pass it through a switch() or whatever you need. :)
Obviously, this being a chrome extension would limit your options regarding any server-side processing. :/
Edit: The above would go in getData.htm. :)

How can I set the Accept Header for a link on a web page?

This is mostly an ivory tower question, since I can easily just make a new URL endpoint. But basically, I'd like to be able to serve up CSV when the user has the Accept header configured to include text/csv. That's trivial on the server side, but on the client side I don't know how to set the Accept header unless I'm using XHR or some other "non-browser" client. Is there a way in HTML to set the Accept header in a link or in JS to set the Accept header when using window.location?
I figure I might as well put this here for the next thousand people looking at the post. You cannot do it.
Update:
I will leave my original answer below for posterity, but I now see that I didn't really answer the question. There isn't a way to do this "natively", the best approach I can think of would be to use a data uri (http://en.wikipedia.org/wiki/Data_URI_scheme) and have AJAX do the work for you:
// aware that you didn't mention jQuery, but you can do this with or without
var download = function(){
var mime = this.getAttribute('data-mime-type');
$.ajax({
accepts: mime,
success: function(data){
var uri = 'data:'+mime+';charset=UTF-8,' + encodeURIComponent(data);
window.location = uri;
}
})
return false;
}
With the same idea used in the example below:
Download CSV
document.querySelectorAll('a[data-mime-type]').onclick = download;
Original Answer
There is no built-in way to force an 'Accept' header on a link (via HTML or Javascript). I think you could pull this off fairly easily using a very small amount of server & client-side code though. Should be easy in any language, my example is PHP:
function get_accepted_headers() {
$headers = apache_request_headers();
if(array_key_exists('Accept', $headers)) {
$accepted = explode(',', $headers['Accept']);
return $accepted;
}
return array();
}
Add a data-accept attribute to your download links:
Download CSV
Then attach a click event handler to ensure that the user accepts the specified content type:
// will end up with something like: ["text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"]
var user_headers = <?=stripslashes(json_encode(get_accepted_headers()))?>;
var click_header_check = function() {
var accept = this.getAttribute('data-accept');
if(user_headers.indexOf(accept) == -1) {
console.log('User does not explicitly accept content-type: %s', accept);
return false;
}
window.location = this.href;
return;
}
// attach the event listener
document.querySelector('a[data-accept]').onclick = click_header_check;
Not sure if this is what you were looking for, but hope that it helps.
For those still interested, there is a way to do this in pure javascript.
The following code uses JQuery (https://jquery.com/) and FileSaver.js (http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js) though you could write the respective parts yourself:
//in case of non binary data use:
var type = 'text/xml';
var url = 'http://your_url_here/'
$.ajax({accepts:{text:type},
url:url,
processData:false,
dataType:'text',
success:function(data){
saveAs(new Blob([data], {type: type}),'filename.txt');
},
error: function(){
// Handle errors here
}
});

Calling a website and getting JSON information back

I am not too experienced in javascript on using API's and how to call websites and get information back. I have done this before in Java using HTTP objects and more. I am attempting to make an application where a user can type in a company stock name such as APPL and get back a ton of data like gains, losses, changes, etc. This shouldn't be that hard. I have a html/javascript file with an input textbox for the stock name. This part is easy. But after I tack on the stock name to the end of the URL by concatenation I don't know how to make the call and get the JSON information. There are examples of how to do this in other languages in the web page I am using but not for javascript. I am using this link as a tutorial:
http://digitalpbk.com/stock/google-finance-get-stock-quote-realtime
Here is my javascript code so far: Again this is probably really simple to do. Any help on this would be greatly appreciated and is good to know in the future.
script type="text/javascript">
var submitButton = document.getElementById("submitButton");
submitButton.addEventListener('click', actionPerformed, false);
function actionPerformed(e)
{
var textValue = document.getElementById("stockTextBox").value;
var urlEncoded = "http://finance.google.com/finance/info?client=ig&q=NASDAQ:" + textValue.toString();
for (var i = 0, len = urlEncoded.length; i < len; ++i) {
var object = urlEncoded[i];
confirm(object.toString());
}
}
</script>
I just found the following code for using HTTP GET and tried it out but nothing happens when I click the submit button. Any suggestions on what to do or what's wrong???
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
Wow, this is turning out to be a lot more work then I had anticipated. Here is the URL string I am using in my code for yahoo finance. I can navigate to it in the browser and it works like a charm. For the life of me I cannot understand why this isn't working.
var urlEncoded = "http://www.finance.yahoo.com/webservice/v1/symbols/" + textValue.toString() + "/quote?format=json";
You could try jQuery, google and download it.
It's a javascript framework that makes things allot simpler .
$.get( "http://yourur.com/file.php?parameter1=value1&parameter2=value2", function( data ) {
//data now contains whatever it loaded from server
console.log("Loaded from server :", data);
}, "json");

Get Raw Gist File [duplicate]

This question already has answers here:
Pull in JSON data
(3 answers)
Closed 6 years ago.
What I want is simple. Is there any way (including a work around) to make this work?
function loadXMLDoc() {
var request = new XMLHttpRequest();
var gistRawFileUrl = 'https://gist.github.com/kentcdodds/5822336/raw/6ef128c8c8d6fe416782d969efa95d36e0acf374/KentsBlog.md';
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var gistFileContent = request.responseText;
doSomethingCool(gistFileContent);
}
};
request.open('GET', gistRawFileUrl, true);
request.send();
}
Right now, if I execute this in the console here I'm getting:
XMLHttpRequest cannot load https://gist.github.com/kentcdodds/5822336/raw/6ef128c8c8d6fe416782d969efa95d36e0acf374/KentsBlog.md. Origin http://stackoverflow.com is not allowed by Access-Control-Allow-Origin.
This makes sense, and I know I'm not going to get GitHub to open up their access control, but if there's a work around to this or if I'm doing something wrong that would be great.
I realize that you can get the content of the file, by hitting the JSONP endpoint, but that doesn't give you the newline characters, so what was once this:
Hello World!
You
Rock!
Is now this:
Hello World!YouRock!
Thanks in advance.
Edit The problem with the newlines is something I need to fix on my end, not a Gist thing.
Check out this answer: https://stackoverflow.com/a/10454873/240963
API endpoint will give you content of each file within the Gist, including the formatting. The only downside is that you need to transfer extra data even if you already know the URL for the raw file.
We can simplify the code from the original answer, since you don't want to parse JSON and you probably know the filename:
$.ajax({
url: 'https://api.github.com/gists/'+gistid,
type: 'GET',
dataType: 'jsonp'
}).success( function(gistdata) {
var content = gistdata.data.files[filename].content;
DoSomethingWith(content)
}).error( function(e) {
// ajax error
});
JSFiddle
Using JSONP with raw XHR is a bit more complicated, but you could use something lighter than jQuery.

jquery.get(url) synchronization

OS X 10.6.8, Chrome 15.0.874.121
I'm experiencing an issue with javascript/jquery: I want to download a header file from base url, then add some more text to it and than spit it out to the client. I'm using the following code:
var bb = new window.WebKitBlobBuilder;
$.get('js/header.txt', function(data) {
bb.append(data);
console.log("finished reading file");
});
console.log("just before getting the blog");
var blob = bb.getBlob('text/plain');
// append some more
saveAs(blob,"name.dxf");
But that fails because getting the file is only finished way after the saveAs(blob) is executed. I know I can fix it with:
var bb = new window.WebKitBlobBuilder;
$.get('js/header.txt', function(data) {
bb.append(data);
//append some more
var blob = bb.getBlob('text/plain');
saveAs(blob,"name.dxf");
});
But that does not really look attractive: I only want to use the get statement only to append the header to the blob, and if I want to read a footer from the file system, I have to do a get inside a get, and spit out the blob in the inner get
Are there alternative ways to withhold the code after the get statement from executing until the whole file has been successfully loaded?
No.*
But, if you want it to look more attractive, try to describe semantically what you are trying to achieve and then write functions accordingly. Maybe:
function loadBlob (loadHeader, loadBody) {
loadHeader(loadBody);
}
loadBlob(function (oncomplete) {
$.get("js/header.txt", function(data) {
bb.append(data);
oncomplete();
});
}, function () {
var blob = bb.getBlob('text/plain');
// append some more
saveAs(blob,"name.dxf");
});
I don't know, is that more attractive? Personally, I find the original just fine, so maybe mine isn't any better, but the point is to use sematics.
* You could use setTimeout to poll and see if the response has been received. That's technically an alternative, but certainly not more attractive, is it?

Categories

Resources