Hi and Good day to all,
I have a dilemma which includes javasript and ajax. I have an ajax code which is show below (not the whole code but part of the code, so some brackets might be missing but it works correctly)
$.ajax({
url: "ajax/month.php",
type: 'POST',
data: { telcos: telco, start: sdate, end: edate, regions: region},
success: function (dataofconfirm) {
var month = dataofconfirm;
alert(month);
In the ajax above (of course it was inside a javascript), when i tried to alert it this is the result
Then I tried to place a monthly sales chart like the one below
This is the code (javascript) of my sales chart
var months = month;
// Get context with jQuery - using jQuery's .get() method.
var salesChartCanvas = $("#salesChart").get(0).getContext("2d");
// This will get the first returned node in the jQuery collection.
var salesChart = new Chart(salesChartCanvas);
var salesChartData = {
labels: months,
datasets: [
{
label: "SMART",
fillColor: "rgb(255,40,40)",
strokeColor: "rgb(255,40,40)",
pointColor: "rgb(253,16,16)",
pointStrokeColor: "#c1c7d1",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgb(220,220,220)",
data: [65, 59, 80, 81, 56, 55, 40]
}
Above code is just a portion again so some brackets might be missing.
Notice that I placed the ajax result inside var months
But when the javascript loads and finishes its process the result is like the one below
Instead of a certain number per months will be shown it now displays that certain number per letter in the month variable.
How Can i fix this. The result mut be like the one below(this is just a static so its correct)
This is whar the labels:months should look like
labels: ["August", "September", "October", "November"],
The ajax response is returning a string, not an array.
In JavaScript (and most languages) a string can be treated as an array of characters. Which is what is happening here.
Instead you need to parse the returned data as JSON, you can do this one of two ways:
JSON.parse(month); // <-- the result returned from the server
Or using jQuery $.ajax
$.ajax({
url: "ajax/month.php",
dataType: "json", // <-- response will be an object, not a string
type: 'POST',
data: { telcos: telco, start: sdate, end: edate, regions: region},
Related
So I am making a COVID-19 tracker(For Indian region) web Application using Node.js Express.js and EJS. So the issue i am getting is while creating Chart using library chart.js And I am using this API to fetch data https://api.covid19india.org/data.json .And the chart is for Total Confirmed cases on Y-axis and on X-axis Date (date from the starting of this pandemic till now)
these Informations are fetched from the api .I'm using a for loop to iterate through the array and get the specific data and pusshing it into an empty array dailyDateChnage=[], dailyCnf=[];
and later passing this data into the EJS file analytics.ejs <%=dailyDateChnage%> <%=dailyCnf%>
const dailyDateChange=[],dailyCnf=[];
const url = "https://api.covid19india.org/data.json";
const covidDataApi = axios.get(url).then(function(response) {
covidData = response.data;
for (var i = 0; i < covidData.cases_time_series.length; i++) {
let day = covidData.cases_time_series[i].date;
let cnf = covidData.cases_time_series[i].totalconfirmed;
dailyDateChange.push(day);
dailyCnf.push(cnf);
}
app.get("/analytics", function(req, res) {
res.render("analytics", {
dailyDateChange: dailyDateChange,
dailyCnf: dailyCnf,
});
});
my code for creating a chart using chart.js in file analytics.ejs
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data:{
labels:[<%=dailyDateChange%>],
datasets: [{
label: 'Daily Confirmed Cases',
data: [<%=dailyCnf%>],
fill:false,
backgroundColor: [
"red"
],
borderColor: [
"red"
],
borderWidth: 2,
pointBorderColor:"red",
pointBackgroundColor:"red",
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
labels:<%=dailyDateChange%> using this label the chart is not rendering [here is an image of the source page the data is being sent but not being rendered2 and an image of the output
but when replacing the labels as labels:<%=dailyCnf%>, the chart is getting rendered. image after replacing the labels
And I have tried converting the date data to string and Converting the date data to millisecond the again converting it to string
nothing has worked for me.
I don't even understand what is this issue
Can someone Explain and provide a solution for this.
When printing dailyDateChange using <%= %> it simply "prints" it as output. Consider this: You use console.log with a string element - you don't get double quotes around it in the output.
But in your code, you want the double quotes around the values of label.
Currently you might be getting something like this:
labels: [10 April, 11 April]
While you need this:
labels: ["10 April", "11 April"]
The simplest method to do so is convert it via JSON.stringify and use <%- %>` instead. The - tag (instead of =) does not escapes the string.
This code should work for you:
labels: <%- JSON.stringify(dailyDateChange) %>
Note that I also removed [] from around label as Stringify does that for us.
I have hit upon a problem where by I have an IEnumerable<string> of labels and an IEnumerable<double[]> of data in my MVC model object, and I would like to plot these values using Chartjs.
I pass both of in to my javascript function, which I trying to make plot the chart.
The Chartjs syntax is such that I want, in effect:
var data = {
... chart info e.g. colors, etc.
datasets: [
{
label: labels[0], // My first label
data: datas[0] // My first double[]
},
// Repeat for each data/label combo
{
label: labels[n], // My n-th label
data: datas[n] // My n-th double[]
}
]
};
Given my two collections, how can I extract the information within them appropriately? Clearly the lengths of these collections need to be the same, as there is a one-to-one association. I did try combing them in to a Tuple but I think that will make it more complicated on the js side.
Or does anyone know an easier way to achieve the same end result with ChartJS?
I'm comfortable with C# but Javascript is new to me.
You can certainly send a tuple to the client side and split it up easily with java-script. You could do a simple ajax call to get your tuple as a Json object and then split it up into two arrays. Those arrays could then be used in the chart.js label and data spots.
$.ajax({
url: 'AjaxCall/getChartObjects',
dataType: 'json',
data: {},
success: function (data) { //data here being the tuple recieved from server
//receive the tuple as a single Json object and split it up easily with some seperate arrays
dblArray= []
$.each(data.Item1, function (index, value) {
dblArray.push(value.text); //label array
}
descArray= []
$.each(data.Item2, function (index, value) {
descArray.push(value.dblTxt); //data array
}
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
}
});
Sending the tuple from the controller would be something like:
//tuple sends two objects together- both job arrays will be seperated
//and used in observables on client side
var chartObjects = Tuple.Create(chartData, chartLabel);
return Json(chartObjects, JsonRequestBehavior.AllowGet);
You would then have the arrays that you need to place in the chart properties:
var barChartData = {
labels: descArray, //array labels
datasets: [
{
type: "Bar",
strokeColor: "black",
pointColor: "rgba(220,220,220,1)",
pointstrokeColor: "white",
data: dblArray,
}
]
}
I guess I'm not entirely sure if this is what you were looking for. Let me know if you have questions.
I am using the select2 multiple for search box. I am passing these data with JSON and saving it using ajax(JSON stringify).
I just need 2 variables passed, which is the ID(primary key, customized) and the Selection itself.
I managed to save it to the database when only 1 value is selected.
When selecting multiple values, in my console.log, I see something like this
{21,23,25,26}
which is the selection itself.
How do I get it show like this,
Object0->{id:1, selection:21}
Object1->{id:2, selection:23}
Object2->{id:3, selection:25}
Object3->{id:4, selection:26}
Below is the code I am using,
var nature = {
ubtBusinessInfo: businessId, // the primary key
ubtBusinessListing: nature.val() // here is selection
};
Here is the initialization of the select2,
nature
.select2({
allowClear: true,
placeholder: "Filter as you type",
minimumInputLength: 3,
multiple: true,
ajax: {
url: 'home/umkei/info/nature',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return { q: term };
},
results: function (data, page) {
return { results: data };
},
cache: true
}
})
nature is defined from(I tried both as below)
var nature = $('[name=nature_business]') OR var nature = $(#nature_business);
I know it must have something to do with the nature.val() usage. Must have been something like array but I dont know how to differentiate/split those data to be key->value pairs.
Thank you.
I got this about last week and thought I'd share my solution.
var nature=[];
var splitnature = nature_business.val().trim().split(',');
var n;
for(n=0; n<=splitnature.length-1;n++){
nature.push({
ubtBusinessListing: splitnature[n],
ubtBusinessInfo: businessId
});
}
So I am using the library ECharts to create some charts and graphs for various data that I have on a website. This is my first time using the library and I am fairly new to Javascript/jQuery. What I am trying to do is set the xAxis data to the results from a local page which will return a JSON Object with an array containing the days of the week. After I can do this, I then plan to load the Series data in the same way.
The jSON that is returned is this
When I am trying to set the data for xAxis, I am doing it as shown
xAxis: [{
type: 'category',
boundaryGap: false,
data: function(){
$.ajax({
type: "POST",
url: "ajax/getData.php?test=t&graph_last_days=d&days=7",
cache: false,
success: function(result){
return result.data;
//console.log(result.data);
}
});
}
}],
However, I keep getting the error Uncaught TypeError: o.slice is not a function and this error is only being outputted when I try and use this method of setting the data. In addition to this, if I try and make a function to return the data from the external page and set a variable to that, whenever I try and print it to the console it says undefined
If I do not use my method of trying to load the external data and I predefine the data like so
xAxis: [{
type: 'category',
boundaryGap: false,
data: [
'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'
]
}]
Then there are no errors and it works just fine
Can anyone see the problem?
Seems that after speaking with some people, the only example usage or documentation available is this example they have which is closely related to my question here.
If anyone else wants some examples related to ajax or dynamic data loading with ECharts then here are some (in English) *
Line + Bar
Scatter + Candlestick
Pie + Radar
Helpful tip
If you do not speak Chinese and you are using some sort of translator for their code examples; be aware that it's common for websites such as Google Translate and Bing Translator to incorrectly translate the punctuation used in JS by doing things such as,
Translating arrays with single quotes into arrays with single quotes and double quotes: thus causing syntax errors.
Removing commas (,) from objects.
Changing Semi-colon's (;) into Colon's (:) or even removing them.
complete example for echarts pushing data from Ajax call
data.importPorts -> Array of strings
data.importBD -> Array of Objects { clientanem : [4,5,6,7,3]}
$.get("/Home/Graph1", { clients: "403,300", years: "2012" })
.done(function (data) {
var option = {
tooltip: {
show: true
},
legend: {
data: (function () {
var res = [];
for (var name in data.importBD) {
res.push(name);
};
return res;
})()
},
xAxis: [
{
type: 'category',
data: (function () {
var res = [];
data.importPorts.forEach(function (i) {
res.push(i);
});
return res;
})()
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
}
]
};
for (var name in data.importBD) {
var obj = {
name: name,
type: "bar",
data: data.importBD[name]
};
option.series.push(obj);
}
// Load data into the ECharts instance
imprtChart.setOption(option);
});
In my MVC application, I am trying to create a SVG Map with data that comes from a database. Using jQuery, I call an action in the controller which returns data in the format that is expected in the MapSvg region's parameter.
The format that is expected goes as follows:
regions : {
'Yemen': {disabled: true},
'USA': {tooltip: 'USA: Click to go to Google.com', attr: {fill: '#ff0000', href: 'http://google.com', 'cursor': 'help'}}},
'France': {tooltip: 'This is France!', attr: {'cursor': 'help'}},
'Kazakhstan': {tooltip: 'Kazakhstan - the ninth largest country in the world.'}
},
In my controller, I have an action that will be called in the view by a jQuery ajax request
public ActionResult GetCountries()
{
List<ScratchMap> allitems = this.Worker.GetAllItems();
var allItemsAsArray = allitems.Select(x => string.Format("'{0}': {{ tooltip: 'Test', attr: {{ fill: '{1}' }} }}", x.PluginCountryName, x.Color)).ToArray();
return Json(allItemsAsArray, JsonRequestBehavior.AllowGet);
}
In the View, the following code is executed after the jQuery plugins and the MapSvg plugins are loaded:
$.get('/ScratchMap/GetCountries', {},
function (data) {
var regionsData = '{' + data + '}';
$('#map').mapSvg(
{
source: '#Url.Content("~/Content/Maps/world_high.svg")',
loadingText: 'Loading map...',
tooltipsMode: 'names',
responsive: true,
zoom: true,
pan: true,
zoomButtons: {
'show': true,
'location': 'right'
},
regions: regionsData
});
}), 'json';
When the page is rendered, the map does not fill any countries that were retrieved from the database. However, when I copy and assign the output of the regionsData variable directly to the regions parameter, the map loads everything correctly.
The following article teaches me that this could have something to do with the input data type. However, if I parse the regionsData to JSON, it tells me it is in a wrong format. But the given example by the creators of MapSvg is also in a wrong format.
Does anybody have any ideas for a workaround?
Thanks.
The problem is that even if the regions variable is edited the map plugin doesnt watch the change in its object contents so you must either wait till the data is returned before graphing the contents. Or re-graph with the method below.
If you wish to wait to graph till the data has been returned from your database call you can use a promise to delay the graphing of the object. Also important to know is the format in which the OPTS variables needs to have here is a sample.
var OPTS = {
source: sourcepath, // Path to SVG map
colors: {background: '#fff',base: '#0066FF', stroke: '#fff', selected: 10, disabled: '#ff0000'},
tooltipsMode: 'combined',
zoom: true,
pan: true,
responsive: true,
width: 1170,
zoomLimit: [0,100],
onClick: function (e, m) {
//do something here on each map click
},
regions:{
id_of_svg_path(the actual region you want to add data for):{
disabled:true,/*or whatever you need*/
tooltip:'<h4>Something to say</h4>'
}
}
}
In-order to re-graph I used the return object:
OPTS are just your specific chart options.
A variable javascript object that contains a regions variable.
var chartObj = $('#chart_container').mapSvg(OPTS);
chartObj.destroy();
This call will destroy then you re-graph it with OPTS that you have passed in.
Once you have destroyed it and passed in the new data you can just call.
var chartObj = $('#chart_container').mapSvg(OPTS);
Re-graphing it with the new data.
It turns out that it was an issue with the way I created the javascript output. The answer to this question can be found in this article.