views:

785

answers:

1

I am trying to post a javascript array to a php page. The array has to be associative. My structure looks like this:

<input id="test" value="1" class="settings" />
<input id="test1" value="2" class="settings" />

When I create the array it is:

var myArray = new Array();

$(".setttings").each(function(){
     myArray[$(this).attr("id")] = $(this).val();
});

Now when I post that data I am just doing:

$.ajax({
 type: "POST",
 url: 'post.php",
 data: "settings="+myArray,
});

The problem is that in firebug if I look at the post for settings it is empty. I need the array passed like this because I am going to take each of those settings into php and serialize them and insert them into a field in a database. That way I can pull the settings back out and unserialize to repopulate those fields. Any ideas how I can do this?

+2  A: 

I would recommend two changes.

First, since you want an associative array in PHP, you should use an Object, not an Array in Javascript:

var myObject = new Object();

$(".setttings").each(function(){
    myObject[$(this).attr("id")] = $(this).val();
});

Next, you want to pass it to the data section a little differently:

$.ajax({
    type: "POST",
    url: "post.php",
    data: {
        settings: $.param(myObject)
    }
});

The important part is the $.param since that converts the object into a series of parameters (suitable for a query_string).

The final thing you need to do on the server to get it working is parse it in PHP:

parse_str($_POST['settings'], $settings);

Now you can access everything in the $settings variable just like you could in JavaScript.

$settings['id'] = "value";
Doug Neiner
thanks that works perfectly
ngreenwood6
actually I have anothe question if I want to add an id to the query how would I do that. for example id=1
ngreenwood6
Do you want to add the id to the whole request? If so, just put it along side the `settings` parameter like this: `data: { settings: ... , id: 1}` Did I understand your question correctly?
Doug Neiner
thankss that worked perfectly. i was trying to add it outside of that like the way you normally would but now i understand. thanks for your time
ngreenwood6