Home > php > jquery 1.2 and ajax parameter serialization – passing a php array

jquery 1.2 and ajax parameter serialization – passing a php array

php 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!

Advertisements
Categories: php
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: