Jquery Save Documents onchange and Avoid Duplication of Documents - php

I am saving documents with onchange function in jquery. I am facing issue that when i save first document it save as single but when i save second document saveDocument function save first document again with second document.
`function saveDocument() {
// Get files
var data = {};
var files_to_upload = {};
var formData = new FormData();
var lead_id = $("#lead-id").val();
formData.append('lead_id', lead_id);
Color_Copy_of_Id = document.getElementById('Color_Copy_of_Id').files;
Color_Copy_of_Id_back = document.getElementById('Color_Copy_of_Id_back').files;
SSN_Card = document.getElementById('SSN_Card').files;
Utility = document.getElementById('Utility').files;
Business_Voided_Check = document.getElementById('Business_Voided_Check').files;
Personal_Financial_Statment = document.getElementById('Personal_Financial_Statment').files;
Employed = document.getElementById('Employed').files;
Self_Employed = document.getElementById('Self_Employed').files;
// for (i = 0; i < files.length; i++){
/** Only PDF files Allowed */
// files_to_upload[] = files[i];
formData.append('files[Color_Copy_of_Id]', Color_Copy_of_Id[0]);
formData.append('files[Color_Copy_of_Id_back]', Color_Copy_of_Id_back[0]);
formData.append('files[SSN_Card]', SSN_Card[0]);
formData.append('files[Utility]', Utility[0]);
formData.append('files[Business_Voided_Check]', Business_Voided_Check[0]);
formData.append('files[Personal_Financial_Statment]', Personal_Financial_Statment[0]);
formData.append('files[Employed]', Employed[0]);
formData.append('files[Self_Employed]', Self_Employed[0]);
// }
if($("[id='Signed Loan Application']").length > 0){
Signed_Loan_Application = document.getElementById('Signed Loan Application').files;
formData.append('files[Signed loan Application]', Signed_Loan_Application[0]);
}
if($("[id='2019 Business Tax Returns']").length > 0){
Business_Tax_Returns_2019 = document.getElementById('2019 Business Tax Returns').files;
formData.append('files[2019 Business Tax Returns]', Business_Tax_Returns_2019[0]);
}
if($("[id='2020 Business Tax Returns']").length > 0){
Business_Tax_Returns_2020 = document.getElementById('2020 Business Tax Returns').files;
formData.append('files[2020 Business Tax Returns]', Business_Tax_Returns_2020 [0]);
}
if($("[id='2021 Business Tax Returns']").length > 0){
Business_Tax_Returns_2021 = document.getElementById('2021 Business Tax Returns').files;
formData.append('files[2021 Business Tax Returns]', Business_Tax_Returns_2021[0]);
}
if($("[id='2019 Personal Tax Returns']").length > 0){
Personal_Tax_Returns_2019 = document.getElementById('2019 Personal Tax Returns').files;
formData.append('files[2019 Personal Tax Returns]', Personal_Tax_Returns_2019[0]);
}
if($("[id='2020 Personal Tax Returns']").length > 0){
Personal_Tax_Returns_2020 = document.getElementById('2020 Personal Tax Returns').files;
formData.append('files[2020 Personal Tax Returns]', Personal_Tax_Returns_2020[0]);
}
if($("[id='2021 Personal Tax Returns']").length > 0){
Personal_Tax_Returns_2021 = document.getElementById('2021 Personal Tax Returns').files;
formData.append('files[2021 Personal Tax Returns]', Personal_Tax_Returns_2021[0]);
}
if($("[id='YTD Profit and Loss Statement']").length > 0){
Balance_Sheet_YTD_PF = document.getElementById('YTD Profit and Loss Statement').files;
formData.append('files[YTD Profit and Loss Statement]', Balance_Sheet_YTD_PF[0]);
}
if($("[id='Business Debt Schedule']").length > 0){
Business_Debt_Schedule = document.getElementById('Business Debt Schedule').files;
formData.append('files[Business Debt Schedule]', Business_Debt_Schedule[0]);
}
if($("[id='Personal Financial Statement']").length > 0){
Personal_Financial_Statement_G = document.getElementById('Personal Financial Statement').files;
formData.append('files[Personal Financial Statement]', Personal_Financial_Statement_G[0]);
}
if($("[id='4 Months Business Bank Statements']").length > 0){
Four_Months_Business_Bank_Statements = document.getElementById('4 Months Business Bank Statements').files;
formData.append('files[4 Months Business Bank Statements]', Four_Months_Business_Bank_Statements[0]);
}
if($("[id='Personal_Voided_Check']").length > 0){
Personal_Voided_Check = document.getElementById('Personal_Voided_Check').files;
formData.append('files[Personal_Voided_Check]', Personal_Voided_Check[0]);
}
if($("[id='YTD_Balance_Sheet_Statement']").length > 0){
YTD_Balance_Sheet_Statement = document.getElementById('YTD_Balance_Sheet_Statement').files;
formData.append('files[YTD_Balance_Sheet_Statement]', YTD_Balance_Sheet_Statement[0]);
}
if($("[id='SS4_IRSEIN_Letter']").length > 0){
SS4_IRSEIN_Letter = document.getElementById('SS4_IRSEIN_Letter').files;
formData.append('files[SS4_IRSEIN_Letter]', SS4_IRSEIN_Letter[0]);
}
if($("[id='other']").length > 0){
other = document.getElementById('other').files;
formData.append('files[other]', other[0]);
}
$.ajax({
cache: false,
contentType: false,
processData: false,
headers: {
'X-CSRF-Token': _token
},
data: formData,
type: "POST",
url: base_url + "Leads/saveDocument",
success: function (response) {
console.log("SUCCESS");
var result = JSON.parse(response);
var docu_ids = result['document_id'];
$(document).on('change', '.docs_field', function () {
console.log("check");
$(this).next('.doc_hidden_id').val(docu_ids);
});
}
});
}`
Data is sending to php function using above code. The php function code id
`function saveDocument(){
Log::write('debug', 'Save document');
$restAPI = new RestAPIHelper(new \Cake\View\View());
if ($this->request->is('Ajax')) {
$this->autoRender = false;
$data = $this->request->getData();
$field_mapping_arr = array(
"Color_Copy_of_Id" => "sales_check_color_copy_id_c",
"Color_Copy_of_Id_back" => "sales_check_color_copy_id_back_c",
"SSN_Card" => "sales_check_ssn_card_c",
"Utility" => "sales_check_utility_bill_c",
"Personal_Voided_Check" => "sales_check_ach_voided_check_c",
"Business_Voided_Check" => "sales_check_business_voided_check_c",
"Personal_Financial_Statment" => "sales_check_financial_statement_c",
"Employed" => "sales_check_employed_c",
"Remove Fraud Alerts" => "sales_check_remove_fraud_alerts_c",
"Self_Employed" => "sales_check_self_employed_c",
"Business Debt Schedule" => "sales_check_debt_schedule_c",
"Signed loan Application" => "sales_check_signed_application_c",
"YTD Profit and Loss Statement" => "sales_check_ytd_balance_sheet_c",
"YTD_Balance_Sheet_Statement" => "sales_check_ytd_balance_sheet_statement_c",
"SS4_IRSEIN_Letter" => "sales_check_ss4_irsein_letter_c",
);
Log::write('debug', "SaveDocument");
Log::write('debug', $data);
$files_arr = $data["files"];
foreach($files_arr as $document_type => $doc_arr){
Log::write('debug', "doc_arr");
Log::write('debug', $doc_arr);
if($doc_arr != 'undefined')
{
$dataToSave = array (
'lead_id' => $data["lead_id"],
'document_name' => $doc_arr["name"],
'document_type' => str_replace("_"," ",$document_type),
'template_type' => str_replace("_"," ",$document_type),
'revision' => '1'
);
$sendResult = $restAPI->setRecord('Documents', $dataToSave);
Log::write("debug", "dataToSave");
Log::write("debug", $dataToSave);
$dataToSaveForLead = array (
'id' => $data["lead_id"],
"$field_mapping_arr[$document_type]" => true,
);
Log::write("debug", "dataToSaveForLead");
Log::write("debug", $dataToSaveForLead);
Log::write("debug", "sendResult->id");
Log::write("debug", $sendResult->id);
$docu_details = array(
'document_id' => $sendResult->id,
);
$sendResultLead = $restAPI->setRecord('Leads', $dataToSaveForLead);
if($sendResult->id){
$param = array (
'note' => array(
//The ID of the parent document.
'id' => $sendResult->id,
//The binary contents of the file.
'file' => base64_encode(file_get_contents($doc_arr['tmp_name'])),
//The name of the file
'filename' => $doc_arr['name'],
//The revision number
'revision' => '1',
),
);
$result = $restAPI->createDocumentRevision($param);
}
}
}
ob_clean();
Log::write("debug", "DATA");
Log::write("debug", $docu_details);
echo json_encode($docu_details);
exit;
}
}`
And onchange function is
`$(document).on('change', '.docs_field', function () {
if (this.files[0].size > 20971520) {
swal("Please select file less then 20MB");
$(this).val('');
}
else
{
saveDocument();
}
});`
All input type fields have same class docs field.
I want that function should save the document of active input field.
I apologies if i am asking non sense query.

