I have dataId
from checkbox values and I'm sending it using a GET AJAX request:
dataId = 1, 2, 16, 15, 17, 3, 14, 5, 9, 11;
URI = "<?php echo site_url('Terpasang/Update_Kebutuhan_ke_Terpasang')?>";
$.ajax({
url : URI,
type: "GET",
data: { "iddata": [dataId] },
dataType: "JSON",
});
In controller I am passing this data with code:
$iddata = array($_GET['iddata']);
$Countdata = count($iddata);
for($i = 0; $i <= $Countdata; $i++)
{
$data = array('id_perjal'=>$iddata[$i]); // this code can't generate id one by one like i wanna : 1, next 2, next 16 etc
$this->M_perjal_terpasang->save($data);
}
echo json_encode(array("status" => TRUE));
The issue is with how you build the array. You cannot set a variable equal to a comma list of values. If you check the code you'll see that dataId
only has a single value:
dataId = 1, 2, 16, 15, 17, 3, 14, 5, 9, 11;
data = {
"iddata": [dataId]
};
console.log(data);
To fix this define the dataId
as an array explicitly:
var dataId = [1, 2, 16, 15, 17, 3, 14, 5, 9, 11]; // note the [] wrapping the values
Then use it in the object you provide to data
:
data: { "iddata": dataId },
</div>
You need to first assign a variable your "dataId" then it need to pass dataId in your ajax function. Also you can see this success info in console log.
var dataId=[1,2,16,15,17,3,14,5,9,11];
URI = "<?php echo site_url('Terpasang/Update_Kebutuhan_ke_Terpasang')?>";
$.ajax({
url : URI,
type: "GET",
data: {"iddata":dataId},
dataType: "JSON",
success:function(res){
console.log(res);
}
});
You don't need to add in a array your $_GET['iddata']. If you want to type cast then simply add (array)$_GET['iddata']. If you add this $_GET['iddata'] in a array then you will get your count 1.
$iddata=$_GET['iddata'];
$Countdata=count($iddata);
for($i=0;$i<=$Countdata;$i++)
{
$data=array('id_perjal'=>$iddata[$i]); // this code can't generate id one by one like i wanna : 1, next 2, next 16 etc
$this->M_perjal_terpasang->save($data);
}
echo json_encode(array("status" => TRUE));
</div>
Set dataId as string:
dataId = '1,2,16,15,17,3,14,5,9,11';// remove white space
URI = "<?php echo site_url('Terpasang/Update_Kebutuhan_ke_Terpasang')?>";
$.ajax({
url : URI,
type: "GET",
data: { "iddata": [dataId] },
dataType: "JSON",
});
In PHP code:
$iddata = explode(",",$_GET['iddata']);// string to array separated by ,
$Countdata = count($iddata);
for($i = 0; $i <= $Countdata; $i++)
{
$data = array('id_perjal'=>$iddata[$i]);
$this->M_perjal_terpasang->save($data);
}
echo json_encode(array("status" => TRUE));
Use foreach
instead for
Remove these
$Countdata = count($iddata);
for($i = 0; $i <= $Countdata; $i++)
{
$data = array('id_perjal'=>$iddata[$i]); // this code can't generate id one by one like i wanna : 1, next 2, next 16 etc
$this->M_perjal_terpasang->save($data);
}
echo json_encode(array("status" => TRUE));
and add
foreach($iddata as $id)
{
$data = array('id_perjal'=>$id);
$this->M_perjal_terpasang->save($data);
}