How to get json array from json file? - javascript

im creating Image Hotspot using javascript, i need to get a data (x,y and Info) from json file, currently im getting data from Javascript Array. How can i get it from json file?
Code Pasted here;
var points;
var l_nOldX;
var l_nOldY;
function createHotspots(){
var points = new Array(
/*Tamilnadu*/
[38.7, 85.6, "0168"],
[36.1, 85.3, "1843"],
[38.5, 88.3, "39647"],
[34.8, 29.2, "12320"]
);
var divHotspot = document.getElementById("loadImages");
for(pi = 0; pi < points.length; pi++){
var hs = document.createElement("div");
hs.className = "hotspot";
hs.style.position = "absolute";
hs.style.left = "calc(" + points[pi][0] + "% - 8px)";
hs.style.top = "calc(" + points[pi][1] + "% - 0px)";
hs.style.width = "15px";
hs.style.height = "15px";
var html;
if (points[pi][0] < 31) {
html = "<table cellpadding='0' cellspacing='0' class='tbltooltipright' align='center'><tr><td id='img9' align='center'><div align='center'><div class='divtooltip'><div class='divclose'></div>" + points[pi][2] + "</div><div id='triangle-down' class='arrow_boxr'></div></td></tr><tr><td align='center' id='img10' ></td></tr></table>";
// alert('a');
hs.innerHTML = html;
$(hs).bind("mouseenter", function () {
$(".tbltooltipnormal").hide();
$(".tbltooltipleft").hide();
$(".tbltooltipright").hide();
$(this).find(".tbltooltipright").show();
});
}
else {
html = "<table cellpadding='0' cellspacing='0' class='tbltooltipnormal' align='center'><tr><td id='img9' align='center'><div align='center'><div class='divtooltip'><div class='divclose'></div>" + points[pi][2] + "</div><div id='triangle-down' class='arrow_boxn'></div></td></tr><tr><td align='center' id='img10' ></td></tr></table>";
hs.innerHTML = html;
$(hs).bind("mouseenter", function () {
$(".tbltooltipnormal").hide();
$(".tbltooltipleft").hide();
$(".tbltooltipright").hide();
$(this).find(".tbltooltipnormal").show();
});
}
$('.divclose').on('click touchstart', function () {
//debugger;
$('.tbltooltipnormal').hide();
$('.tbltooltipleft').hide();
$('.tbltooltipright').hide();
return false;
});
divHotspot.appendChild(hs);
}
}
In above code i've get data from "Points" array instead of i need to get this array data from one json file ?
Please help me to get this fixed.
thanks in Advance.

You can use ajax to get the data from the json file and just wrap the existing code in a function which takes an argument and just assign that argument to the desired var:
var points;
var l_nOldX;
var l_nOldY;
function createHotspots(points){ // <---pass the array
var points = points; // assign it here
var divHotspot = document.getElementById("loadImages");
...
}
$.ajax({
url:'points.json', //<----call the json file
type:'GET',
dataType:'json',
success:createHotspots // reference to the data
});

var yourJsonDataFromFile=undefined;
var getJsonData=function () {
console.log("fetching data from JSON file");
var url = "path_to_your_json _file";
var ajaxHttp = new XMLHttpRequest();
ajaxHttp.overrideMimeType("application/json");
ajaxHttp.open("GET",url,true);
ajaxHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
ajaxHttp.send(null);
ajaxHttp.onreadystatechange = function () {
if(ajaxHttp.readyState == 4 && ajaxHttp.status == "200")
{
yourJsonDataFromFile = JSON.parse(ajaxHttp.response);
}
};
}
modify this code add file path in path_to_your_json _fileand call this function getJsonData() after that your data will be in yourJsonDataFromFile in json format , hope this will resolve your issue

Please try this. Should solve your problem
$.getJSON('<path_to_your_json_file>/file.json', function(data) {
var points = data;
});

Related

Getting undefined/no result when printing out api callback

