Sep 19, 2012

Transfer array from PHP to jQuery

I wanted to transfer an array from server side PHP to client side jQuery in metadata, as following:
    ...

    $meta = metadata(array('invalid_chars' => $this->getUnwantedCharCodeArray()));
    return sprintf('<div class="token %s">%s</div>', $meta, $output);
    ...

While in this way what I got at client side is an object, which could not be used in method like $.inArray():

  $('.token').metadata().invalid_chars was an object like object { 0=35, 1=94....}, what I wanted was an array [35, 94...]

Tried .toArray() and $.makeArray(), wouldn't work....

Finally I found a solution: json_encode at the server side and parseJSON at the client side:

Server side:
    ...

    $meta = metadata(array('invalid_chars' => json_encode($this->getUnwantedCharCodeArray())));
    return sprintf('<div class="token %s">%s</div>', $meta, $output);
    ...

Client side:

    if ($.inArray(charCode, $.parseJSON($('.token').metadata().invalid_chars)) > -1 ) { ...