2

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.

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

It was the scope, I was using $_SESSION variables for the other $row values and had been storing other $_SESSION variables to cookies as well. Thanks for the catch!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.