How to read JSON data from url - javascript

Snapped code returns data from url in JSON format, how to create function to read data returned by this code in JQuery ?
var RealDataApi = function () {
var url_getgatedata = "api/realdata/getgatedata";
return {
getGateData: function (done, fail, always) {
var jqxhr = $.get(url_getgatedata);
jqXhrHandler(jqxhr, done, fail, always);
},

You can take the headers or parameters in the URL and by using postman you can get the JSON.
Some of the headers will be encrypted in the URL.

Related

How can I get JavaScript to parse a parse and pass it in an API call

I have an API which I'd like to call through client-side JavaScript. I need to parse a URL parameter ref which then needs to be passed to the API call. For example:
I visit this page www.example.com?ref=123, JavaScript parses ref and passes it to /api/v1.0/add?ref=123 and sends the request.
How can i do this?
Edit - Other answers show parsing the URL not making the API call.
You can do something like this:
var url_string = "http://www.example.com?ref=123";
var url = new URL(url_string);
var ref = url.searchParams.get("ref");
var urlGet = '/api/v1.0/add?ref=' + ref
$.get( urlGet , function( data ) {
});
André
For that you may use .get() function, as follows:
var input = 123;
var url = "/api/v1.0/add?ref="+input;
$.get( url, function( data ) {
// data is the return value, if any. You may use this return value, data, over here
});

Javascript parse json from URL

Trying to parse a json response from URL in javascript.
Here is what the response looks like
{"data":[{"version":"7.4.0","startDate":"2016-12- 12","totalSessions":"6208723","totalCrashes":"2944","crashRate":"0.047"},{"version":"7.4.0","startDate":"2016-12-11","totalSessions":"4979676","totalCrashes":"2378","crashRate":"0.048"},{"version":"7.4.0","startDate":"2016-12-10","totalSessions":"534913","totalCrashes":"208","crashRate":"0.039"},{"version":"7.4.0","startDate":"2016-12-09","totalSessions":"309564","totalCrashes":"147","crashRate":"0.047"},{"version":"7.4.0","startDate":"2016-12-08","totalSessions":"255597","totalCrashes":"162","crashRate":"0.063"},{"version":"7.4.0","startDate":"2016-12-07","totalSessions":"21379","totalCrashes":"12","crashRate":"0.056"}]}
I can dump the json output using
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
$('#show-list').html(data2); //shows json
});
Then I tried to parse it using
document.getElementById("placeholder").innerHTML=data2.data[0].version
also tried
obj = JSON.parse(crash);
console.log(obj.data2[0].version);
But no luck.
You should tell jQuery that the AJAX function returns JSON, then it will parse it automatically for you.
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
$("#placeholder").text(data2.data[0].version);
}, 'json');
Or you can call JSON.parse() yourself.
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
var data = JSON.parse(data2);
$("#placeholder").text(data.data[0].version);
});

Can't create and pass jsonp data

