How to preload JSON link? - javascript

I've got a function that needs to call a link (JSON format), the fact is that I would like to be able to preload this link to smooth and reduce the operation time when calling the function.
onSelectionChanged: function (selectedItems) {
selectedItems.selectedRowsData.forEach(function(data) {
if(data) {
colorMe(data.target)
}
});
}
function colorMe(item){
globalItem = item;
request('http://blablabla/?format=json',findMaterial);
};
function findMaterial(data){
jq310.each(data, function(table) {
if (data[table].identifier == globalItem){
globalData = data[table]
request('http://another-blablabla/?format=json',findMatchArea);
};
});
};
function findMatchArea(areas){
jq310.each(areas, function(area) {
blablabla
The request function that I built just look if the link as been already called, so it's reloading it if true. And also send data from the link to the called function.

If you'r looking to load a static json file you should concider loading it on the top of your file. To do so you should store the datas in a global variable like that :
let datas;
request('http://blablabla/?format=json', (data) => {
datas = data
});
onSelectionChanged: function (selectedItems) {
selectedItems.selectedRowsData.forEach(function(data) {
if(data) {
globalItem = data.target;
findMaterial();
}
});
}
function colorMe(item){
globalItem = item;
};
function findMaterial(){
const data = datas;
jq310.each(data, function(table) {
if (data[table].identifier == globalItem){
globalData = data[table]
request('http://another-blablabla/?format=json',findMatchArea);
};
});
};

I finally found a way to do it properly, here it is :
var mylink = 'https://fr.wikipedia.org/wiki/JavaScript';
function preloadURL(link){
var xhReq = new XMLHttpRequest();
xhReq.open("GET", link, false);
xhReq.send(null);
var jsonObject = JSON.parse(xhReq.responseText);
return jsonObject;
};
jsonObjectInv = preloadURL(mylink);
And I just point to my json variable to parse it (really faster)
function colorMe(item){
globalItem = item;
findMaterial(jsonObjectInv);
};
Problem solved

Related

Initialize variable after ajax callback

I'm looking for a way to initialize a var after an ajax call. The problem is that the ajax call is in an another file.
Here is my code :
file1.js
$(document).ready(function () {
getKanbans();
});
function getKanbans() {
var kanbans = RequestSender.getKanbans();
console.log(kanbans); // print undefined
}
RequestSender.js
class RequestSender {
static getKanbans() {
$.ajax({
url: './ajax/select_kanbans.php',
type: 'GET',
success: RequestSender.initKanbanList
});
}
static initKanbanList(data) {
var result = JSON.parse(data);
var kanbans = [];
for (var i = 0; i < result.kanbans.length; ++i) {
var currentKanban = result.kanbans[i];
kanbans.push(new Kanban(currentKanban['Name'], currentKanban['Status']))
}
console.log(kanbans); // correctly displayed
return kanbans;
}
}
I just use jQuery, all my files are included. I think that the problem come from the fact that ajax is async but I don't know how to fix that.
in your example ajax call started but kanbans still undefined
function getKanbans() {
//ajax call started but kanbans still undefined
var kanbans = RequestSender.getKanbans();
console.log(kanbans); // print undefined
}
so you should complete execution after ajax call finished you can do that with the help of promises
for more information Check this
function getKanbans(url) {
var promiseObj = new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("xhr done successfully");
var response = xhr.responseText;
var responseJson = initKanbanList(response);
resolve(responseJson);
} else {
reject(xhr.status);
console.log("xhr failed");
}
} else {
console.log("xhr processing going on");
}
}
console.log("request sent succesfully");
});
return promiseObj;
}
function initKanbanList(data) {
var result = JSON.parse(data);
var kanbans = [];
for (var i = 0; i < result.kanbans.length; ++i) {
var currentKanban = result.kanbans[i];
kanbans.push(new Kanban(currentKanban['Name'], currentKanban['Status']))
}
console.log(kanbans); // correctly displayed
return kanbans;
}
$(document).ready(function () {
// to call it
getKanbans('./ajax/select_kanbans.php').then(function (kanbans) {
console.log(kanbans);
}, function (error) {
console.log(error);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This is called modules in javascript. You can implement them using link tags directly. But you are much better served by libraries like RequireJS and others. Then you can do things like:
require(['./RequestSender'], function (RequestSender) {
var rs = new RequestSender();
... //whatever
});
Here is a good SO question that explains modules well: How do I include a JavaScript file in another JavaScript file?

Function needs to return Rest Call response as JSON object. How to set the response to a variable so that it can be return as variable

var Client = require('node-rest-client').Client;
var client = new Client();
module.exports = {
getWeatherStatus: function() {
var messageData = "";
client.get("http://api.openweathermap.org/data/2.5/weather?q=Pune&appid=123234234234243242", function (data, response) {
console.log(JSON.parse(data));
messageData=data;
});
//how to set the response of that rest call to this messageData object
return messageData;
}
}
this method getWeatherStatus should return the rest response in json format.
Open for totally different suggestion to implement this kind of scenario.
My basic requirement is to use this REST call response and send to other functions.
In getWeatherStatus you use async function client.get. You need wait result from async function and only than return messageData. For this you can use deasync. Example:
var Client = require('node-rest-client').Client;
var client = new Client();
module.exports = {
getWeatherStatus: function() {
var messageData = "";
client.get("http://api.openweathermap.org/data/2.5/weather?q=Pune&appid=123234234234243242", function (data, response) {
console.log(JSON.parse(data));
messageData=data;
});
//We waiting for data.
while (messageData === "") {
require('deasync').sleep(10);
}
return messageData;
}
}
But, maybe, you should return Promise, not data.
Since get is callback function so you have to put your return messageData
in stead of messageData=data.
Code should be like
var Client = require('node-rest-client').Client;
var client = new Client();
module.exports = {
getWeatherStatus: function() {
var messageData = "";
client.get("http://api.openweathermap.org/data/2.5/weather?q=Pune&appid=123234234234243242", function (data, response) {
return JSON.parse(data);
});
}
}
I think you are facing difficulties to deal with with callbacks,
In the method getWeatherStatus, instead of returning the result, you should pass it to a callback function once the treatment is done.
If really you are required to return, galk.in answer seems to be a possible way.
Otherwise, check this out,
var Client = require('node-rest-client').Client;
var client = new Client();
module.exports = {
getWeatherStatus: function(then) {
var messageData = "";
client.get("/some/url", function (data, response) {
then(err=null, JSON.parse(data));
});
}
}
So you may call getWeatherStatus in such way,
// Somewhere else in your code
getWeatherStatus(function fnCallback(err, jsonData) {
console.log(jsonData) // process data here
})
As suggested, Promise are also a good alternative. but it is still async.

How to connect jsReport in AngularJS?

I have a problem now about JSReport.. It assumed that I already have an API...What I want now is how to link it with my Client Side which uses AngularJS.
If I use Postman it will return a pdf file which is what I want. But my problem is how to show it is my page when i post it using angularjs..
I have a code like this :
Controller
$scope.Print = function () {
authService.print().then(function(result){
var _result = result;
});
};
Service
var _print = function () {
var data = { "template": { "shortid": "byQtwHLPQ" } };
return $http.post("http://192.168.8.87/api/report", data).then(function (result) {
return result;
});
};
authServiceFactory.print = _print;
Now I have that Code and its not working... I assumed it has no return so I remove the return and just post but still it didn't work and even downloading the pdf didn't work on it.
Anyone can help Please...
Use like this one..
Controller
var parameter = { "template": { "shortid": "ZkMoslfdX" }};
PrintService.Print(parameter).then(function (result) {
var file = new Blob([result.data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
Service
var reportUrl = "http://192.168.8.87/api/report";
var _print = function (parameter) {
return $http.post(reportUrl, parameter, { responseType: 'arraybuffer' }).success(function (response) {
return response;
});
};
The main idea is that the result.data is converted into a blob and create an objectURL so that it is readable and to the object tag and $sce.trustAsResourceUrl used to trust angular to your URL
HTML
<object data="{{content}}" type="application/pdf" style="width:100%;height:80%"></object>
I refer to this post AngularJS: Display blob (.pdf) in an angular app for clarification just read that one.

Pass a variable to a function from another function in JavaScript (winJs)

Hi I'am working with Windows 8 app using Java Script
function fetchFromLiveProvider(currentList, globalList,value) {
feedburnerUrl = currentList.url,
feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json&num=999&q=" + encodeURIComponent(feedburnerUrl);
WinJS.xhr({url: feedUrl, responseType: "rss/json"
}).done(function complete(result) {
var jsonData = JSON.parse(result.response);
//console.log(JSON.stringify(jsonData));
var entries = jsonData.responseData.feed;
});
}
function setOther(entries){
//some code here
}
I want to do is pass the entries in the fetchFromLiveProvider function to another function called setOther(entries){}. Thank you for any help...
Since WinJS.xhr returns a promise, you can do the following:
var entriesPromise = function fetchFromLiveProvider(currentList, globalList, value) {
feedburnerUrl = currentList.url,
feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json&num=999&q=" + encodeURIComponent(feedburnerUrl);
return WinJS.xhr({
url: feedUrl,
responseType: "rss/json"
});
}
function setOther(entries) {
entries.done(function complete(result) {
var jsonData = JSON.parse(result.response);
//console.log(JSON.stringify(jsonData));
var entries = jsonData.responseData.feed;
//some code here
})
}
setOther(entriesPromise);

Accessing Data from JavaScript Object's Array Member Variable

I'm writing a jQuery plugin for work which pulls in RSS feed data using Google's Feed API. Using this API, I'm saving all of the relevant RSS feed data into an object, then manipulating it through methods. I have a function which is supposed to render the RSS feed onto the webpage. Unfortunately, when I try to display the individual RSS feed entries, I get an error. Here's my relevant code:
var RSSFeed = function(feedTitle, feedUrl, options) {
/*
* An object to encapsulate a Google Feed API request.
*/
// Variables
this.description = "";
this.entries = [];
this.feedUrl = feedUrl;
this.link = "";
this.title = feedTitle;
this.options = $.extend({
ssl : true,
limit : 4,
key : null,
feedTemplate : '<article class="rss-feed"><h2>{title}</h1><ul>{entries}</ul></article>',
entryTemplate : '<li><h3>{title}</h3><p>by: {author} # {publishedDate}</p><p>{contentSnippet}</p></li>',
outputMode : "json"
}, options || {});
this.sendFeedRequest = function() {
/*
* Makes the AJAX call to the provided requestUrl
*/
var self = this;
$.getJSON(this.encodeRequest(), function(data) {
// Save the data in a temporary object
var responseDataFeed = data.responseData.feed;
// Now load the data into the RSSFeed object
self.description = responseDataFeed.description;
self.link = responseDataFeed.link;
self.entries = responseDataFeed.entries;
});
};
this.display = function(jQuerySelector) {
/*
* Displays the RSSFeed onto the webpage
* Each RSSEntry will be displayed wrapped in the RSSFeed's template HTML
* The template markup can be specified in the options
*/
var self = this;
console.log(self);
console.log(self.entries);
};
};
$.rssObj = function(newTitle, newUrl, options) {
return new RSSFeed(newTitle, newUrl, options);
};
// Code to call the jquery plugin, would normally be found in an index.html file
rss = $.rssObj("Gizmodo", "http://feeds.gawker.com/Gizmodo/full");
rss.sendFeedRequest();
rss.display($('div#feed'));
Obviously, my display() function isn't complete yet, but it serves as a good example. The first console.log() will write all of the relevant data to the console, including the entries array. However, when I try to log the entries array by itself, it's returning an empty array. Any idea why that is?
I guess the problem is that display() is called without waiting for the AJAX request to complete. So the request is still running while you already try to access entries - hence the empty array.
In order to solve this you could move the call to display() into the callback of $.getJSON(). You just have to add the required selector as a parameter:
this.sendFeedRequest = function(selector) {
var self = this;
$.getJSON(this.encodeRequest(), function(data) {
var responseDataFeed = data.responseData.feed;
...
self.entries = responseDataFeed.entries;
self.display(selector);
});
};
EDIT:
If you don't want to move display() into the callback, you could try something like this (untested!):
var RSSFeed = function(feedTitle, feedUrl, options) {
...
this.loading = false;
this.selector = null;
this.sendFeedRequest = function() {
var self = this;
self.loading = true;
$.getJSON(this.encodeRequest(), function(data) {
...
self.loading = false;
if (self.selector != null) {
self.display(self.selector);
}
});
};
this.display = function(jQuerySelector) {
var self = this;
if (self.loading) {
self.selector = jQuerySelector;
}
else {
...
}
};
};

Categories

Resources