Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery 1.4.4+ AJAX request - post empty array or object becomes string

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?

like image 794
Nathan Firth Avatar asked Mar 15 '11 23:03

Nathan Firth


People also ask

Is AJAX request GET or POST?

GET vs POST in AJAX callsUnless you are sending sensitive data to the server or calling scripts which are processing data on the server it is more common to use GET for AJAX calls. This is because when using XMLHttpRequest browsers implement POST as a two-step process (sending the headers first and then the data).

What does AJAX request return?

ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option.

What is processData in AJAX?

processData: It's default value is true. It is used to specify whether or not data sent with the request should be transformed into a query string.

How do I send a post request in AJAX?

Send Http POST request using ajax()In the options parameter, we have specified a type option as a POST, so ajax() method will send http POST request. Also, we have specified data option as a JSON object containing data which will be submitted to the server.


1 Answers

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.

like image 162
Aroha Labs Avatar answered Oct 06 '22 02:10

Aroha Labs