I am new to Node.js and I have created a method that should asynchronously fetch jsonp data via ajax and display the retrieved content in a graph. This method works fine when the url points to a static js file (in this case productsData.js) containing jsonp data:
function loadChart(destElementId, alertId) {
$.ajax({
url:'http://localhost:3000/products/data/productsData.js',
type: "GET",
data: {prodId: prodId},
jsonp: true,
dataType : 'json',
jsonpCallback: "jsonpCallback"
});
window["jsonpCallback"] = function(data) {
populateData(data, destId);
}
}
As in normal applications, I want to pass real data fetched via an external web service. I have created the following js file (data-client.js) that retrieves data from a specific web service. When calls are browser-based, the data is fetched successfully as a normal json and is displayed accordingly in the browser.
var express = require('express');
var router = express.Router();
var http = require('http');
var yaml_config = require('node-yaml-config');
var config = yaml_config.load(__dirname + '/../config/app-config.yml');
router.get('/data/:id', function (req, res, next) {
var opts = {
host: config.alertService.host,
port: config.alertService.port,
method: 'GET',
path: '/DataService/rest/receiveData/' + req.params.id
}
var reqGet = http.request(opts, function (dataResponse) {
var responseString = '';
dataResponse.on('data', function (data) {
responseString += data;
});
var response = {x:[],y:[],z:[],t:[]};
dataResponse.on('end', function () {
var responseObject = JSON.parse(responseString);
var accs = responseObject.data.listPCS;
for(var i in accs){
response.x.push(accs[i].accX);
response.z.push(accs[i].accY);
response.y.push(accs[i].accZ);
response.t.push(accs[i].timestamp);
}
res.json(response);
});
});
reqGet.end();
reqGet.on('error', function (e) {
console.error(e);
});
});
module.exports = router;
The first step for using live jsonp data is to replace the previous url value with:
url: 'http://localhost:3000/products/data/'+productId,
The second step is to replace in the data-client.js:
res.json(response);
with:
res.jsonp('jsonpCallback('+ JSON.stringify(response) + ');');
Somehow the data is not fetched. When I try to get the data via the browser (i.e. by entering http://localhost:3000/data/ID937) however I get the following result:
"jsonpCallback({\"x\":[1,1,1],\"y\":[2,1,4],\"z\":[0,0,9],\"t\":[1462790772000,1462790772010,1462790772020]});"
Can someone please tell me where the problem may be? I would be very thankful.
It looks like you are using Express.
jsonp() expects to be passed your raw data, not a string containing the complete response. It also expects to read the callback name from the query string, which jQuery will generate for you if you let it.
So the first thing to do is to fix your client side code so it passes the callback name correctly
On the client
$.ajax({
url: 'http://localhost:3000/products/data/' + productId,
dataType: 'jsonp',
}).done(function(data) {
populateData(data, destId);
});
The changes here are:
GET is the default (and, for JSONP, only option) so there is no need to specify the type.
You are passing the data as a URL path part, not a query string. Drop the data property that you aren't using.
The jsonp property is used to override the callback name. That's harmful, don't do that (likewise, don't specify jsonpCallback). jQuery will generate one for you and add it to the query string.
If you are dealing in JSONP then specify that as the data type, not JSON.
Don't create your own global manually. Pass your function to done and let jQuery make it a global (with a generated name to match the callback).
On the server
Just pass the data structure you want to send back to jsonp().
res.jsonp(response);
The callback name will be read from the query string by Express.

Addon firefox php request

i'm trying to develop Firefox extension
problem :
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = response.json;
}
});
I want to use this request function to parse json to an array (List here) from php file.
The php my php file echo json form correctly, but I can't transform the data into javascript array to be able to use it in my addon.
if there is a better idea than using this function to do it please tell me :)
try this: MDN - JSON Object
JSON.parse and JSON.stringify
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = JSON.parse(response.json);
}
});
it's very important to use double quotes.
If you are having a problem with JSON.parse. Copy your array to scratchpad and then run JSON.stringify on it and then make sure your php file matches the strignified result.
if Addon-SDK doesnt have JSON then you gotta require the module if there is one. If there isn't one than require('chrome') and grab the component HERE
There's a bug in Noitidarts code.
why JSON.parse the request.json? If you want to parse do it on request.text
However no need to json.parse as the request module tries to parse and if successful retuns request.json
see here:
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
so the likely problem is that your php is not outputting a json string that json.parse can read. make sure to use ". figure out what your php file should return by running json.stringify on a dummy object. ie:
var obj = {myarr:[1,8,9,7,89,0,'ji'],strr:'khhkjh',anothrtObj:{1:45,56:8}};
alert(JSON.stringify(obj)) //{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
so now in your php make sure your outputted text mateches this format
{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
if your php outputs something like below JSON.parse will fail on it so request.json will be null
{myarr:[1,8,9,7,89,0,"ji"],strr:"khhkjh",anothrtObj:{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,"ji"],'strr':"khhkjh",'anothrtObj':{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,'ji'],'strr':'khhkjh','anothrtObj':{'1':45,'56':8}}

How to store the ajax response in browser cache with jquery

I'm trying to store the ajax response in browser cache. I know to store it for only url like (example.com), but want to store the data which having url like (example.com?xyz=abc%20efg&mno=hjk).
My code :
beforeSend: function () {
var addC=url; // I want to add data also with this url
console.log(addC);
if (localCache.exist(addC)) {
printRes(localCache.get(url));
console.log("cached values");
return false;
}
return true;
},
And
var localCache = {
data: {},
remove: function (url) {
delete localCache.data[url];
},
exist: function (url) {
return localCache.data.hasOwnProperty(url) && localCache.data[url] !== null;
},
get: function (url) {
console.log('Getting in cache for url' + url);
return localCache.data[url];
},
set: function (url, cachedData, callback) {
localCache.remove(url);
localCache.data[url] = cachedData;
if ($.isFunction(callback)) callback(cachedData);
}
};
Please anyone help me to solve this.
By reading the docs from
MDN i Think you are doing wrong. If you want to cache ajax response CACHE property to true
in your ajax call ,also see to it that you provide proper cache expiration header from server.
Also
[from MDN]
Never access cached files by using traditional GET parameters (like other-cached-
page.html?parameterName=value). This will make the browser bypass the cache and attempt to get
it from network. To link to cached resources that have parameters parsed in JavaScript use
parameters in the hash part of the link, such as other-cached-page.html#whatever?parameterName=value.
if you are looking for local storage[key value storage]
globalStorage['cache_1'].setItem("key",data);

Categories

Resources