最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sending HTML Form Multiple <select> box via POST request with AJAX? - Stack Overflow

programmeradmin1浏览0评论

I have an html form with a multiple select box. I can't figure out how to send the values to my php application with AJAX via a post request. It works just fine if I use a GET request and use a single select box but not when I use a multiple select box. The idea is for users to hold control (or command with mac) and select one or more categories. Depending on which categories are selected will determine what other form options will be displayed using AJAX. The select box looks like this:

Edit: SOLVED

<select multiple name="categories[]" onclick="sendCategories(this)">
<option value="0">Category 1</option>
<option value="1">Category 2</option>
<option value="2">Category 3</option>
</select>

My javascript function looks like this:

function sendCategories(sel){
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("my_div").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST",".php",true);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var values = $(sel).serialize();
    xmlhttp.send(values);
}

I have an html form with a multiple select box. I can't figure out how to send the values to my php application with AJAX via a post request. It works just fine if I use a GET request and use a single select box but not when I use a multiple select box. The idea is for users to hold control (or command with mac) and select one or more categories. Depending on which categories are selected will determine what other form options will be displayed using AJAX. The select box looks like this:

Edit: SOLVED

<select multiple name="categories[]" onclick="sendCategories(this)">
<option value="0">Category 1</option>
<option value="1">Category 2</option>
<option value="2">Category 3</option>
</select>

My javascript function looks like this:

function sendCategories(sel){
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("my_div").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST","http://www.mysite.com/update_categories.php",true);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var values = $(sel).serialize();
    xmlhttp.send(values);
}
Share Improve this question edited Feb 8, 2013 at 19:32 denvdancsk asked Feb 8, 2013 at 5:12 denvdancskdenvdancsk 3,0532 gold badges27 silver badges41 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 7

You'll have to generate the query string to send in the POST on your own. Here's the HTML tag to use:

<select multiple name="categories[]" onchange="sendCategories(this);">

And the Javascript function:

function sendCategories(sel){
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            document.getElementById("my_div").innerHTML = xmlhttp.responseText;
        }
    };
    xmlhttp.open("POST","http://www.mysite.com/update_categories.php",true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    var values = [], i, j, cur;
    for (i = 0, j = sel.options.length; i < j; i++) {
        cur = sel.options[i];
        if (cur.selected) {
            values.push(encodeURIComponent(cur.value));
        }
    }
    if (values.length) {
        values = encodeURIComponent(sel.name) + "=" + values.join("&" + encodeURIComponent(sel.name) + "=");
    } else {
        values = null;
    }

    xmlhttp.send(values);
}

Note that I changed the event from onclick to onchange, but that's really up to you whether you want this function to run when the element is clicked, or its value is truly changed...it can reduce some unnecessary calls.

This should generate a querystring that is normally used for sending values for a <select> with multiple options selected.

Here's a jsFiddle that demonstrates how the querystring is being generated here: http://jsfiddle.net/kKWQM/

You can do something like this,

<select multiple name="categories[]" onclick="sendCategories(this)">

And Make AJAX using JQuery,

function sendCategories(sel){
    var values = $(select).serialize();
    console.log (values);       // See if you get the serialized data in console.

    $.ajax({
        type: 'POST',
        url: "http://www.mysite.com/update_categories.php"
        data: values,
        success: function (data) {
            document.getElementById("my_div").innerHTML = data;
        }
    });
}

And FYI, Netscape event binding model is deprecated, you could use the cross browser event binding like this

You can implement the solution however you would like using JS string and array functions. Effectively, the string you need to send to Apache should contain a pattern like:

xxx[]=a&xxx[]=b&xxx[]=c

where the SELECT element's name is xxx[] in your form and a, b, and c are three values the user selected.

So yes, you are repeating a key name as many times as the user selected a different option in the SELECT.

In JS you can use an array of selected options:

selected_options.join("&xxx[]=") to produce that pattern.

jQuery should make this easier for you. Calling .val() on a wrapped select returns an array of the selected values. You just have to post these to the server:

HTML:

<html>
    <body>
        <form>
            <select name="mySelect" multiple="on">
                <option value="1">Uno</option>
                <option value="2">Dos</option>
                <option value="3">Tres</option>
            </select>
        </form>
        <input id="submitButton" type="button" value="Click To Submit"/>
    </body>
</html>

JavaScript:

$(function() {
    $('#submitButton').click(function() {
        var valuesArray = $('select[name=mySelect]').val()
        $.ajax({
            type: 'POST',
            url: '/path/to/php', // your php url would go here
            data: { mySelect: valuesArray }
        }).done(function(msg) {
            // parse response from msg
        });
    });
});
发布评论

评论列表(0)

  1. 暂无评论