Adding rows to the Google Data Visualization Table - javascript

I'm trying to add different set of lat,long in the google visualization table by iterating over the Ajax get response, it looks like only the last value in the response json is added to the row,
Javascript:
$.ajax({
type: 'GET',
url: '/api/v1.0/tasks/'+document.getElementById("autocomplete").value,
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(data){
for(var i=0; i<data.task.length; i++) {
var lat,long,name;
var lat = data.task[i].lat
var longi = data.task[i].longi
var name = data.task[i].markerText
alert(lat,longi,name)
var datag = new google.visualization.DataTable();
datag.addColumn('number', 'lat');
datag.addColumn('number', 'longi');
datag.addColumn('string', 'markerstr');
datag.addRows([[lat,longi,name],]);
}
})
Expected Output:
data = [[37.6153, -122.3900, 'Airport'],
[37.4422, -122.1731, 'Shopping'],]

It looks like you are rebuilding the data structure each time you iterate. It happens that your headers are the same. But in this case the whole data gets re-written on each iteration. Perhaps try something like this.
$.ajax({
type: 'GET',
url: '/api/v1.0/tasks/'+document.getElementById("autocomplete").value,
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(data){
var datag = new google.visualization.DataTable();
datag.addColumn('number', 'lat');
datag.addColumn('number', 'longi');
datag.addColumn('string', 'markerstr');
var rows = []
for(var i=0; i<data.task.length; i++) {
var lat,long,name;
var lat = data.task[i].lat
var longi = data.task[i].longi
var name = data.task[i].markerText
rows.push([lat,longi,name]);
}
datag.addRows(rows);
})

Related

DataSet Value in Jquery C#

I have one page in which, URL contains Querystring Value.
QSecID=164&QTempId=55&QSecName=New%20Temp%20Bt
When the page loads them and tries to get the value it works fine.
$(document).ready(function() {
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
var urlName = getUrlParameter('QSecName');
alert(urlName);
getImageData(urlName); //Pass Query String Value to Function
});
Now I am passing this value to C#, ASPX.CS page and try to fetch the data based on QSecName.
But i got error. Here is my Jquery function.
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
//data: '',
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("Success");
alert(JSON.parse(data.d));
}
});
}
My C# Page returns the DataSet in Jquery.
[WebMethod()]
public static string GetImageData(string dataSecName)
//public static string GetRole()
{
clsSection objSectNew = new clsSection();
DataSet DS = new DataSet();
DS = objSectNew.GetImageDataByJQ(dataSecName);
return JsonConvert.SerializeObject(DS);
}
Edit Code 1
Here is my SQL Statement Which is get executed when i run the page and
DS = objSectNew.GetImageDataByJQ(dataSecName);
this method pass the query string value in to execute the Stored Procedure.
select mhp.ImageName,mhp.HotSpotID,imgdetail.XCordinate,imgdetail.YCordinate
from tbl_SOAPDetailsInfo e inner join M_ImageHotSpot mhp on e.ImgHotSpotName=mhp.ImgHotSpotNameByUser
inner join M_ImageHotSpotDetail imgdetail on mhp.HotSpotID=imgdetail.HotspotIDFK where e.SOAP_D_Name='New Temp Bt'
I want to use my XCordinate, YCordinate and ImageName to display image using jquery. but Inside the alert BOX
**[object] [object]**
error display. How can i get and assign this value X AND Y value and display in DIV.
Edit Code 2
ImageName XCordinate YCordinate
$parent in angularjs.png 1146 590
$parent in angularjs.png 1216 588
$parent in angularjs.png 1188 626
$parent in angularjs.png 1162 582
$parent in angularjs.png 1193 586
The Database Value. JSON FORMAT DATA
{"d":"{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"}
So as per your question [object] [object] is not an error. It means you cannot fetch it in a correct manner.
Though I am not sure what kind of data you are sending from your back-end code in data But you could try following way,
var data = "{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
So now if you replace your code with above sample your code should look like below:
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
});
}
Note : Try to debug in browser console you would understand object notation more details.
See the screen shot how would you do that
Hope this would help

how to overload an array in javascript?