Related

how to show array of parent and child Data as row in datatables

i am working in codeigniter and i need to show a list of destinations as row in datatables, like UK as Parent and London as Child destination.
i need to show them in datatable, i have created array of both parent and child data, but i am not able to understand, how to show them in datatable properly as each child destination row below their parent row.
something like wordpress parent and child category.
here is what i did as of now.
here is my controller
public function fetch_destinations(){
// POST data
$postData = $this->input->post();
// Get data
$data = $this->tourismo->fetch_dest_nested($postData);
echo json_encode($data);
}
this is my model
function fetch_dest_nested($postData=null)
{
$response = array();
## Read value
$draw = $postData['draw'];
$start = $postData['start'];
$rowperpage = $postData['length']; // Rows display per page
$columnIndex = $postData['order'][0]['column']; // Column index
$columnName = $postData['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $postData['order'][0]['dir']; // asc or desc
$searchValue = $postData['search']['value']; // Search value
## Search
$search_arr = array();
$searchQuery = "";
if($searchValue != ''){
$search_arr[] = " (name like '%".$searchValue."%' ) ";
}
if(count($search_arr) > 0){
$searchQuery = implode(" and ",$search_arr);
}
## Total number of records without filtering
$this->db->set_dbprefix('');
$this->db->select('count(*) as allcount');
$records = $this->db->get('destinations')->result();
$totalRecords = $records[0]->allcount;
## Total number of record with filtering
$this->db->select('count(*) as allcount');
if($searchQuery != '')
$this->db->where($searchQuery);
$records = $this->db->get('destinations')->result();
$totalRecordwithFilter = $records[0]->allcount;
//fetch records
$this->db->select("*");
if($searchQuery != '')
$this->db->where($searchQuery);
$this->db->where('level', 1);
$this->db->order_by($columnName, $columnSortOrder);
$this->db->limit($rowperpage, $start);
$this->db->from("destinations");
$q = $this->db->get();
$final = array();
if ($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$this->db->select("*");
$this->db->from("destinations");
$this->db->where("parentid", $row->id);
$q = $this->db->get();
if ($q->num_rows() > 0) {
$row->children = $q->result();
}
array_push($final, $row);
}
}
$data = array();
foreach($final as $parentdest){
$data[] = array(
"id"=>$parentdest->id,
"name"=>$parentdest->name,
"slug"=>$parentdest->slug
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
return $response;
}
this is my view
<table class="apitable table dt-table" id="destlist_table">
<thead>
<th>
Destination Id</th>
<th>Destination Name</th>
<th>Destination Slug</th>
</thead>
</table>
here is my jquery code for ajax request
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<!-- Script -->
<script type="text/javascript">
$(document).ready(function(){
var destlistDataTable = $('#destlist_table').DataTable({
'bDestroy': true,
'processing': true,
'serverSide': true,
'serverMethod': 'post',
"searching": true,
"pageLength": 10,
"order":[[0,'desc']],
'ajax': {
'url':'<?php echo admin_url('tourismo/tourismo/fetch_destinations'); ?>',
'data': function(data){
}
},
'columns': [
{ data: 'id' },
{ data: 'name' },
{ data: 'slug' },
]
});
});
what i want is every child destination row should be just below its Parent destination row, i am just not able to understand how to work with this loop here.
this is the reference for what i want

Convert correctly currency

I have a default currency as USD.
The part of the class below allow to convert different currencies but my problem is the conversion is always based in EUR as default.
How to update the function to use USD as default if it selected ?
Thank you
EUR = 1 (default)
USD = 1.10
This approach works very well for any currencies
EUR = 0.9
USD = 1 (default)
This approach do not work because USD is in default and the result is always like above.
Note :
$currenciesAdmin->getAll() take all the currencies with the code (EUR) and the title (Euro) for example.
The value of EUR is always null because the convertion is based on EUR as default (see link ecb.europa.eu for the values)
public function getConvertCurrency()
{
$currenciesAdmin = new CurrenciesAdmin();
$XML = HTTP::getResponse([
'url' => 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
]);
if (empty($XML)) {
throw new \Exception('Can not load currency rates from the European Central Bank website');
}
$currencies = [];
foreach ($currenciesAdmin->getAll() as $c) {
$currencies[$c['id']] = null;
}
$XML = new \SimpleXMLElement($XML);
foreach ($XML->Cube->Cube->Cube as $rate) {
if (array_key_exists((string)$rate['currency'], $currencies)) {
$currencies[(string)$rate['currency']] = (float)$rate['rate'];
}
}
foreach ($currencies as $code => $value) {
if (!is_null($value)) {
try {
$this->db->save('currencies', [
'value' => $value,
'last_updated' => 'now()'
], [
'code' => $code
]);
} catch (\PDOException $e) {
trigger_error($e->getMessage());
}
}
}
}
Normally you'd use an API that allows you to select a base currency and do the conversion that way. That said, if you need to work with this dataset I believe the following approach may work for you:
$sourceCurrency = 'EUR'; // Your data source uses this as the base value
$defaultCurrency = 'USD'; // Read this from desired location
$currencies = [];
foreach ($currenciesAdmin->getAll() as $c) {
$currencies[$c['id']] = null;
}
// This is a constant
$currencies[$sourceCurrency] = 1;
$XML = new \SimpleXMLElement($XML);
foreach ($XML->Cube->Cube->Cube as $rate) {
$code = (string)$rate['currency'];
if (array_key_exists($code, $currencies)) {
$currencies[$code] = (float)$rate['rate'];
}
}
if ($defaultCurrency !== $sourceCurrency) {
// Conversion is required
$convertedCurrencies = [];
foreach (array_keys($currencies) as $code) {
$convertedCurrencies[$code] = $currencies[$code] / $currencies[$defaultCurrency];
}
$currencies = $convertedCurrencies;
}
// Use $currencies as normal with the adjusted values
Below is an interactive demo that contains the JavaScript equivalent code that you can test in your browser:
(() => {
const currencyDropdown = document.querySelector('select');
const selForm = document.querySelector('form');
const sourceCurrency = 'EUR';
let cachedData = null;
const generateTable = async(first) => {
const defaultCurrency = first ? sourceCurrency : currencyDropdown.options[currencyDropdown.selectedIndex].value;
if (cachedData === null)
cachedData = await fetch('https://cors-anywhere.herokuapp.com/https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml').then(r => r.text()).then(str => (new window.DOMParser()).parseFromString(str, "text/xml"));
let currencies = Array.from(cachedData.querySelectorAll('Cube > Cube > Cube'))
.reduce((a, c) => ({ ...a,
[c.attributes.currency.value]: parseFloat(c.attributes.rate.value)
}), {});
currencies.EUR = 1;
const currencyKeys = Object.keys(currencies).sort();
currencyDropdown.innerHTML = currencyKeys.map(code => `<option${code === defaultCurrency ? ' selected' : ''}>${code}</option>`)
if (sourceCurrency !== defaultCurrency) {
const convertedCurrencies = currencyKeys.reduce((a, code) => ({
...a,
[code]: currencies[code] / currencies[defaultCurrency],
}), {});
currencies = convertedCurrencies;
}
let tbl = document.querySelector('table');
if (tbl !== null)
tbl.remove();
tbl = document.createElement('table');
tbl.innerHTML = '<tr><th>code</th><th>value</th></tr>' +
(currencyKeys.map(
code => `<tr><td>${code}</td><td>${currencies[code]} ${defaultCurrency}</td></tr>`).join(''));
document.body.appendChild(tbl);
selForm.hidden = false;
};
selForm.addEventListener('submit', (e) => {
e.preventDefault();
generateTable(false);
});
generateTable(true);
})();
<form hidden>
<label>
Default currency:
<select></select>
<input type="submit">
</label>
</form>
<table>
<tr>
<td>Loading…</td>
</tr>
</table>

Insert Batch php mysql with check duplicate and sum values of field duplicate

i have 1 million data using foreach.
ex table:
table
the data
data
i want to inserting that's data using batch/multipleinsert, but i have problem when i got duplicate data. if data duplicate i want the field amount will sum and update amount field with sum amount duplicated data.
this is my code before
<?php
foreach ($data_transaksi as $key)
{
if($key['STATUS_COA'] != $key['CHART_OF_ACCOUNT_STATUS'])
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2);
}
else
{
$amount = round($key['AMOUNT'],2) *-1;
}
}
else
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2)*-1;
}
else
{
$amount = round($key['AMOUNT'],2);
}
}
$dt_exsis = $this->ledger_model->cek_data_coa_exsis($key['COA_CODE'],$modul,$ID_USER);
if(empty($dt_exsis['id']))
{
//TRYINSERTINGBATCH
// $datainsert[] = '('.$key['COA_CODE'].','.$amount.','.$ID_USER.',"'.$modul.'")';
// $test = $key['COA_CODE'];
$datainput = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
$this->ledger_model->save_rows_to_table($datainput,'finance_lapkue_temp');
}
else
{
$amount_fix = $amount + $dt_exsis['AMOUNT'];
$data=array(
'AMOUNT' => $amount_fix
);
$this->ledger_model->edit_rows_to_table_where($data,'finance_lapkue_temp','id',$dt_exsis['id']);
// $q = "UPDATE finance_lapkue_temp set AMOUNT = '$amount_fix' where id = '".$dt_exsis['id']."'";
// $this->db->query($q);
}
// $data_amount[$key['COA_CODE']] += $amount;
}
?>
if i using this code, the proccess so slow
Good option will to pass only data to DB that you want to insert. All the data cleaning task can be done in controller.
// Create a data array and add all info
$data = [];
//if user does not exist add it in array
if (empty($dt_exist($id))) {
$data[$ID_USER] = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
}
else {
//if user exist in $data just modify the amount
if (!empty($data[$ID_USER])) {
$data[$ID_USER]['AMOUNT'] += $dt_exsis['AMOUNT'];
}
else {
// if user does not exist in data create add all info
$data[$dt_exsis['ID_USER']] = array(
'COA_CODE' => $dt_exsis['COA_CODE'],
'AMOUNT' => $dt_exsis['amount'],
'MODUL' => $dt_exsis['modul'],
'USER_ID' => $dt_exsis['ID_USER']
);
}
}
This will save multiple calls to DB and at the end you can pass $data and do multiple insert.

