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?

1
  • 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. Commented Feb 8, 2012 at 7:34

2 Answers 2

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.

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

Comments

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.

1 Comment

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].

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.