thsi is my code:
var data_book_list=new Array();
var test_type= jQuery('#test_type').val('list1');
function bookList() {
jQuery.ajax({
type: "POST",
url: "array.php",
dataType: 'json',
data: {book:book},
success: function(data){
for(var i=0;i<data.length;i++)
{
data_list.push(data[i]);
}
}
});
imagine database like: list1 has a1,a2,a3 & list2 b1,b2,b3
if i selected value list1 ajax get that value and sent it to php.
php using where case so it gives back to ajaxa1,a2,a3
now data has a1,a2,a3 i make it that a new array form for loop like ['a1','a2','a3']
i push this to a var data_book_list=[];
it work great.
but my problem is if i select option list2
data hasb1,b2,b3 and data_book_list=[] has a1,a2,a3
for loop push data b1,b2,b3 to array data_book_list it will extend like ['a1','a2','a3', 'b1','b2','b3']
but i need like this ['b1','b2','b3] in array data_book_list. how to clear or overload old array data automatically.
If you need to keep track of all the values retrieved so far, then you will have to use an object and have the value as array, corresponding to the keys.
var data_book_list_obj = {};
var test_type= jQuery('#test_type').val('list1');
function bookList() {
jQuery.ajax({
type: "POST",
url: "array.php",
dataType: 'json',
data: {book: test_type},
success: function(data){
for(var i=0;i<data.length;i++)
{
data_book_list_obj[test_type] = data_book_list_obj[test_type] || [];
data_book_list_obj[test_type].push(data[i]);
}
}
});
Or if you need only the recent information, then just assign the value.
var data_book_list=new Array();
var test_type= jQuery('#test_type').val('list1');
function bookList() {
jQuery.ajax({
type: "POST",
url: "array.php",
dataType: 'json',
data: {book: test_type},
success: function(data){
// Edit removed for loop wrongly put here
data_book_list = data;
}
});

How to build JSON string for JQuery DataTable?

I have created a code which fetches data using the Ajax Call and populate it to the data table UI.
My code is as below:
jQuery.ajax(
{
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('Events')/items?$select=Title,Session_x0020_Room,Session_x0020_Date,StartTime,EndTime,Duties,OnsiteContactEmail",
type: "GET",
headers: { "Accept": "application/json;odata=verbose" },
dataType: "json",
success: function (data, textStatus, xhr) {
if (data.d.results.length > 0) {
var resColl = data.d.results;
var strData= new Array();
for(var i=0; i < resColl.length; i++){
var arr = new Array();
arr.push(resColl[i].Title);
arr.push(resColl[i].Session_x0020_Room);
strData[i] = JSON.stringify(arr);
}
$('#example').DataTable({
data:strData,
columns: [
{ title: "Event" },
{ title: "Room" }
]
});
}
},
error: function (data, textStatus, xhr) {
console.error("Error while getting the data from Events list");
}
});
In strData object I am getting this value: "["Asian Women in Computing","Room 1"]"
But in the table of HTML I am not getting proper output.
What am I missing?
I'm assuming that DataTable expects an array of arrays that exists of strings. You have an array of JSON strings because you convert the array arr to a JSON string and push it to strData, which DataTable will later use.
var resColl = data.d.results;
var strData= new Array();
for(var i=0; i < resColl.length; i++){
var arr = new Array();
arr.push(resColl[i].Title);
arr.push(resColl[i].Session_x0020_Room);
strData[i] = arr;
}
Don't convert arr to a JSON string and it should print fine.

JQuery ajax to invoke method in controller and store the data

I have this code in JS:
$("#send_button").click(function(){
var isitArray = getObjectsRequest('isit', isitID);
var ecArray = getObjectsRequest('ec', ecID);
var bcArray = getObjectsRequest('bc', bcID);
var bbArray = getObjectsRequest('bb', bbID);
var ioArray = getObjectsRequest('io', ioID);
function getObjectsRequest(type, compId){
var array = [];
for (var i = 0; i<compId; i++) {
var comp = mainLayer.find('#'+ type + i)[0];
array.push({
xposition: comp.getX(),
yposition: comp.getY(),
titleid: comp.getId(),
description: comp.find('.textDescription')[0].getText(),
leftrelationsids: comp.leftCRelations,
rightrelationsids: comp.rightCRelations
});
};
return array;
}
var datatosend = {
isit: isitArray,
ec: ecArray,
bc: bcArray,
bb: bbArray,
io: ioArray
};
var diagramName = $("#diagramName").val();
if(diagramName==''){
alert("Enter the diagram name!");
} else {
datatosend.diagramname = diagramName;
$.ajax({
type: "POST",
url: "insertdata.php",
data: datatosend,
dataType: "text"
})
.done(function( msgReply ) {
alert("Data saved with success.");
//alert( "Data Saved: " + msgReply );
displayDiagrams();
});
}
return false;
});
This ajax jquery example uses a php file. I'm integrating this tool into an application in ruby on rails. My objective is to store the diagram data using a method in Diagram controller.
Is it possible to store the data using this kind of ajax request? More like this:
$.ajax({
type: "POST",
url: "/diagrams",
data: datatosend,
dataType: "html"
Invoking the create method in the Diagram controller.
How should I do this?

Assigning JSON value to a Variable that Resides Outside JavaScript Function

I have a question regarding JSON Web Services and AJAX Function. I have declared a JavaScript Function below.
function setJsonSer(){
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
alert("This is Set JSON In "+JSON.stringify(data));
}
});
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'GET',
data: formData,
complete: function(data) {
alert("This is Get JSON Out "+JSON.stringify(data));
}
});
}
As you can see I have alert the JSON.stingify(data) statement and it gave me the result as I expected.
Now I want to get that JSON response out of that particular function SetJsonSer() to assign to avariable that resides out side the SetJsonSer() function.
I already tried return JSON.stringify(data)) and JSON.stringify(data) statements but they did not put the result out from the SetJsonSer() function.
The output must grab from a variable like the below.
function Load(){
//-----------------------------------------------
setJsonSer();
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = "return value of JSON.stringify(data)";
This variable will be used as the query to draw a chart using HighCharts. So could you someone give me a clue how to get the result of the SetJsonSer() function?
Thanks and regards,
Chiranthaka
You're getting a bit mixed up with asynchronous nature of AJAX.
The AJAX event is being fired, but it won't be causing any pause in the execution of your code, as such, you need to implement a callback.
This code isn't particularly nice, but it should give you an idea of how the data needs to be handled.
function setJSONSer() {
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
console.log("Successfullly set JSON!");
getJSONSer();
}
});
}
function getJSONSer()
{
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'GET',
complete: function(data) {
//alert("This is Get JSON Out "+JSON.stringify(data));#
Load(data);
}
});
}
function BeginLoad()
{
setJSONSer();
}
function Load(data)
{
setJsonSer();
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = "return value of JSON.stringify(data)";
}
BeginLoad();

Categories

Resources