2

I'm populating an array nodevalues with objects. It looks like this:

nodevalues.push({id: this.id, left: left, right: right});

This line is inside a $.each() iterator which iterates over some li nodes and also calculates the left and right values.

So I have an array with several objects who all look the same:screen dump chrome console

Is it possible to serialize this array to an url string for database storage using jQuery.post()?

Calling $(nodevalues).serialize() returns nothing and $.param(nodevalues) returns undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined...

9
  • 3
    Never do $(this).attr('id'). "this" is .each() is the DOM element -> this.id Commented Nov 30, 2011 at 11:15
  • @Didier G I'm not sure I understand your comment. $(this) in jquery is this[0] in javascript. You should ALWAYS use $(this).attr('id') in jquery. Commented Nov 30, 2011 at 11:16
  • @DidierG. I think you're missing the point of my post. My question is how to serialize an array of objects. The code you mention works like it should. Commented Nov 30, 2011 at 11:18
  • @ZacL. It's just a comment, not an answer to your problem, i'm aware of that. Commented Nov 30, 2011 at 11:23
  • @ThomasClayson. Check this example Commented Nov 30, 2011 at 11:24

3 Answers 3

12

jQuery.param() might do what you want

var dataString = jQuery.param(nodevalues);

It seems that param only works on objects, not arrays.

If you wrap your array in an object it works fine:

var nodevalues = [];

nodevalues.push({id: "node1", left: 1, right: 20});
nodevalues.push({id: "node2", left: 2, right: 10});
nodevalues.push({id: "node3", left: 3, right: 30});
nodevalues.push({id: "node4", left: 4, right: 40});

var data = { data: nodevalues };

alert($.param(data));

http://jsfiddle.net/4NELt/

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! You just made my day!
1

You could use the stringify function from the JSON library.

Comments

0

you can supply the data as second argument to jquery.post()

jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] );

jquery will serialize it for you.

1 Comment

You mean like this? $.post('ajax/changenode.php', nodevalues); Results in: Form data: undefined:undefined undefined:undefined undefined:undefined undefined:undefined undefined:undefined undefined:undefined undefined:undefined undefined:undefined undefined:undefined undefined:undefined Doesn't do the job!

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.