Search code examples
jqueryajaxformmalsup-ajax-form

How to submit comma delimited on multiple select using jquery ajax


I was trying to figure it out to submit a comma delimited value on a multiple select. Here's my sample code:

$( 'myform').ajaxForm({
    beforeSubmit: function(data) {
        var queryString = compressParam($.param(data));
        //console.log('params:'+queryString);
    },
    success: function(response){
        $('div').html(response);
    }
    error: function(a,e,et) { alert('ERROR 101: '+et); }
});

function compressParam(data) {
    data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
    return /([^&=]+=).*?&\1/.test(data) ? compressParam(data) : data;
}

I found a function that will combine same parameter. Works like a charm but don't know how to submit as data or do you have other idea how to submit a multiple parameter in comma delimited using ajaxForm?


Solution

  • I know this is a late response to my question but hopefully helps anyone just like me looking to solve this problem again and again. Kudos to John Resig for the code and explanation.

    function compress(data){
        var q = {}, ret = "";
        data.replace(/([^=&]+)=([^&]*)/g, function(m, key, value){
            q[key] = (q[key] ? q[key] + "," : "") + value;
        });
        for ( var key in q )
            ret = (ret ? ret + "&" : "") + key + "=" + q[key];
        return ret;
    }