Replace url with a variable and display object one by one - javascript

i have a file locally which has array of objects in my view i need it to be warped as a variable, on viewing the variable that array should be used
i tried this but i dont know its the right way could some one help me
var url = 'proj/array/arrayobject';
console.log(url);
var refreshId = setInterval(function(){
$('div.comment-container').comment({
//here i should call that url and display object one by one with equal intervals
})
}, 1000);
could some one help me

First of all I would suggest to keep that file as JSON file having .json extension. It would make the file purpose more clear.
Secondly, You can use jQuery Ajax's getJSON() method to get data of that file and assign it to your local or global variable like below:
var myGlobalVariable = null;
$.getJSON("proj/array/arrayobject.json", function( data ) {
myGlobalVariable = data;
});
Then, You can use your myGlobalVariable in your code. But, Make sure that you use it once you get data in it. For this you can use callbacks.
For your scenerio, Code will be like below:
var url = null;
function init() {
$.getJSON("proj/array/arrayobject.json", function(data) {
url = data;
MyFunc();
});
}
function MyFunc() {
setInterval(function() {
$('div.comment-container').comment({
// use url here
})
}, 1000);
}
$(function() {
init();
});

Related

I want to send multiple variables from JavaScript function to another page

I have a form and I have fetch form data inside function.I want to send all
variables having data to be send to next page .Please tell me how to do it
function form_values() {
var jsvar = document.myform1.text_quest.value;
alert(jsvar); // test
$('select[name="dropdwn"]').each(function() {
alert(($(this).val()));
});
var cal = document.getElementById("otherAnswer").value;
alert(cal);
var chk = [];
$(':radio:checked').each(function() {
//alert($(this).val());
chk.push($(this).val());
});
alert(chk);
$('[type=checkbox]:checked').each(function() {
alert($(this).val())
});
} //End of function
you have to use serialize() in jquery.
For example:
url:'your_file.php?'+serialize();
This will send all the form values to that file.
For more details check here
Why not use localStorage to store the values in a json object, and use them in any of your scripts?
For example, in your form_values():
var formData = {};
$('select[name="dropdwn"]').each(function() {
formData.dropdwn = $(this).val();
});
Then on form submit:
localStorage.setItem('formData', JSON.stringify(formData));
Then from another javascript file:
var formData = JSON.parse(localStorage.getItem('formData'));
console.log(formData.dropdwn); // logs your value
Of course, make sure you check if formData exists on localStorage before trying to get a value from it.

Passing variable from a onload promise in jQuery

I'm trying to pass a parameter from a onload GET method call to a POST method. The GET method is being loaded on window.onload and the POST function is not in the onload call otherwise the POST function will trigger once the window has loaded. I only want to trigger POST function when I click a button.
How can I pass a variable from a onload AJAX call to my POST function?
The only way I could think of is using a global variable however I don't think that's a good way of passing it to another function.
window.onload = function () {
function firstCallBack() {
$.get('http://website.com/API/docs/v1').then(function(data1){
var passThis = "PassMeToPOST"
}).then(function (data2) {
})
}
}
POST function
function saveSettings(passThatVar) {
var urlVal = window.__env.url+ "Preview/TypeDefinition";
var xslSettingVal = $('#PreviewXml').val().replace(/\n/g, "");
var allData = {
'ObjectName': passThatVar,
'DisplayDefinition': setting,
}
$.ajax({
url: urlVal,
type: "POST",
data: JSON.stringify(allData),
success: function (data) {
console.log('success');
}
});
}
Button HTML:
<button onclick="saveSetting()"> Save Setting </button>
Try this:
Your button:
<button id="save-settings"> Save Setting </button>
After your get request, set a data-attribute to your button:
function firstCallBack() {
$.get('http://website.com/API/docs/v1').then(function(data1){
$("#save-settings").data("passMe", "PassMeToPOST");
}).then(function (data2) {
})
}
Bind the click event(its a best practice than using inline events):
$("#save-settings").on("click", saveSetting);
On your saveSetting() function:
function saveSetting() {
var allData = {
'ObjectName': $(this).data("passMe"),
'DisplayDefinition': setting,
}
//... your post request
}
You can also check if the get request has finished before starting the post request(to avoid a bug in an extreme scenario):
if (!$(this).data("passMe")) {
return;
}
You're basically asking how to keep a variable out of the global scope. This is called encapsulation. It is a good instinct but a large topic. Here is a post that I like on the topic: http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/
One low budget way of doing this is instead of making a global variable for your value, make a global namespace for your own use.
var MyUniquelyNamedThing = {};
...
// get response:
MyUniquelyNamedThing.ThatValueINeed = data;
...
// posting:
data = { val1: MyUniquelyNamedThing.ThatValueINeed , etc. };

How To Read JSON File Offline Using JavaScript?

