Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  10] [ 6]  / answers: 1 / hits: 16989  / 13 Years ago, wed, february 22, 2012, 12:00:00

I've already read those questions but none of them answer to my need:





(the latest one said just add hard-coded quotes ie [''] but I can't do this, I'm calling a function that returns an Array)



So here's my code (note that the problem lies to the empty array new Array()):



function AjaxSend() {
$.ajax({
url: '/json/myurl/',
type: 'POST',
dataType: 'jsonp',
data : { 'tab':new Array() },
context: this,
success: function (data) {
if (data.success) {
console.log('ok');
}
else {
console.log('error');
}
}
});
}


Simple eh?
Here's my Php code:



echo '_POST='.var_export($_POST,true).n;


And here's the result:



_POST=array (
)
jQuery1710713708313414827_1329923973282(...)


If I change the empty Array by a non-empty, i.e.:



'tab':new Array({ 't':'u' },{ 'v':'w' })


The result is:



_POST=array (
'tab' =>
array (
0 =>
array (
't' => 'u',
),
1 =>
array (
'v' => 'w',
),
),
)
jQuery1710640656704781577_1329923761425(...)


So this clearly means that when there's an empty Array() to be sent, it is ignored, and it's not added to the POST variables.



Am I missing something?



PS: my jQuery version is from the latest google CDN i.e.:



http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js



and



http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js



I want the array to be sent, even if it's empty (= send [])!
Any solution? Any idea? I've already tried to add this option traditional: true without success.


More From » jquery

 Answers
18

The problem is that you can't really send empty array. Have you tried to send an empty array manually? How would that uri look (note that it's the same reasoning for POST)?



/path?arr[]


This would result in a $_GET like this:



array (
'arr' => array (
0 => ''
)
)


That's not really an empty array, is it? It's an array with a single element of an empty string. So what jQuery does, and I would agree that this is the correct way of handling it, is to not send anything at all.



This is actually really simple for you to check on the server. Just add an extra check whether the parameter exists or not, i.e:



$tabs = array();
if(isset($_POST['tab'])) {
$tabs = $_POST['tab'];
}

[#87297] Tuesday, February 21, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eliasf

Total Points: 703
Total Questions: 97
Total Answers: 129

Location: Chad
Member since Tue, Apr 27, 2021
3 Years ago
;