2

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 Answers 2

10

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";
Sign up to request clarification or add additional context in comments.

3 Comments

actually I have anothe question if I want to add an id to the query how would I do that. for example id=1
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?
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
3

Just a small update to Dougs answer.

data: {
        settings: $.param(myObject)
    }

can be changed to

data: myObject

The jQuery ajax function will automatically turn your object into a string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.