David
David

Reputation: 2232

php output to javascript array with json

I have a project that spits out a json_encode string of date items.

Looks like this:

<input type="hidden" class="avail_dates" data-id='["12-9-2014", "7-9-2014"]' />

I've tried different things, but because of this project it has to be there, I can't simply do an ajax call and return the json_encode stuff.

So, I need to get the data-id into a javascript array somehow for a datePicker.

Using this works, but it's hard coded:

var availableDates = ["9-9-2014","5-9-2014","7-9-2014"];

Using this doesn't do anything:

var availableDatesArray = jQuery('.avail_dates').attr('data-id'); 
//alerting gives ["9-9-2014","5-9-2014","7-9-2014"]

Is there a way to convert the string into an array that works?

I can change the way the data gets into the data-id, or the way jquery interacts with the element, but I can't add a separate ajax query just for this, it has to come from that data-id.

var availableDates = ["9-9-2014","5-9-2014","7-9-2014"];    

function dates(date){
    dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
    console.log(dmy+' : '+(jQuery.inArray(dmy, availableDates)));
    if (jQuery.inArray(dmy, availableDates) != -1) {
        return [true, "","Available"];
    } 
    else {
        return [false,"","unAvailable"];
    }           
    return;
}

jQuery('#myDates').datepicker({
changeYear: true,
maxDate: '0',
changeMonth: true,
dateFormat: "mm/dd/yy",
yearRange: '2014:2030',
beforeShowDay: dates,       
onSelect: function(dateText) {

}
});

EDIT: Should have mention I already tried json.parse. It gives an "unexpected number" error.

EDIT 2: I added the function I'm trying to pass the data too for jQuery datePicker.

Upvotes: 1

Views: 80

Answers (3)

Anthony Martin
Anthony Martin

Reputation: 678

Unless I'm misunderstanding your question, you just need to use JSON.parse:

var availableDatesArray = JSON.parse(jQuery('.avail_dates').attr('data-id'));

jQuery('.avail_dates').attr('data-id') is just going to return a string (the contents of the 'data-id' attribute. JSON.parse will actually create a JavaScript object from it.

Upvotes: 0

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60527

Just use JSON.parse.

Example:

var availableDatesArray = JSON.parse(jQuery('.avail_dates').attr('data-id'));

If you prefer, you can use jQuery.parseJSON.

Example:

var availableDatesArray = jQuery.parseJSON(jQuery('.avail_dates').attr('data-id'));

This is actually how jQuery itself parses JSON in AJAX responses.

Upvotes: 2

Kevin
Kevin

Reputation: 41885

Yes you can, use JSON.parse. Like this:

var availableDatesArray = jQuery('.avail_dates').attr('data-id'); 
availableDatesArray = JSON.parse(availableDatesArray);
console.log(availableDatesArray);

Or much better suggestion of @charlie

var availableDatesArray = jQuery('.avail_dates').data('id'); // much better

Upvotes: 2

Related Questions