Ash
Ash

Reputation: 444

working with PHP array in javascript

building a countdown to a date that is based on a variable integer that will indicate how many days are left. Im trying to return the result as the difference in unix time between the current time and the future time in an array including days, hours, minutes, seconds. All seems to work fine however instead of an array it seems to return the results as a string.

Can anyone see what is wrong with my markup here? Or do i need to do another conversion within javascript?

PHP

$zTimeCombined = array($days_remaining, $hours_remaining, $minutes_remaining, $seconds_remaining);
echo json_encode($zTimeCombined);

How im accessing the "array" in JS (within a GET success function)

var zDays = results[0];
var zHours = results[1];
var zMinutes = results[2];
var zSeconds = results[3];

edit:

possible duplicate of this question (use php array in javascript?), however the answers were not as succinct and were not as simple as was needed here. Id say this question is really very basic but will be handy for non PHP users like myself

Upvotes: 0

Views: 40

Answers (1)

Tushar
Tushar

Reputation: 87203

The response you're getting from the AJAX is in string format, not in JSON.

To convert it to json format use JSON.parse()

The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing.

var result = JSON.parse(response);

Upvotes: 1

Related Questions