I am trying to run my script that is going to search for a movie title from a movie database. I get results in the console and no errors. But in my renderMovies function it's supposed to store the API movie title, plot etc in my variables, but when I print it out in a list it either gives me nothing (blank) or undefined. I am kind of new to jQuery, AJAX and APIs so I'm following a guide, so the code is not entirely written by me.
OBS: I get undefined when using this $("<td>" + plot + "</td>"), but blank when using $("<td>").append(title). You can find that code in the middle of the renderMovies function.
For example: I search for the movie 'Avatar' and I get two results. However the two results gets "stored" as undefined in the plot description and blank from the title.
$(document).ready(function(){
$(init);
function init() {
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody");
function searchMovie(){
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title=" + title + "&token=b81c6057-20cf-4849-abc4-decbf9b65286&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&keyword=0&quotes=0&fullSize=0&companyCredits=0&filmingLocations=0",
dataType: "jsonp",
success: renderMovies
});
};
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title); // blank
var plotTd = $("<td>" + plot + "</td>"); // undefined on my website
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I've reordered your functions and calls because some of the variables were undefined. (Google Chrome -> F12 (opens developers console))
This returns a response on a button click.
$(document).ready(function () {
function searchMovie() {
var movieTitle = $("#movieTitle");
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title=" + title + "&token=b81c6057-20cf-4849-abc4-decbf9b65286&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&keyword=0&quotes=0&fullSize=0&companyCredits=0&filmingLocations=0",
dataType: "jsonp",
success: renderMovies
});
}
function renderMovies(movies) {
console.log(movies);
var movieInfo = movies.data.movies;
var table = $("#results");
var tbody = $("#results tbody");
tbody.empty();
for (var m in movieInfo) // Tar information från apin och stoppar in i egna variabler.
{
var movie = movieInfo[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title); // blank
var plotTd = $("<td>" + plot + "</td>"); // undefined on my website
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
$("#searchMovie").click(searchMovie);
});

use ajax success:function(data) on document ready jquery function

I am loading responsive calendar in document ready :
eventList=disp();
$(".responsive-calendar").responsiveCalendar({
events:eventList //json object data
});
function disp(){
//getArr();
//alert(data1); //not working
stb = '{';
edb = '}';
dt = ["2015-09-13","2015-10-22","2015-10-02"]; // dynamically to be created from ajax data
ct = [2,5,6]; // dynamically to be created from ajax data
ev = dt.length;
var ddt = stb;
for(var i=0; i<ev;i++){
ddt += '"' + dt[i] + '":{"number":'+ct[i]+'},';
}
mString = ddt.substring(0,ddt.length-1)
ddt = mString+edb;
return JSON.parse(ddt);
}
function getArr() {
$.ajax({
url:"../JLRFile.php",
success:function(data) {
data1 = data;
}
});
}
Here in disp() I need dt and ct to load from ajax data function, can any one provide proper solution, I called ajax function in disp() but its not working.
Please provide proper solution
eventList = getArr();
$(".responsive-calendar").responsiveCalendar({
events: eventList //json object data
});
function disp(data1) {
alert(data1); //getting now
stb = '{';
edb = '}';
dt = ["2015-09-13", "2015-10-22", "2015-10-02"]; // dynamically to be created from ajax data
ct = [2, 5, 6]; // dynamically to be created from ajax data
ev = dt.length;
var ddt = stb;
for (var i = 0; i < ev; i++) {
ddt += '"' + dt[i] + '":{"number":' + ct[i] + '},';
}
mString = ddt.substring(0, ddt.length - 1)
ddt = mString + edb;
return JSON.parse(ddt);
}
function getArr() {
$.ajax({
url: "../JLRFile.php",
success: function (data) {
data1 = data;
disp(data1);
}
});
}

