Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.ajax() omits "empty" object attributes

Tags:

jquery

I have the following JS object:

var data_test = { foo: [], bar: [ 'baz' ] };

When I submit this object via jQuery.ajax():

$.ajax({
    url: "test.php",
    type: "POST",
    data: data_test
});

It turns out only the bar array is sent, and not the foo one.

Proof: In test.php I simply var_dumped the $_REQUEST:

array(1) {
  ["bar"]=>
  array(1) {
    [0]=>
    string(3) "baz"
  }
}

Is it possible to force jQuery to also submit an empty object attribute? I need jQuery to send an EXACT copy of the data_test object, if it omits empty value that breaks my logic!

like image 694
Louis B. Avatar asked Feb 21 '13 10:02

Louis B.


1 Answers

A little (very) late to the game, but I wanted to point out that if your application is ready to accept JSON, you can send empty arrays using JSON.stringify:

var data_test = { foo: [], bar: [ 'baz' ] };

$.ajax({
    url: "test.php",
    type: "POST",
    data: JSON.stringify(data_test),
    contentType: 'application/json'
});

This should post the empty array. Beware that JSON.stringify is available starting from IE8, but you could always use json.js to fill this gap.

like image 70
enrique-ramirez Avatar answered Oct 15 '22 16:10

enrique-ramirez