code-learner code-learner - 3 months ago 8
Ajax Question

How can I add to an AJAX array result

I have an AJAX request where I want to add more properties to the returned AJAX result. Any help would be great

Here is my AJAX request code:

var form_data = {};

$.ajax({
type: "GET",
url: "../../../sample_data/chart1.json",
data: form_data,

success: function( response) {
var result = $(data);
console.log(result.datasets.push(style));
var ctx = document.getElementById("chart_div_won").getContext("2d");
var options = {
responsive: true,
maintainAspectRatio: true,
pointDotRadius: 5,
showXLabels: 5,
};

var myLineChart = new Chart(ctx).LineAlt(response, options);


},
error: function() {
$('div#chart-container').html('<div class="notification-body"><p class="notification-heading">Loading error...</p><p class="notification-description">Unfortunatley for some reason visual data failed to load.</p></div>');
},
dataType: "json",
contentType: "application/json; charset=utf-8",
});


Which returns the following data:

{
"labels":[
"1 Feb",
"8 Feb",
"15 Feb",
"22 Feb",
"29 Feb",
"7 Mar",
"14 Mar",
"21 Mar",
"28 Mar",
"4 Apr",
"11 Apr",
"18 Apr",
"25 Apr"
],
"datasets":[
{

"data":[
77,
55,
40,
65,
59,
80,
81,
56,
55,
65,
59,
80,
75
]
}
]
}


My question is I want to add/push into the returned 'datasets' array the following (at 'data:' level):

fillColor:"rgba(253,0,20,0.2)",
strokeColor:"rgba(253,0,20,1)",
pointColor:"#fff",
pointStrokeColor:"rgba(253,0,20,1)",
pointHighlightFill:"#fff",
pointHighlightStroke:"rgba(253,0,20,1)"


Is this possible and how?

Answer

The returned data becomes a regular Javascript object. You can add properties to the desired level with regular assignments:

res.datasets[0].fillColor = "rgba(253,0,20,0.2)";
res.datasets[0].strokeColor = "rgba(253,0,20,1)";

and so on.