Click or scroll down Circle me on Google+ Fork me on GitHub Follow me on Twitter Ask me on Stack Overflow Gild me on Reddit Code Ninja, Entrepreneur, Idiot ChalkHQ — consulting, prototyping, mentoring HighF.in — resolve innefficiencies in your startup's workflow DearDrum.org — online open-mic / creative space The Dirac Equation (click to WikiPedia) A maxim Sun Tzu references in his magnum opus The Art of War

If you know the enemy and know yourself, you need not fear the result of a hundred battles.
If you know yourself but not the enemy, for every victory gained you will also suffer a defeat.
If you know neither the enemy nor yourself, you will succumb in every battle.
Fork me on GitHub

Tags

actionscript ad-hoc networks Adobe AIR anonymous Apple array Browsing convert Debugger Error Facebook file permissions Flash Flex fonts function future Google Google Plus grid hackers html javascript logs loop network p2p php privacy regexp Security Server social ssl technology terminal time Twitter upgrade Web 2.0 Web 3.0 Web 4.0 Web 5.0 wordpress

Featured Posts

  • Javascript: Undefined parameters
  • The Web, A Look Forward
  • Let Postfix send mail through your Gmail Account – Snow Leopard
  • Archives

  • April 2013
  • December 2011
  • July 2011
  • June 2011
  • March 2011
  • February 2011
  • January 2011
  • November 2010
  • October 2010
  • September 2010
  • July 2010
  • May 2010
  • Categories

  • Code
  • Design
  • Opinion
  • Security
  • Tools
  • Uncategorized
  • Passing a Multi-dimensional Array Between Javascript And Php.

    Passing data between client and server is pretty straight forward, we use HTML structured forms and AJAX calls to put data up, and echo/print methods to bring it down. The data types transmitted are usually strings and numbers. Unfortunately Javascript and Php don't have built in conventions for you to pass arrays or objects between one another. This article shows you how to pass an array from server to client, and then from client to server. Looking around Google there are a number of other developers who've found ways to do this, but the methods they use tend to limit the number of tiers in the array being passed from client to server, use up unwarranted resources for multiple form items and variables to hold each array item, and limit your overall control of the task. This method focuses on getting your data from an array to a string and back again using 1 hidden input, 1 variable, and allows you to have as many tiers to yourarray as you have characters to use as delimiters.

    Passing an array from Php to Javascript is quite simple, because our array starts in Php, and Php is parsed first by the server. The whole process can be done in one block of code. Loop through the array in Php echoing it into Javascript code, which when parsed by the clients browser will generate a Javascript array.

    Say we have a Php array:

     array("model" => "Prophecy Les Paul Ex", "neck" => "Mahogany"),
         "Fender" => array("model" => "Lite Ash Telecaster", "neck" => "Birdseye Maple" ),
         "Washburn" => array("model" => "Idol WI15", "neck" => "Rosewood")
         );
    ?>

    On the page to be served add the following Php which will loop through the arraygenerating the Javascript code to re-create the array on the client-side. You may also want to wrap the generated Javascript in a function if you don't want thearray to be generated on page load, or want to be able to refresh/reset the array:

     
    var Guitars = new Array();

    That's it.

    Now if you want to pass the array back from Javascript to Php it's a bit more complex. We'll use the Javascript array Guitars that we just created. First we'll need an HTML form:

     
    <form method="post" action="/example.php">
    </form>

    Note the use of both id and name. Name will be assigned to the posted variables we'll need to pick up on the server, as for referring to the input in Javascript you could use the getElementByName(); but I find it to be less reliable and harder to keep track of which elements have a name and which have an id. Using id throughout your application is more uniform.

    Anyway remember we still have the array Guitars from before, now we need to write the function called by the Submit button:

     
    function fn_SubmitForm() {
         arr_Guitars = document.getElementById('arr_Guitars'); //get the element
         arr_Guitars.value = ""; //make sure the value is empty in case the user double clicked
         //loop through the array Guitars concatenating the values into a formatted string
         for(var i in Guitars) {
              arr_Guitars.value += Guitars[i]['model'] + ':' + Guitars[i]['neck'];
              /*
              //Nest this for(){} loop within itself for every tier of your array
              //for each nesting move the delimiters over, if you used a ; next, the
              //nested loop would look like the following:
              for(var ii in Guitars[i]['avail_colours']) {
              arr_Guitars.value += Guitars[i]['avail_colours'][ii]['colour'] + ';';
              }
    
              //to add more array items to this Guitar[i] replace the last delimiter of
              //the output of the last nested loop with that of the tier above it
              arr_Guitars.value = arr_Guitars.value.replace(/;$/,":");
              //or if you're finished with this Guitar[i] remove it
              arr_Guitars.value = arr_Guitars.value.repalce(/;$/,"");
              */
    
              arr_Guitars.value += ',';
              //the preceding line could be added to the end of the first line of the
              //loop if you're only passing a two tiered array
         }
         //remove the last , from the formatted string
         arr_Guitars.value = arr_Guitars.value.replace(/,$/,"");
    
         document.form_Decision.submit();  //submit the form
    }

    Note the formatted string uses the following structure model:neck,model:neck. Also for those new to regular expressions the expression used in the value.replace(); method in plain english means "the comma before the end of the string". Forward slashes mark the beginning and end of the expression, the comma represents a comma and the dollar sign represents the end of the string being analyzed.

    Now on the server:

    <?php
    //get the formatted string
    $Guitars = mysql_real_escape_string($_POST["arr_Guitars"]);
    //make sure the array being passed is not empty
    if($Guitars != ""){
         //Php's explode function breaks apart the string into an array of strings based on the delimiter
         //Here we break apart the string into it's sub-strings <em>model:neck</em>
         $Guitars = explode(",", $Guitars);
    
         //for each exploded array item separate the model and neck values and elaborate the array
         foreach($Guitars as $key=>$row) {
              $row = explode(":",$row);
              $Guitars[$key] = array(
                   "model" => $row[0],
                   "neck" => $row[1]
                   );
         }
    }
    ?>

    And that's it, you now have $Guitars again on the server. This method of passing arrays is extensible in that each level of the array can have unlimited values, and the arrayitself can have unlimited dimensions. For every dimension added to the array you need a new delimiter and you have to run a variation on the second foreach() statement above based on that delimiter.

     

    Category: Code

    Tagged: , ,