.on('click', function (event) is not firing if the link is rendered inside a partial view [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
I am trying to implement an export to CSV functionality inside my asp.net mvc. So i added the following link inside a partial view:-
Export Table data into Excel
and inside the _layout view i call the following script:-
$(document).ready(function () {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function (i, row) {
var $row = $(row),
$cols = $row.find('td');
return $cols.map(function (j, col) {
var $col = $(col),
text = $col.text();
return text.replace('"', '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"',
// Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
// This must be a hyperlink
$(".export").on('click', function (event) {
// CSV
exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
i am using the table2CSV plugin as follow:-
jQuery.fn.table2CSV = function (options) {
var options = jQuery.extend({
separator: ',',
header: [],
delivery: 'popup' // popup, value
},
options);
var csvData = [];
var headerArr = [];
var el = this;
//header
var numCols = options.header.length;
var tmpRow = []; // construct header avalible array
if (numCols > 0) {
for (var i = 0; i < numCols; i++) {
tmpRow[tmpRow.length] = formatData(options.header[i]);
}
} else {
$(el).filter(':visible').find('th').each(function () {
if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
});
}
row2CSV(tmpRow);
// actual data
$(el).find('tr').each(function () {
var tmpRow = [];
$(this).filter(':visible').find('td').each(function () {
if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
});
row2CSV(tmpRow);
});
if (options.delivery == 'popup') {
var mydata = csvData.join('\n');
return popup(mydata);
} else {
var mydata = csvData.join('\n');
return mydata;
}
function row2CSV(tmpRow) {
var tmp = tmpRow.join('') // to remove any blank rows
// alert(tmp);
if (tmpRow.length > 0 && tmp != '') {
var mystr = tmpRow.join(options.separator);
csvData[csvData.length] = mystr;
}
}
function formatData(input) {
// replace " with “
var regexp = new RegExp(/["]/g);
var output = input.replace(regexp, "“");
//HTML
var regexp = new RegExp(/\<[^\<]+\>/g);
var output = output.replace(regexp, "");
if (output == "") return '';
return '"' + output + '"';
}
function popup(data) {
var generator = window.open('', 'csv', 'height=400,width=600');
generator.document.write('<html><head><title>CSV</title>');
generator.document.write('</head><body >');
generator.document.write('<textArea cols=70 rows=15 wrap="off" >');
generator.document.write(data);
generator.document.write('</textArea>');
generator.document.write('</body></html>');
generator.document.close();
return true;
}
};
But currently when i user clicks on the link, nothing will happen. but if i move the link to be inside the main view instead of inside the partial view the script will fire. but on the main view no data will be displyed , so i want the "Export Table data into Excel" to be rendered whenever the partial view is rendered,, so can anyone adivce on this please?
try change
$(".export").on('click', function (event) {
on
$(document).on('click', ".export", function (event) {

cannot read property '0' of undefined JSON

I'm trying to make an image slider that changes the image 'displayMain' every few seconds. My problem is that when I call the displayMain function in setInterval, I continuously get a 'cannot read property 0 of undefined' error. Even when I use the hardcoded value of jsonData[i].name, I receive the same error. The value gets passed in displayThumbs just fine, however. Does anyone know why I can't retain the values in displayMain but can do so in displayThumbs?
window.addEventListener('load', function () {
var mainDiv = document.getElementById('main');
var descDiv = document.getElementById('main-description');
var gallery = document.querySelector('#main-img');
var ul = document.querySelector('ul');
var li;
var i = 0;
var displayThumbs;
var thumbName;
var current = 0;
var images = [];
function displayMain () {
var data = images[i];
gallery.src = 'img/' + data[0];
descDiv.innerHTML = '<h2>' + data[1] + '</h2>';
}
function displayThumbs () {
for (i = 0; i < images.length; i += 1) {
var data = jsonData[i].name.replace('.jpg', '_thumb.jpg');
// thumbnails use dom to make img tag
li = document.createElement('li');
thumbs[i] = document.createElement('img');
var createThumbNail = thumbs[i].src = 'img/' + data;
thumbs[i].setAttribute('alt', data);
thumbs[i].addEventListener('click', function() {
alert(createThumbNail);
});
ul.appendChild(thumbs[i]);
}
}
// success handler should be called
var getImages = function () {
// create the XHR object
xhr = new XMLHttpRequest();
// prepare the request
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === 4 && xhr.status == 200) {
// good request ...
jsonData = JSON.parse(xhr.responseText);
for (var i = 0; i < jsonData.length; i += 1) {
var data = [];
data.push(jsonData[i].name);
data.push(jsonData[i].description);
images.push(data);
}
displayMain();
displayThumbs();
setInterval(displayMain, 1000);
}
else {
// error
}
});
xhr.open('GET', 'data/imagedata.json', true);
xhr.send(null);
};
// setInterval(getImages, 2000);
getImages();
// displayThumbs();
});
Your problem is that your displayMain uses whatever value i is at the time, and i never gets incremented, so it'll be equal to images.length after the for loop in displayThumbs. displayThumbs increments it itself, so you won't ever go beyond the end of the array.
In your comment, you mentioned that you want to cycle through the images. This should work a bit better:
function displayMain () {
var data;
// wrap around to the first image
if (i >= images.length) {
i = 0;
}
data = images[i];
gallery.src = 'img/' + data[0];
descDiv.innerHTML = '<h2>' + data[1] + '</h2>';
i++;
}
Personally, I would use a private i, just in case another function reuses the same variable:
function displayMain () {
var data;
// wrap around to the first image
if (displayMain.i >= images.length || isNaN(displayMain.i)) {
displayMain.i = 0;
}
data = images[displayMain.i];
gallery.src = 'img/' + data[0];
descDiv.innerHTML = '<h2>' + data[1] + '</h2>';
// move to the next image
displayMain.i++;
}
This attaches a variable named i to the function displayMain. It will update this variable each time it is called, and no other function will use the same i variable.

How to parse XML string with Prototype?

I have a string <ul><li e="100" n="50">Foo</li><li e="200" n="150">Bar</li></ul> and on client side I have to convert it to JSON. Something like {data:['Foo','Bar'],params:['100;50','200;150']}
I found a pretty good way to achieve it in here so my code should be something like that
var $input = $(input);
var data = "data:[";
var params = "params:[";
var first = true;
$input.find("li").each(function() {
if (!first) {
data += ",";
params += ",";
} else {
first = false;
}
data += "'" + $(this).text() + "'";
var e = $(this).attr("e");
var n = $(this).attr("n");
params += "'" + e + ';' + n + "'";
});
return "{data + "]," + params + "]}";
But the problem is that I can't use jquery. How can I do the same thing with prototype?
You want to use a DOM parser:
https://developer.mozilla.org/en/DOMParser
Something like this...
var xmlStr = '<ul><li e="100" n="50">Foo</li><li e="200" n="150">Bar</li></ul>';
var parser = new DOMParser();
var doc = parser.parseFromString(xmlStr, "application/xml");
var rootElement = doc.documentElement;
var children = rootElement.childNodes;
var jsonObj = {
data: [],
params: []
};
for (var i = 0; i < children.length; i++) {
// I realize this is not how your implementation is, but this should give
// you an idea of how to work on the DOM element
jsonObj.data.push( children[i].getAttribute('e') );
jsonObj.params.push( children[i].getAttribute('n') );
}
return jsonObj.toJSON();
Also, don't manually build your JSON string. Populate an object, then JSON-encode it.
Edit: Note that you need to test for DOMParser before you can use it. Check here for how you can do that. Sorry for the W3Schools link.
Why you are building an array object with string? Why not
var data = new Array();
var params = new Array();
$$("li").each(function() {
data.push ($(this).text());
params.psuh($(this).attr("e") + ";" + $(this).attr("n"));
});
return {data:data.toString(), params:params.toString()};
or
return {data:data, params:params};

Categories