After searching extensively on both SO and Google, I have not been able to find a solution to my issue and I'm feeling stuck. The problem arises when I try to parse an array returned from a PHP page using echo json_encode()
. Here is what the array looks like:
[" "," "," "," "," ",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]
Each time I attempt to use JSON.parse(), I encounter the error
Unexpected token o at Object.parse (native)
, and with the jQuery alternative, I receive Unexpected token o at Function.parse (native)
.
Oddly enough, simply assigning it to the $scope
allows me to display it on the page. So, where am I going wrong and how can I rectify this?
Below is a snippet of my controller code:
function myController($scope, memberFactory) {
response = memberFactory.getMonth("2013-08-01 06:30:00");
var monthDays = $.parseJSON(response);
var dates = [];
for (var i = 0; i < monthDays.length; i++) {
if (i % 7 == 0) dates.push([]);
dates[dates.length - 1].push(monthDays[i]);
}
$scope.dates = dates;
}
This is the relevant service method implementation:
obj.getMonth = function (date) {
var month = $q.defer();
$http.get('getMonth.php?date=' + date)
.success(function (data, status, headers, config) {
month.resolve(data);
});
return month.promise;
}
And here's the corresponding PHP code:
<?php
$daysOfMonth=[ " ", " ", " ", " ", " ",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31];
echo json_encode($daysOfMonth);
?>
Attempted Solutions
Upon checking the typeof
of the response which reveals it as an Object, I tried various solutions mentioned in answers such as
var monthDays = Array.prototype.slice.call(response)
and var monthDays = $.map(response, function (value, key) { return value; });
. Additionally, I experimented with JSON.stringify()
but only ended up with {}
as the output.
This issue has become quite frustrating, and I truly need some guidance in the right direction.
Update
I suspect that the problem lies within my usage of $q.defer()
. As a result, I made adjustments to the getMonth method:
obj.getMonth = function (date) {
var month = $q.defer();
$http.get('getMonth.php?date=' + date)
.success(function (data, status, headers, config) {
month.resolve(data);
console.log("data " + data[0]);
console.log("resolved " + month.promise[0]);
});
return month.promise;
}
Now, upon logging console.log("data " + data[0]);
, I correctly see '1' displayed. However, when I log console.log(month)
, I receive '[object Object]', and for console.log(month.promise)
as well as console.log(month.promise[0])
, I get 'undefined'.