Using render() value does not update when color box open second time

I'm posting value using color box from view to controller. First time it works perfectly fine but when I reopen the color box it POST the old value to the new.
This is my color box code:
$('#equipmentPopup').colorbox({
ajax: true,
width: "620px",
height: "450px",
href: showEquipment,
data: {
briefingId: $("#briefing_id").val(),
briefingDate: $("#Briefing_scheduled_date").val(),
briefingEndDate: $("#Briefing_scheduled_end_date").val(),
briefingEquipments: $('#BriefingEquipments').val()
}
});
This is my action code:
public function actionShowEquipment()
{
$this->layout = "//layouts/popup";
$equipmentConflicts = '';
$briefingId = $_POST['briefingId'];
$briefingDate = $_POST['briefingDate'];
$briefingEndDate = isset($_POST['briefingEndDate']) ? $_POST['briefingEndDate'] : '';
$serializeBriefingEquipments = isset($_POST['briefingEquipments']) ? $_POST['briefingEquipments'] : '';
$equipment = CHtml::listData(Equipment::model()->findAll(), 'id', 'name');
$briefingCenter = BriefingCenter::model()->findByPk(Yii::app()->user->currentBriefingCenterId);
if ($briefingId) {
$briefingEquipmentArr = BriefingEquipment::model()->findAll('briefing_id = :bId', array(':bId' => $briefingId));
if (!$briefingEquipmentArr) {
$briefingEquipmentArr[] = new BriefingEquipment();
}
} else if ($serializeBriefingEquipments) {
$serializeBriefingEquipments = unserialize($serializeBriefingEquipments);
}
$briefing = Briefing::model()->findByPk($briefingId);
if (!empty($briefing->scheduled_date) && !empty($briefing->scheduled_end_date)) {
$minDate = $briefing->scheduled_date;
$maxDate = $briefing->scheduled_end_date;
} else {
$minDate = $briefingDate;
$maxDate = $briefingEndDate;
}
echo $this->render('edit/equipment', array(
'briefing' => array(
'briefingId' => $briefingId,
'briefingDate' => $briefingDate,
'briefingEndDate' => $briefingEndDate,
),
'minDate' => strtotime($minDate),
'maxDate' => strtotime($maxDate),
'briefingEquipmentArr' => $briefingEquipmentArr,
'equipments' => $equipment,
'briefingCenter' => $briefingCenter,
'serializeBriefingEquipments' => $serializeBriefingEquipments,
'dateFormat' => Yii::app()->user->currentBriefingCenterDateFormat,
));
}
Your code does not work for me. I see there is no passed data by colorbox, so try changing data to this:
data: function() {
return {
briefingId: $("#briefing_id").val(),
briefingDate: $("#Briefing_scheduled_date").val(),
briefingEndDate: $("#Briefing_scheduled_end_date").val(),
briefingEquipments: $('#BriefingEquipments').val()
}
}
Maybe it will help.

