Im creating multiple charts at the same page, now i want a smart function to either update a single chart or all of them
It works fine when i hard code the object name but i want to be able to get the object name from the button it was executed from
<button class="update" name="prodChart1" funtionName="f_A_GetTotalWorkedHours"> Test</button>
var prodChart1 = document.getElementById('ProdChart1');
var prodChart1 = new Chart( prodChart1, {
type: "line",
data: <%=f_A_GetTotalWorkedHours(Dateadd("d",-2,Date), Date, 48, Line, "")%>,
options: {
color: 'red',
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
$(".update").click(function(){
UpdateChart($(this).attr("name"),"")
});
function UpdateChart(chartName, aFunction) {
$.ajax({
type: 'POST', //post method
url: 'AnalyticsAPI.asp?',
dataType: "text",
data: {requestParam: 'f_A_GetTotalWorkedHours|'+ getParam()[0] +'|'+ getParam()[1] +'|48' },
success: function (result, textStatus, jqXHR)
{
data3= result;
chartName.config.data = JSON.parse(data3);
chartName.update();
},
error: function (xhr, ajaxOptions, thrownError) {
// alert(xhr.status);
alert(thrownError);
}
});
};
So the "update" function should get the name of the existing chart object, the object name is part of the button name attribute.
The error i get is that "UpdateChart(chartName, aFunction)" chartname isnt a object. If i would hardcode the object name in the call it works.
Try this: Get global variable dynamically by name string in JavaScript
Or add your chart to an Object of which you can access the keys:
var charts = {};
charts.populationIncrease = new Chart(...);
function updateChart(chartName, value) {
charts[chartName].value = value;
}
updateChart('populationIncrease', { ... });
Issue you have is that you are trying to access the objects property (getting and setting) however you are trying to access properties of the string $(this).attr("name")
where instead you should be using $(this)
see fixed code below
var prodChart1 = document.getElementById('ProdChart1');
var prodChart1 = new Chart( prodChart1, {
type: "line",
data: <%=f_A_GetTotalWorkedHours(Dateadd("d",-2,Date), Date, 48, Line, "")%>,
options: {
color: 'red',
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
$(".update").click(function(){
UpdateChart($(this), $(this).attr("name"),""); //Pass in the object and the name
});
function UpdateChart(chartObject, chartName, aFunction) {
$.ajax({
type: 'POST', //post method
url: 'AnalyticsAPI.asp?',
dataType: "text",
data: {requestParam: 'f_A_GetTotalWorkedHours|'+ getParam()[0] +'|'+ getParam()[1] +'|48' },
success: function (result, textStatus, jqXHR)
{
data3= result;
chartObject.config.data = JSON.parse(data3); //you are using the object not the string attribute of name
chartObject.update();
},
error: function (xhr, ajaxOptions, thrownError) {
// alert(xhr.status);
alert(thrownError);
}
});
};
Related
Here is what the console reads:
Uncaught TypeError: Cannot read property 'addTo' of undefined
I am currently working with leaflet JS and before the page loads, there is quite a number of Ajax calls going on so that the website can render the acquired data for the user.
I have used two particular methods to synchronize certain ajax calls which rely on the previous. One method is passing the next ajax call into the complete function, whilst another is the when().then() function
The objective with the function below, which is called with the window.onload method, is to determine the users location using the javascript navigator, set the map, and proceed with the ajax calls as mentioned above.
$(window).on('load', function() {
//Pre-loader Jquery
if ($('#preloader').length) {
$('#preloader').delay(200).fadeOut('slow', function() {
$(this).remove();
});
}
//Determine users location, initiate leaflet map, synchornised ajax calls to retreive country core information
navigator.geolocation.getCurrentPosition((success) => {
const crd = success.coords;
onLoadLat = crd.latitude;
onLoadLng = crd.longitude;
currentMap = L.map('map').setView([onLoadLat, onLoadLng], 5);
mapTileLayer.addTo(currentMap);
$.ajax({
url: "libs/php/openCage.php",
type: "POST",
dataType: "JSON",
data: {
latLng: onLoadLat + "+" + onLoadLng
},
success: function(data, textStatus, jqXHRs) {
iso_a2 = data["results"][0]["components"]["ISO_3166-1_alpha-2"];
},
complete: function() {
//Retreive GeoJson file, mark polygon and set initial map for to reflect user location
$.ajax({
url: "libs/php/getCountryBorder.php",
type: "POST",
dataType: "JSON",
data: {
countryCode: iso_a2
},
success: function(geoData, txtSt, jq) {
//Reference details of existing country for further API's and functionality
nameOfCountry = geoData["properties"]["name"];
//Use the index to target the array and create polygon border on map
targetMapData = L.geoJSON(geoData, {
style: borderStyle
});
targetMapData.addTo(currentMap);
currentMap.fitBounds(targetMapData.getBounds(), {
padding: [50, 50],
});
},
complete: function() {
$.ajax({
url: "libs/php/keyCountryInfo.php",
type: "POST",
dataType: "JSON",
data: {
country_code: iso_a2
},
success: function(data, textStatus, jqXHR) {
capitalCity = data["capital"];
currencyCode = data.currencies[0].code;
coordinates = [...data.latlng];
$("#timezoneList").empty();
$("#countryName").text(data["name"]);
$("#region").text(data["region"]);
$("#sub-region").text(data["subregion"]);
$("#countryFlag").attr("src", data["flag"]);
$("#population").text(numeral(data["population"]).format(0, 0));
$("#capital").text(data["capital"]);
$("#timezoneList").text(data["timezones"][0]);
},
complete: function() {
$.when(**getPopularCities()**, getCityWeatherList(), getWikiEntries(onLoadLat, onLoadLng), getGeoNameId(), getCountryImages(), getPublicHolidays(), getLatestExchange(), populateSelect()).
then(function(data, textStatus, jqXHR) {
infoEasyBtn.addTo(currentMap);
wikiEasyBtn.addTo(currentMap);
currencyEasyBtn.addTo(currentMap);
covidEasyBtn.addTo(currentMap);
newsEasyBtn.addTo(currentMap);
weatherEasyBtn.addTo(currentMap);
airportMarkers.addTo(currentMap);
cityMarkers.addTo(currentMap);
siblingMarkers.addTo(currentMap);
});
}
})
}
})
}
})
})
});
within the onload function above, is the getPopularCities() method, which is where the issue is. I have set markers to be shown on the map, but there is one group of markers which do not load, from within that function
Get Popular Cities Method
function getPopularCities() {
let cityPopulation = [];
cityMarkers = new L.MarkerClusterGroup();
if (mainLayer) {
currentMap.removeControl(mainLayer);
}
$.ajax({
url: "libs/php/getCountryCities.php",
type: "POST",
dataType: "JSON",
data: {
getCountryIso: iso_a2
},
success: function(success, textStatus, jqXHRs) {
$("#top10CityTable").empty();
let cityList = success["cities"]; //grab all the cities from the response
//create an array in global variable named cityPopulation, to contain all the markers
cityList.sort((a, b) => {
if (a["population"] > b["population"]) {
return -1
} else {
return 1
}
})
cityList.forEach((element, index) => {
let formatedPop = numeral(element["population"]).format(0, 0);
//depending on how many citys have returned, title the heading accordingly
if (cityList.length < 10) {
$("#top10CityHeading").text("Major Cities")
}
if (cityList.length >= 10) {
$("#top10CityHeading").text("Top 10 Most Populated Cities");
}
//stop index at 9 to get data of top 10 most populated cities for modal section
if (index <= 9) {
$("#top10CityTable").append(`<tr><td>${element["name"]}</td><td>${formatedPop}</td></tr>`)
}
cityMarkers.addLayer(L.marker([element["latitude"], element["longitude"]], {
icon: populatedCities
}).bindPopup(`<h3>${element["name"]}</h3></br>Population: ${formatedPop}`));
})
//create a new overlay prop/value pairing in the global overlays variable
overlays["Major Cities"] = cityMarkers;
},
error: function(text, xh, errorThrown) {
console.log(errorThrown);
},
complete: function() {
let siblingsMapArr = [];
siblingMarkers = new L.MarkerClusterGroup();
$.ajax({
url: "libs/php/getCountrySiblings.php",
type: "POST",
dataType: "JSON",
data: {
countryGeoId: geoNameId
},
success: function(success, textStatus, jqXHRs) {
$("#countrySiblings").empty();
let siblingsArr = success["geonames"];
siblingsArr.sort((a, b) => {
if (a["population"] > b["population"]) {
return -1
} else {
return 1
}
})
let top10Sib = siblingsArr.slice(0, 10);
top10Sib.forEach((element, index) => {
let formatedPop = numeral(element["population"]).format(0, 0);
let rank = index + 1;
siblingMarkers.addLayer(L.marker([element["lat"], element["lng"]], {
icon: citySiblings
}).bindPopup(`<h3>${rank}. ${element["countryName"]}</h3><br/>Population: ${formatedPop}`));
$("#countrySiblings").append(`
<tr>
<td>${element["countryName"]}</td>
<td>${formatedPop}</td>
<td>${element["lat"]} / ${element["lng"]}</td>
</tr>`)
})
overlays["Top 10 Siblings (By Population)"] = siblingMarkers;
},
complete: function(success, data, jq) {
$.ajax({
url: "libs/php/getAirports.php",
type: "POST",
dataType: "JSON",
data: {
countryCode: iso_a2
},
success: function(success, txtStatus, jqXHR) {
let airportsArr = [];
airportMarkers = new L.MarkerClusterGroup();
const airportsList = success["data"];
airportsList.forEach((element) => {
airportMarkers.addLayer(L.marker([element["location"]["latitude"], element["location"]["longitude"]], {
icon: airportIcon
}).bindPopup(`<h3>${element["name"]["original"]}</h3></br>ICAO: ${element["icao"]}</br>Elevation: ${element["elevationFeet"]}<br/>Classification: ${element["classification"]}`));
})
overlays["Airports"] = airportMarkers;
mainLayer = L.control.layers(baseMaps, overlays);
mainLayer.addTo(currentMap);
airportMarkers.addTo(currentMap);
cityMarkers.addTo(currentMap);
siblingMarkers.addTo(currentMap);
}
})
}
})
}
})
}
The markers saved in the variable airportMarkers and cityMarkers appear on the map as well as the leaflet control panel, but the siblings markers do not.
So Im guessing the safe bet is that it is not bringing the data back in time before the page loads? Does anyone have a solution for this or perhaps I have done something wrong in my code?
This is the JS I call in Index on document ready
jsonfields = #Html.Raw(Json.Encode(ViewBag.ColumnData));
This is the Ajax Call which I Make to bind
function onTeamTreeLoad(e) {
try {
$.ajax({
type: "POST",
url: window.ApplicationPath + 'Generic/GetTeamTree',
dataType: "json",
headers: { "__RequestVerificationToken": $("#AntiForgeryToken").val() },
contentType: 'application/json',
success: function (data) {
if (data != null) {
$("#TeamName").kendoDropDownTree({
dataSource: {
schema: {
model: {
children: "Items"
}
},
data: data
},
dataTextField: "Text",
dataValueField: "Id"
});
try {
if (e.model.TeamName !== "") {
$("#TeamName").data("kendoDropDownTree").text(e.model.TeamName);
}
} catch (e) { }
}
},
error: function () {
console.log('Failed to load');
}
});
} catch (e) {
console.log(e);
}
}
Why am I seeing [objectObject] when trying to bind the column? I want the data to be viewed instead of objectObject. I tried adding SerializeObject method to ID and Text but then I could not view that column when editing! I would like to know if there is any mistake in the AJAX call and what are the things that need to be added if using SerializeObject or JSON.Stringify.
Here you are just printing object. So Object -> Stringify give output like [object Object].
You can try this code.
for(var prop in obj) {
console.log(obj[prop]);
}
So, I have my JSON file, but I need to send a certain URL to my JSON aswell with a loop.
this is where I set everything:
function setMainObjectArray() {
var exercises = [];
var eBlocks = $('.eBlock');
eBlocks.each(function(i, eBlock) {
var exObject = {
word: $(eBlock).find('input.ExerciseGetWordInput').val(),
syllables: []
};
$(eBlock).find('input.syllable').each(function(j, syll) {
exObject.syllables.push($(syll).val());
});
exercises.push(exObject);
});
return exercises;
}
this is my ajax save function:
function saveExerciseAjaxCall() {
console.log(setMainObjectArray());
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
getExerciseTitle: $('#getExerciseTitle').val(),
language: $('#languageSelector').val(),
application: 'lettergrepen',
'main_object': {
title: $('#getExerciseTitle').val(),
language: $('#languageSelector').val(),
exercises: setMainObjectArray()
},
dataType: 'json'
}
}).done(function(response) {
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(errorThrown);
console.log(textStatus);
});
}
and I think I need to loop something like this through my function setMainObjectArray()
var audioId = MEDIAARRAY.audio.lowercase.indexOf(exObject['exerciseGetWordInput'].toLowerCase() + '.mp3');
var audio_link = '';
if (audioId > -1) {
exObject['audio'] = 'https://TheUrlServer' + MEDIAARRAY.audio.path + MEDIAARRAY.audio.files[audioId];
}
But I have no idea how to implement this into my function setMainObjectArray. I am not entirely sure if the loop is even written the correct way, i'm quite new to javascript and from there on to put it in my ajax call (since it's a link).
I'm trying to send an object that looks like this
var postBody = {
id: userID,
objectID: [0, 1],
objects: [
{id: 0, x: 0.33930041152263374, y: 0.08145246913580247, width: 0.0823045267489712, height: 0.30864197530864196},
{id: 1, x: 0.5277777777777778, y: 0.08453888888888889, width: 0.0823045267489712, height: 0.30864197530864196}
]
};
this is ajax call
$.ajax({
type: 'POST',
url: url,
data: postBody,
dataType: 'JSONP',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
}
});
this is what it looks like on server
{ id: '583f137fc338b517ec467643',
'objectID[]': [ '0', '1' ],
'objects[0][id]': '0',
'objects[0][x]': '0.33930041152263374',
'objects[0][y]': '0.08145246913580247',
'objects[0][width]': '0.0823045267489712',
'objects[0][height]': '0.30864197530864196',
'objects[1][id]': '1',
'objects[1][x]': '0.5277777777777778',
'objects[1][y]': '0.08453888888888889',
'objects[1][width]': '0.0823045267489712',
'objects[1][height]': '0.30864197530864196' }
if I put data: JSON.stringify(postBody) this is what I get
{ '{"id":"583f137fc338b517ec467643","objectID":[0,1],"objects":[{"id":0,"x":0.5,"y":0.5,"width":0.1,"height":0.1},{"id":1,"x":0.5401234567901234,"y":0.1833043209876543,"width":0.0823045267489712,"height":0.30864197530864196}]}': '' }
And it works! but then I cannot JSON.parse() it
this is what I get when I try
TypeError: Cannot convert object to primitive value
and all that Im doing on data on backend is this
console.log(JSON.parse(req.body)); // in the first example it was the same thing but only without JSON.parse()
Anyone have an idea why this is happening here?
Even if you have a suggestion on what I could try feel free to post here, otherwise I'm gonna have to write a function for parsing these badass inputs lol.
All the parsing/stringifying is handled by Node, so don't worry about it, just pass your object as it is, and you'll be able to access its properties in req.body.
client :
$.ajax({
type: 'POST',
url: url,
data: postBody,
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
}
});
server :
console.log(req.body); //should give you [Object object]
you can then send it right back with: res.status(200).json(req.body));
and read it in your ajax callback :
success: function(data) {
console.log(data);
},
i try show error message
i have a link button in grid view ..i call highcharts when i click on this link button and also this static function.. through this static function i get data and then call this function through javascript so when i click on this button chart is display but when there is no chart it shows error in code so for this i want to show alert box when there is no chart..
public static function(int ID)
try
{
}
catch (Exception ex)
{
Response.Write("<script>alert('" + Server.HtmlEncode(ex.ToString()) + "')</script>");
}
i try above but this shows error message
Error 3 An object reference is required for the non-static field,
method, or property 'System.Web.UI.Page.Server.get'
Error 2 An object
reference is required for the non-static field, method, or property
'System.Web.UI.Page.Response.get'
lbViewChart is link button ...
jquery
<script type="text/javascript">
var strArray = "[['sfdsdfLi', 9],['Kiwsdfi', 3],['Mixesdfd nuts', 1],['Oranges', 6],['Grapes (bunch)', 1]]";
$(function () {
$('[ID*=lbViewChart]').on('click', function () {
var row = $(this).closest('tr');
var Id = row.find('td')[0].firstChild.data;
var obj = {};
obj.ID = Id;
GetData(obj);
return false;
});
});
function GetData(obj) {
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetVoiliations",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert(result.d);
alert('u');
//start
strArray = result.d;
var myarray = eval(strArray);
$('#container').highcharts({
chart: {
type: 'pie',
options3d: {
enabled: true,
alpha: 45
}
},
title: {
text: 'Contents of Highsoft\'s weekly fruit delivery'
},
subtitle: {
text: '3D donut in Highcharts'
},
plotOptions: {
pie: {
innerSize: 100,
depth: 45
}
},
series: [{
name: 'Delivered amount',
data: myarray
}]
});
//end
},
error: function (error) {
alert(error);
}
});
}
// });
</script>
any solution?
You cannot access Server directly in a static method instead for that use System.Web.HttpContext.Current.Server So the code will be like:
System.Web.HttpContext.Current.Response.Write("<script>alert('" + System.Web.HttpContext.Current.Server.HtmlEncode(ex.ToString()) + "')</script>");
Or include using System.Web; to the using section and then use HttpContext.Current.Server
Updates: -
The HttpContext.Current is a static property so you can access it Directly inside a static method. and hence you can access .Server and .Response` from this as like the following:
System.Web.HttpContext currentContext = System.Web.HttpContext.Current;
currentContext.Response.Write("<script>alert('" + currentContext.Server.HtmlEncode(ex.ToString()) + "')</script>");