jquery 1.2 and ajax parameter serialization – passing a php array
It just sucks when I miss the fine print in the documentation. Recently I’ve been working on a project that passes product parameters to a jquery $.ajax call. The parameters are variable, so I wanted to pass them back to the server in a PHP style array:
/process.php?ProductOption[color]=123&ProductOption[size]=455&ProductOption[edition]=711
This seems to work with jquery 1.3 and greater (http://api.jquery.com/jQuery.param/) but the system I’m on requires 1.2 for a few other dependencies. So the workaround I used for the problem of passing php style array query string components was as follows:
//static variables to pass to ajax call
var ajaxData = {
'ProductType' : $('#Type').val(),
};
//variable product options to pass back, all fields
//are wrapped in a <div id="ProductOptions"> for easy selection
$('#ProductOptions :input').each(function(){
if($(this).val().length) {
//the input field names are in PHP array style too: i.e.
//<input type="text" name="ProductOption[color]" value="444" />
var name = $(this).attr('name').replace(/.+\[([^\]]+)\]/, "$1");
ajaxData['ProductOption[' + name + ']'] = $(this).val();
}
});
$.ajax({
async: false,
url: '/admin/ctl_Process.php',
data: ajaxData,
success: function(data) {
//do something here...
}
});
Enjoy!