PHP not deleting and inserting data right

How this code works is every time a user visits the page, i scrape all of the data from the table and pass it through the below posts. If the user hasn't accessed that page before and the database is empty with their cookie_id, then it inserts the content, if it is found then it deletes the content from the database and inserts it again. The problem I am having though is that when the deletion occurs it deletes everything and seems to insert one value from $data1 instead of all the data from $data. Any ideas as to why this is happening?
Backend:
$cookie_id = $this->input->cookie("session_id");
$selected_size = $this->input->post('selected_size');
$product_id = $this->input->post('product_id');
$product_name = $this->input->post('product_name');
$product_color = $this->input->post('product_color');
$q1 = $this->db->query("SELECT * FROM default_cart_temp
WHERE cookie_id = '$cookie_id'
AND is_paid = 'No'");
if ($q1->num_rows() > 0) {
$this->db->where('cookie_id', $cookie_id);
$this->db->delete('default_cart_temp');
foreach($product_id as $key => $value) {
$data1 = array('selected_size' => $selected_size[$key],
'product_id' => $value,
'product_name' => $product_name[$key],
'product_color' => $product_color[$key],
'cookie_id' => $cookie_id,
'is_paid' => 'No');
} $this->db->insert('default_cart_temp', $data1);
echo json_encode(array('success' => true));
} else {
foreach($product_id as $key => $value) {
$data = array('selected_size' => $selected_size[$key],
'product_id' => $value,
'product_name' => $product_name[$key],
'product_color' => $product_color[$key],
'cookie_id' => $cookie_id,
'is_paid' => 'No');
} $this->db->insert('default_cart_temp', $data);
}
Frontend:
selected_size = $('.selected_size1').text();
arr1 = selected_size.split(".");
ss1 = arr1.slice(0, -1);
product_id = $('.product_id1').text();
arr2 = product_id.split(".");
ss2 = arr2.slice(0, -1);
product_name = $('.product_name1').text();
arr3 = product_name.split(".");
ss3 = arr3.slice(0, -1);
product_color = $('.product_color1').text();
arr4 = product_color.split(".");
ss4 = arr4.slice(0, -1);
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?=base_url()?>index.php/products/products/new_instance",
data: { selected_size: ss1, product_id: ss2, product_name: ss3, product_color: ss4 },
json: {success: true},
success: function(data) {
if(data.success == true) {
alert("True");
}
}
});
In every foreach loop execution you are overriding $data and $data1 variables. You have to change them to arrays and add data like this $data[] = $subArray.

Categories