6

I have a object in Javascript that I am trying to AJAX POST to a PHP script. Everything worked in jQuery 1.4.1 but now in 1.4.4 or above all empty arrays or empty objects arrive as a string(0) which is incorrect.

JS:

$(document).ready(function() {
var obj = {};
obj.one = [];
obj.two = {};
obj.three = [];
obj.three.push('one');
obj.three.push('two');
obj.three.push('three');
obj.four = "onetwothree";

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data: obj,
    success: function(data) {
        alert(data);
    },
});
});

PHP:

<?php
var_dump($_POST);
?>

RESPONSE:

array(4) {
  ["one"]=> string(0) ""
  ["two"]=> string(0) ""
  ["three"]=> array(3) {
    [0]=> string(3) "one"
    [1]=> string(3) "two"
    [2]=> string(5) "three"
  }
  ["four"]=> string(11) "onetwothree"
}

In version 1.4.1 it would just NOT send ["one"] or ["two"], but now in the newer versions, the fact that it arrives as a string throws off the whole application. Is there anything I can do so that an empty array ([]) arrives in PHP as an empty array ([]) and same with JavaScript objects?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Nathan Firth
  • 61
  • 1
  • 2
  • 1
    Hi. Did you find any solution to this problem? I am also interested in this. Before I saw your post I already posted [this](http://stackoverflow.com/questions/9179473/why-jquery-ajax-does-not-serialize-my-object). – p.matsinopoulos Feb 08 '12 at 07:34

2 Answers2

3

try applying JSON.stringify to the parameters passed

 data: JSON.stringify ( obj ),

Note you'll likely want to include the contentType: "application/json" option to prompt server side to process the data correctly.

quoting : Why jQuery ajax does not serialize my object?

traditional: true is completely wrong, since it can never handle object hierarchies. What you get instead is: ...&key=[object Object], which is javascript's toString() default result for all objects.

Community
  • 1
  • 1
Aroha Labs
  • 162
  • 9
2

Try setting the traditional option to true:

$.ajax({
    type: 'POST',
    traditional: true,
    url: 'ajax.php',
    data: obj,
    success: function(data) {
        alert(data);
    }
});

Have a look at the data and traditional options of the newer API.

And remove the extra comma from after the success callback if you want things to work in IE7.

karim79
  • 339,989
  • 67
  • 413
  • 406
  • Thank you Karim79, I tried switching the traditional to true but the empty array and object still came across as a string(0) but now my nested array became [object Object]. – Nathan Firth Mar 16 '11 at 17:18