I am trying to read a JSON file using JavaScript in my local computer in index.html file only. My JSON file is feed.json as shown below.
feed.json
// API callback
readFile({
"version": "1.0",
"encoding": "UTF-8",
"feed": {
"xmlns": "http://www.w3.org/2005/Atom",
"xmlns$openSearch": "http://a9.com/-/spec/opensearchrss/1.0/",
"xmlns$blogger": "http://schemas.google.com/blogger/2008",
"xmlns$georss": "http://www.georss.org/georss",
"xmlns$gd": "http://schemas.google.com/g/2005",
"xmlns$thr": "http://purl.org/syndication/thread/1.0",
"title": {
"$t": "Title Of A Feed"
},
"id": {
"$t": "ID Of The Feed"
}
}
});
I am reading the above file using the below code that I added just before </body> tag in my index.html file.
index.html
<script>
function readFile(json) {
alert(json.feed.title.$t);
}
// Calling The JSON File For This Function
var s = document.createElement("script");
s.setAttribute("src","feed.json?callback=readFile");
document.body.appendChild(s);
// Again Calling The Same JSON File
function readFileAgain(json) {
alert(json.feed.id.$t);
}
// Calling The JSON File For This Function
var s = document.createElement("script");
s.setAttribute("src","feed.json?callback=readFileAgain");
document.body.appendChild(s);
</script>
I want to read this file in two functions on same page and I cant edit feed.json file. When I am running my above code, its reading only above function not second. So how is this possible to read this file again?
It is jsonp not json as you can see you have a wrapper js function in the feed.json:
readFile({......})
//^^^^^^^--------^----you can see this is a function name readFile
As you can see readFile is been supposed to call after load or as a callback so in the first case it is running because the callback matches the function name. While in the second one the callback is not matching with the function name, they are different.
For the second one:
readFile != readFileAgain // so it never gets executed.
So, i would suggest you to make use of localStorage:
function readFile(json) {
if(window.localStorage && !localStorage.getItem['data']){
localStorage.setItem('data', json); // <-----set it first here
}
alert(json.feed.title.$t);
}
// Calling The JSON File For This Function
var s = document.createElement("script");
s.setAttribute("src","feed.json?callback=readFile");
document.body.appendChild(s);
// Again Calling The Same JSON File
function readFileAgain() {
var json = '';
if(window.localStorage && localStorage.getItem['data']){
json = JSON.parse(localStorage.getItem['data']); // <------------now get it here.
}
alert(json.feed.id.$t);
}
// Calling The JSON File For This Function
var s = document.createElement("script");
s.setAttribute("src","feed.json?callback=readFileAgain");
document.body.appendChild(s);
The feed.json is in fact a JavaScript file with a single function call: it calls the readFile() function passing an object as argument. So it works the first time, because you have defined the readFile function. The other one, readFileAgain, is defined but never called.
You could assign the data from your file to a global variable in the first read, then use it when needed:
function readFile(json) {
window.feedjson = json;
}
var s = document.createElement("script");
s.setAttribute("src","feed.json");
document.body.appendChild(s);
Now the data is globally available as feedjson, so you can use it:
function getFeedTitle( data ){
alert(data.feed.title.$t);
}
function getFeedId( data ){
alert(data.feed.id.$t);
}
getFeedTitle( feedjson );
getFeedId( feedjson );
I was trying to find out the solutions and I got the below one. Its working now perfectly. Through this I can unlimited functions using single callback...
index.html
<script>
function readFile(json) {
readFileAgain(json);
readFileAgainAgain(json);
}
// Calling The JSON File For This Function
var s = document.createElement("script");
s.setAttribute("src","feed.json?callback=readFile");
document.body.appendChild(s);
// Again Calling The Same JSON File
function readFileAgain(json) {
alert(json.feed.title.$t);
}
function readFileAgainAgain(json) {
alert(json.feed.id.$t);
}
</script>
Local Storage
Other process is using HTML5 Local Storage. Its also tested and working. You can use your JSON unlimited time also here freely...
<script style='text/javascript'>
function savePostsJSON(json) {
if(window.localStorage){
localStorage.setItem('JSONdata', JSON.stringify(json));
} else {
alert("Your Browser Doesn't Suppoet LocalStorage.");
}
}
var s = document.createElement("script");
s.setAttribute("src","http://www.guitricks.com/feeds/posts/default/?redirect=false&orderby=published&alt=json&max-results=500&callback=savePostsJSON");
document.body.appendChild(s);
function readFile1() {
var json = JSON.parse(localStorage.getItem("JSONdata"));
alert(json.feed.id.$t);
}
function readFile2() {
var json = JSON.parse(localStorage.getItem("JSONdata"));
alert(json.feed.title.$t);
}
readFile1();
readFile2();
</script>

JavaScript static function in callback

