2

I have this JavaScript source:

var mydata = [];

$('.myManyElements').each(function() {
    mydata.push({
        'id': $(this).data('id'),
        'quantity': $(this).data('quantity'),
        'price': $(this).data('price'),
        'price_total': Order.getTotalPrice()
    });
});

$.post('/archive', mydata, function(data) {
    if(data.success) {
        alert(data.response);
    } else {
        alert('Custom Error Report!');
    }
}, 'json');

And in my /archive request I have this sample PHP:

echo json_encode(array(
    'success' => true,
    'response' => print_r($_POST, true),
));

When I check Firebug's NET panel for XHR, in the POST tab it says that I've sent this:

undefined=

When I get my response in my alert it outputs:

Array
(
    [undefined] => 
)

Why can't I send an array of data for my POST request?

5
  • 1
    How did you expect it to be sent? There's no standard way to send an array of objects...
    – Ry-
    Nov 7, 2012 at 0:29
  • jQuery can achive this as I can recall...
    – user1386320
    Nov 7, 2012 at 0:32
  • as it says in the jquery docs: If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). — see at: api.jquery.com/jQuery.ajax
    – user1386320
    Nov 7, 2012 at 0:34
  • Note how it says "based on the value of the traditional setting"? Set that to true :) (It's not on by default, probably because that's an incorrect serialization.)
    – Ry-
    Nov 7, 2012 at 0:36
  • @minitech please read my last comment, before this one
    – user1386320
    Nov 7, 2012 at 0:36

1 Answer 1

1

Try

$.post('/archive', {'mydata': JSON.stringify(mydata)}, function(data)
3
  • well this works perfectly like in a Dream... this will do the job :) thanks! accepting after a few min's!
    – user1386320
    Nov 7, 2012 at 0:38
  • Why are you using JSON.stringify? It should work just as {mydata: mydata}.
    – gen_Eric
    Nov 7, 2012 at 1:02
  • Because that way you get it as JSON on the backend, and my understanding is that this is what the OP is about.. Nov 7, 2012 at 3:15

Your Answer

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