Reputation: 11
Hi guys i am new to jQuery and I have encountered this type of problem,
I am trying to create an array from jquery to pass it on to php controller (CI).
Sample HTML
<input type="text" acc_id="5" class="input" />
<input type="text" acc_id="10" class="input" />
<input type="text" acc_id="15" class="input" />
<input type="text" acc_id="20" class="input" />
Javascript
$('#save').click(function(){
var arrayVal = [];
$('.input').each(function(key, value){
var id = $(this).attr('acc_id');
var inputValue = $(this).val();
arrayVal[id] = inputValue;
});
$.ajax({
url: siteurl + '/sample_save',
type: 'POST',
dataType: 'json',
data: {'accounts' : arrayVal},
success: function(data) {}
});
});
Here is my response in Php
Array
(
[array] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] => value 1
[6] =>
[7] =>
[8] =>
[9] =>
[10] => value 2
[11] =>
[12] =>
[13] =>
[14] =>
[15] => value 3
[16] =>
[17] =>
[18] =>
[19] =>
[20] => value 4
)
)
Notice that the response gave me the key from 0 - 20.
But I want it like this :
Array
(
[array] => Array
(
[5] => value 1
[10] => value 2
[15] => value 3
[20] => value 4
)
)
I can somehow make it work in Php, but I want to correct this stuff through my javascript code. Sorry for my bad english :)
Upvotes: 1
Views: 80
Reputation: 264
You are right. This is clearly something that should be solved within your JS code.
jQuery has a native serialize function for forms. See here for an example to use it, that may be a better approach to your problem.
Also please be aware that javaScript does not have real associative arrays. You are only able to use objects in a similar way as you know associative arrays from other languages (like PHP).
Edit
Ok, in that case your code is ok. You would just need to use an object instead of an array.
Just use:
var arrayVal = {};
Instead of:
var arrayVal = [];
Upvotes: 2
Reputation: 466
//You can use this function and it's remove to empty array
<?php
array_filter($array);
?>
http://www.php.net/manual/en/function.array-filter.php
Upvotes: 0
Reputation: 1438
You could use: array_filter
array_filter($array);
There is a previous question covering the subject: Remove empty array elements
Upvotes: 1
Reputation: 23816
Try this code in your php file:
$test = array('','',1,2,'',3); //your array
foreach($test as $i=>$k)
{
if(empty($k))
{
unset($test[$i]);
}
}
print_r($test);
Output:
Array ( [2] => 1 [3] => 2 [5] => 3 )
Or you can use filter
Code:
$test = array('','',1,2,'',3);
$test = array_filter($test);
print_r($test);
Upvotes: 1