Saturday, May 21, 2011

10:26 AM
Suppose you have to send three values: element Id, row and column compounded in one URL parameter. That is simple, parameters can be concatenated and delimited with special character. But how to send multiple of these complex URL parameters? This post should give an answer.


First I will show example where you might need such functionality - Drag and drop table content with JavaScript. Table content is dynamically changed and after arrangement is finished, user should have option to save table content. JavaScript code in this post is used only for demo to prepare concatenated URL parameters.




After "Send query" button is clicked, send_query() function will collect values from drop down menus, prepare query string and send to the PHP page. Prepared query string will be displayed in the box below button.



function send_query()
{
    var selected_value;
    // reset query variable
    var query = '';
    // collect dropdown menus beneath DIV id=my_menu
    var menus = document.getElementById('my_menu').getElementsByTagName('select');
    // open loop through each dropdown element
    for (var i=0; i<menus.length; i++){
        // group 3 values to p parameter
        if (i % 3 == 0) query += '&p[]=';
        // set selected value and append to the query string
        selected_value = menus[i].options[menus[i].selectedIndex].text;
        query += selected_value + '_';
    }
    // replace _& with & and cut first '&' and last '_' character from query string
    query = query.replace(/_&/g,'&');
    query = query.substring(1, query.length-1);
    // write prepared query to the DIV element
    document.getElementById('prepared_query').innerHTML = query;
  // call multiple-parameters.php and show accepted parameters
  popbox = window.open('multiple-parameters.php?'+query,'Mypop','width=300,height=140');
}


PHP script will accept "p" parameters as many as needed. Because parameter name ends with [ ], PHP code implies array. In one PHP line you can accept array from _REQUEST object. Array members are strings like "4_1_3" and they should be detached (list / explode). Finally, variables $id, $row and $column are ready for printing or saving to the database.



// accept parameters (p is array)
$arr = $_REQUEST['p'];
// open loop through each array element
foreach ($arr as $p){
    // detach values from each parameter
    list($id, $row, $column) = explode('_', $p);
    // instead of print, you can store accepted parameteres to the database
    print "Id=$id Row=$row Column=$column<br/>";
}


Just for the note, you can have any number of concatenated values in one URL parameter, but this number should be followed with the same number of variables in list() function.

0 comments: