Logo Background RSS

Javascript: Serialize JS array into PHP

  • Written by vinuvinu 2 Comments2 Comments Comments
    Last Updated: May 19th, 2006

    Here’s a JavaScript function that serializes a JavaScript array into a form that PHP can later unserialize:

    function js_array_to_php_array (a)
    // This converts a javascript array to a string in PHP serialized format.
    // This is useful for passing arrays to PHP. On the PHP side you can
    // unserialize this string from a cookie or request variable. For example,
    // assuming you used javascript to set a cookie called "php_array"
    // to the value of a javascript array then you can restore the cookie
    // from PHP like this:
    // <?php
    // session_start();
    // $my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
    // print_r ($my_array);
    // ?>
    // This automatically converts both keys and values to strings.
    // The return string is not URL escaped, so you must call the
    // Javascript “escape()” function before you pass this string to PHP.
    {
    var a_php = “”;
    var total = 0;
    for (var key in a)
    {
    total;
    a_php = a_php “s:”
    String(key).length “:\”" String(key) “\”;s:”
    String(a[key]).length “:\”" String(a[key]) “\”;”;
    }
    a_php = “a:” total “:{” a_php “}”;
    return a_php;
    }

    Read the article for more details on this function’s usage.

    via Tucows Farm: The Tucows Developers’ Hangout :: Source Code

    Bookmark and share:
    • del.icio.us
    • Digg
    • StumbleUpon
    • BlinkList
    • blogmarks
    • Furl
    • Slashdot
    • Spurl
    • Technorati
    • YahooMyWeb
    • description
    • Facebook
    • Google
    • Live
    • Ma.gnolia
    • NewsVine
    • Reddit
    • TwitThis

Advertisement

  1. #1 andot
    June 20th, 2006 at 11:50 am
    Post ReplyPost Reply
  2. #2 xorax
    September 19th, 2006 at 5:08 pm

    if you want I create 2 function for serialize and unserialize in javascript. my functions is not class and they are very small :

    http://www.xorax.info/blog/programmation/40-javascript-serialize-php.html

    Post ReplyPost Reply
Leave a Comment