Ajax – Post Multiple Select Values

So this form is pretty basic, it has a select box (list box) filled with possible values. You can select all or some of the values and then submit it to the server via Ajax. The problem was when I grabbed the value from the select box I only got the last value selected, not each. Regardless of if I was using POST or GET I still had to build the parameter list since that’s how XMLHttpRequest works. So I looped through the list and tried using the same parameter name for each, then on the PHP end I had the same result — each parameter overwrote the previous one and I saw only the last result. It wasn’t until I stumbled upon this post that someone gave a decent suggestion, which was to put a [] at the end of each parameter name when building the query string and PHP would automatically interpret it as an array. Since his code was somewhat over complicated I thought I’d share my version of it:

test-utility.php

<html>
<head>
    <title>Test Utility</title>
    <script type="text/javascript" src="test-utility.js">	</script>
</head>
<body>
    <h1 align='center'>Test Utility</h1>

<center>

    <p style="width:450px; text-align:justify;<?php if($error) echo "color:red;" ?>">
        <?php if($error) { ?>
            <strong>Error:</strong> <?php echo $error; ?>
        <?php } ?>
    </p>

    <form name='frmTestUtility' id='frmTestUtility' method='post' action=''>
    <table cellpadding="2" cellspacing="2" border="0">
    <tr>
        <td>
            Listbox(s):<br><br>
            <div style="font-size:smaller">(Hold CTRL to<br>select multiple)</div>
        </td>
        <td align="center">
            <select name='listbox[]' id='listbox' multiple="multiple">
                <option value='123'>123</option>
                <option value='abc'>abc</option>
                <option value='alpha'>alpha</option>
                <option value='beta'>beta</option>
                <option value='gamma'>gamma</option>
            </select>
            <br>
            <input type="button" name="all" value="All" onClick='javascript:select_all();'>
            <input type="button" name="none" value="None" onClick='javascript:select_none();'>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="button" name="submit" onclick="javascript:run_queries();" value="Run SQL" />
        </td>
    </tr>
    </table>
    </form>

    <div id="ajax_results">
        &nbsp;
    </div>
    </center>
</body>
</html>

test-utility.js

 
function select_all() {
    var d = document.getElementById("listbox");
        for(var i=0;i<d.length;i++) {
            d.options[i].selected = "1";
        }
}

function select_none() {
    var d = document.getElementById("listbox");

    for(var i=0;i<d.length;i++) {
        d.options[i].selected = "";
    }
}

// Build the query string and submit it to the next page for processing
function run_queries() {
    var xmlhttp = "";
    var url = "";

    // For modern browsers
    if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();

    // for IE 5/6
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    //  Rebuild the array of selected option boxes
    lb = document.getElementById("listbox");
    for(var i=0; i < lb.length; i++) {
        if(lb[i].selected) {
            // Note the [] after the name
            url += "&lb[]=" + lb[i].value;
        }
    }

    xmlhttp.open("GET","test-utility-ajax.php?" + url, false);
    xmlhttp.send();

    if (xmlhttp.status == 200) {
        document.getElementById("ajax_results").innerHTML = xmlhttp.responseText;
    } else {
        return false;
    }

    return false;
}

test-utility-ajax.php

<?php
  // As you can see PHP displays it as an array
  if($_GET} print_r($_GET);
?>

Tags:

  • Del.icio.us
  • StumbleUpon
  • Reddit
  • Twitter
  • RSS

3 Responses to “Ajax – Post Multiple Select Values”

  1. Typhin says:

    I know it’s an old post, but I just recently stumbled across your blog. I’m just starting to learn PHP and stuff, so this article interested me. However, trying it out, I noticed a few problems with it.

    1: The variable “url” in run_queries() is never initialized, but then appended to, causing it to end up as “undefined&lb[]=…”
    2: The request string doesn’t have a question mark to separate the URL from the parameters.
    3: The request is sent using GET, but then test-utility-ajax.php checks POST. It should use _GET or _REQUEST to get those parameters.
    4: Two minor syntax errors, an extra /pre tag on test-utility:js:18 and a curly brace instead of parenthesis in test-utility-ajax.php:3.

    Still, very informative. Thank you for the article. It’s always enjoyable to learn new things. ^_^

  2. FettesPS says:

    Hey, thanks for the comment. You’re right, this is an old post, and I can’t remember what I was working on when I came up with it. This example was a real world scenario which was then stripped down and any business specific code removed, and a few extra layers of stuff such as Smarty. During that process a few things were missed or in the case of the tags just snuck their way in there. I’ve gone ahead and added your corrections.

  3. sanjay says:

    really works

Leave a Reply