Ligthers Ligthers - 1 year ago 80
Javascript Question

ajax result differ if it is placed inside a variable using javascript

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)

url: "ajax/month.php",
type: 'POST',
data: { telcos: telco, start: sdate, end: edate, regions: region},

success: function (dataofconfirm) {
var month = dataofconfirm;

In the ajax above (of course it was inside a javascript), when i tried to alert it this is the result

enter image description here

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

enter image description here

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)

enter image description here

This is whar the labels:months should look like
labels: ["August", "September", "October", "November"],

Answer Source

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

     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},
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download