Josh Whitlow
Josh Whitlow

Reputation: 481

Pass PHP array into cookie and retrieve with jQuery

I've dug deep for this one and can't seem to locate the answer, most answers will show you how to set and retrieve cookies within a language, but not cross language.

I need to pass a php array into a cookie and then retrieve the contents on another page with jquery so that I can dynamically set the options on a dropdown menu. (For a bootstrap dropdown menu, not a standard select dropdown) I have echoed out the php array to confirm it is present and it is.

I am using the jquery cookie plugin.

PHP snippet:

while ($row = mysql_fetch_assoc($result)) {
   //Get Dropdown options
   $wnDropdown[] = '<li value=' . $row['id'] . '>' . $row['name'] . '</li>';
} //end while

            mysql_close();
        } //end inner if
    } //end else

    //Cookie needed
    setcookie("wnDropdown", json_encode($wnDropdown));

jQuery:

$(document).ready(function() {
    var result = JSON.parse($.cookie('wnDropdown'));
    alert(result);
}); 

The result alerted returns 'null'.

What am I missing?

If more information is needed, let me know.

Upvotes: 2

Views: 363

Answers (1)

Vinay
Vinay

Reputation: 7674

There are some points which i want you to check

  • Make sure cookie plugin is loaded , best to load it after jquery.
  • Now regarding whitespaces before setcookie , much of this depends on you buffering setting if you have output buffering on then you can put anything or echo wherever and wherever you want and cookie header will still be sent but if its "Off" any <script> <style> <html> in short anything that comes before your posted php code is likely to cause problems .Check in your php.ini output_buffering=value if value is not "Off" and rather some number then you are clear here ; note that whitespaces inside <?php ?> don't matter just display function like echo,print_r etc do if they come before setcookie().
  • Also check the scope of $wnDropdownmake sure it's global and exists with some value when you call setcookie.

Upvotes: 2

Related Questions