Hi I've been trying to clarify this but there's something I'm still confused about. I know that you can't return values from asynchronous functions so I've referenced this answer's top answer Returning value from asynchronous JavaScript method?
What I'm trying to do is use the flickrAPI to get the biggest size image. The flickrAPI allows one to search images, so I use this to get the photo_id, then I use this photo_id to procses another request to the API's getSize method to get the URL for the biggest size photo.
The code looks a little messy as it is, because I have a method called flickrRequest which sends an XMLHttp request and gets back a JSON string. I know that I can achieve what I want by writing the functions as follows:
function flickRQforimage() {
...got ID
function flickrRQforSize() {
...got maxsizeURL
create image based on maxsizeURL here
}
}
but I was wondering if it was possible to do something like this
function flickRQforimage() {
...got ID
function flickrRQforSize() {
...got maxsizeURL
}
create image based on maxsizeURL here
}
or even create image based on maxsizeURL here
In general my question is whether it is possible to have a callback function that references another statically defined function (I think?). The specifics of the my function is that it takes a callback and the ID and URL processing happens in those callbacks:
flickrRQ(options, cb)
I am wondering whether/what would happen if that unnamed function is instead something else, say flickrRQ(options, processPhoto(data)), and then I define the function in a separate method. This just makes sense for me because I want to keep functionality for the URL processing separate in an attempt to make my code cleaner and more readable.
I tried the following below and it didn't work. Nothing prints. I even have a console.log in the processPhoto method. In fact anything inside of the flickrRQforSize method seems to not evaluate
flickrRQforSize(options, function(data) {
processPhoto(data)
}
even though in the flickrRQforSize definition, a callback function is taken as an argument. I'm suspecting there must be something about functions/async calls that I don't understand.
I hope this is clear -- if not, I can post my actual code.
Here's my code:
var flickrRequest = function(options, xhrRQ, cb) {
var url, xhr, item, first;
url = "https://api.flickr.com/services/rest/";
first = true;
for (item in options) {
if (options.hasOwnProperty(item)) {
url += (first ? "?" : "&") + item + "=" + options[item];
//parses to search equest;
first = false;
}
}
//XMLHttpRQ to flickr
if(xhrRQ == 1 ) {
xhr = new XMLHttpRequest();
xhr.onload = function() { cb(this.response); };
xhr.open('get', url, true);
xhr.send();
};
}
var processPhotoSize = function(photoJSON) {
var parsedJSON = JSON.parse(data);
var last = parsedJSON.sizes.size.length;
console.log(parsedJSON.sizes.size[last-1].source);
return parsedJSON.sizes.size[last-1].source;
}
...
flickrRequest(options, 1, function(data) {
...
flickrRequest(sizesOptions, 0, function(data) {
parsedJSON = JSON.parse(data);
console.log(parsedJSON);
processPhotoSize(data);
});
}

Javascript variable equal to json data file

I have a simple javascript file, javascriptvar.js, which contains a json within that file like this:
var ajavascriptjsonvariable = {
id: "someid",
name: "somerandomname",
data: {},
children: []
};
What i am trying to do is to simply make the var ajavascriptjsonvariable equal to a text file where the json is stored. So i create a file called "data.json" with this inside:
{
id: "someid",
name: "somerandomname",
data: {},
children: []
}
(I'm not sure if i need a semicolon in the end of data.json or not?)
And now i try to make the variable ajavascriptjsonvariable in the js file read the data.json file, but it won't go through. Here's what i do:
$.getJSON("data.json", function(data){});
var ajavascriptjsonvariable = data;
How do i get the ajavascriptjsonvariable = the data.json file?
Edit, sorry, quotes were a typo, corrected them, what i am asking is i think i'm supposed to include something into function(data){} brackets part to make ajavascriptjsonvariable read the data.json file, i don't know that part, that's what i'm trying to figure out.
first of all the JSON wont validate it should look like this
{
"id": "someid",
"name": "somerandomname",
"data": {},
"children": []
}
next since you are making an ajax call here, u must assign the value inside the ajax callback function
$.getJSON("data.json", function(data){
var ajavascriptjsonvariable = data;
/* Rest of the code with uses the "ajavascriptjsonvariable" variable */
});
AJAX is asynchronous, in 99% of all cases assigning a value to a variable which you do not use in the callback function is wrong. Here's what you should do:
$.getJSON("data.json", function(data) {
// use data here
});
Obviously you can assign data to some other variable that exists in an outer scope, but then you cannot just use it after the $.getJSON() call! You need to call whatever codes relies on the result from your callback function.
var MyVariableModule = (function($){
var myJavaScriptJsonVariable = null;
var getJsonFile = function(){
return $.getJSON("data.json").done(function(data) {
myJavaScriptJsonVariable = $.trim(data);
});
};
return {
makeComparison : makeComparison
};
})(jQuery);

Categories