DataTable Odd Behavior when Deleting Data - php

I'm adding and deleting row on datatable via ajax.. when I delete data on the datatable and call the additional_info_datatable.ajax.reload() it gives me errors.
here's the error:
Here's my code:
PHP
public function ajax_call_additional_info(){
$result = $this->main_m->get_all_where('additional_info', array('is_deleted' => 0));
$data = array();
if(!empty($result)){
foreach($result as $row){
array_push($data,
array(
'id' => $row['additional_info_id'],
'description' => $row['description'],
'action' => "<button type='button' data-url='".site_url(array('events','soft_delete_additional_info'))."' data-name='".$row['description']."' data-id='".$row['additional_info_id']."' class='btn btn-danger delete_additional_info'><i class='fa fa-fw fa-trash'></i></button>"
));
}
echo json_encode(array('data' => $data));
}else{
echo json_encode(array("draw" => 0, "recordsTotal" => 0, "recordsFiltered" => 0, "data" => array()));
}
}
public function soft_delete_additional_info(){
$id = $this->input->post('id');
$name = $this->input->post('name');
$check_if_exist = $this->main_m->get_where('additional_info', array('additional_info_id' => $id));
if(!empty($check_if_exist)){
$this->main_m->update_data('additional_info', array('is_deleted' => 1), 'additional_info_id', $id);
// $newdata = array(
// 'type' => 'success',
// 'message' => $name."'s successfully deleted!"
// );
// $this->session->set_userdata($newdata);
$message = array('type' => 'alert-success', 'message' => $name."'s successfully deleted!");
echo json_encode($message);
// echo site_url(array("events", "hotel_groupings", $check_if_exist['event_id']));
// echo 1;
}
}
JQUERY
INITIALIZE DATATABLE:
var additional_info = $("#additional_info_table");
var additional_info_datatable = additional_info.DataTable({
"ajax": additional_info.data('url'),
"columns": [
{ "data": "id" },
{ "data": "description" },
{ "data": "action" },
],
"autoWidth": false,
// scrollX: true,
keys: true,
// iDisplayLength: 10,
// "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
// buttons: []
});
DELETE CODE
$(document).on('click', '.delete_additional_info', function(){
var $this = $(this);
var $url = $this.data('url');
var $id = $this.data('id');
var $name = $this.data('name');
var $csrf_token = $("#csrf_token").val();
bootbox.confirm({
title: "Delete Data",
message: "Do you want to delete <strong>"+$name+"</strong>? This process is irreversible.",
buttons: {
cancel: {
label: '<i class="fa fa-times"></i> Cancel'
},
confirm: {
label: '<i class="fa fa-check"></i> Confirm'
}
},
callback: function (result) {
// console.log('This was logged in the callback: ' + result);
if(result){
$.ajax({
url:$url,
type:'post',
data:{id : $id, name: $name, csrf_test_name : $csrf_token},
dataType:'json',
success:function(data){
// console.log(data);
$(".alert").css("display","block");
$(".alert").addClass(data['type']);
$("#additional_info_message").html(data['message']);
additional_info_datatable.ajax.reload();
}
});
}
}
});

Related

How to pass * as an argument with jQuery to be validated in the Laravel controller?

I've tried passing through using string (teachers_remark.*) from what I searched, but it is not validated in the controller. I expected it to return an error, but it is successfully saved instead.
Need help, I'm a beginner in jQuery.
This is my jQuery:
var students_id = $('#students').val();
var teachers_id = $('#teachers').val();
var teacherArray = $('#my_teachers_remarks input').map(function () {
return {
"value": this.value,
}
}).get();
sessionStorage['teachers'] = JSON.stringify(teacherArray);
var teachers_remark_arr = [];
teachers_remark_arr = sessionStorage['teachers'];
event.preventDefault();
swal({
title: "{{ __('Are you sure?') }}",
text: "{{ __('No further changes allowed.') }}",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then(function(willAssign) {
if (willAssign) {
return axios.post(route('students.report'), {
students: students_id,
teachers: teachers_id,
'teachers_remark.*': teachers_remark_arr,
})
.then(function (response) {
if (response.data.status === 'ERROR'){
swal({
title: "Error",
text: response.data.errors,
icon: "error"
}).then(function(){
location.reload();
});
}
if (response.data.status === 'SUCCESS'){
swal("Success", response.data.message , "success");
}
})
This is my Controller:
$this->validate(
$request,
[
'students' => ['required'],
'teachers' => ['required'],
'teachers_remark.*' => ['required'],
],
[
'students.required' => 'There is no students selected.',
'teachers.required' => 'There is no teachers selected.',
'teachers_remark.*.required' => 'You must include remarks',
]
);

How to create a JSTree view with context menu with create, rename, delete, drag'n'drop with PHP/Laravel? This is the Full solution

My project needed a file treeview to upload documents and I was using a theme forest template with jstree included in a page.
So I've decided to use it but it was necessary to connect it to the database. It was needed a database, an api and all the code for it.
I've spent some hours trying to find out how to create a JSTree Structure with Laravel, with drag and drop, moving, creating, renaming and sorting features.
After digging into the jstree documentation and Stack Overflow, here is my working solution compilation of everything, step by step.
I'm using JSTree version 3.3.11 and Laravel 8.
Steps:
A) Create Database.
The table is "Directories".
class CreateDirectoriesTable extends Migration
{
public function up()
{
Schema::create('directories', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('parent_id')->nullable();
$table->string('name');
$table->text('observations')->nullable();
$table->timestamps();
$table->foreign('parent_id')
->references('id')
->on('directories')
->cascadeOnDelete();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('directories');
}
}
B) Directory.model
Use it to define which fields are updatable, and to define the recursive relationship.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Directory extends Model
{
use HasFactory;
protected $fillable = [
'parent_id',
'name',
'observations',
];
public function children()
{
return $this->hasMany(Directory::class, 'parent_id');
}
}
C) Seeder (optional)
I've used a Seeder to include some items to test
<?php
namespace Database\Seeders;
use Faker\Factory;
use App\Models\Directory;
use Illuminate\Database\Seeder;
class DirectorySeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$faker = Factory::create();
$items = array(
[
'name' => $faker->lexify('???????????????'),
'parent_id' => null,
'observations' => $faker->optional()->paragraph(3),
],
[
'name' => $faker->lexify('???????????????'),
'parent_id' => null,
'observations' => $faker->optional()->paragraph(3),
],
[
'name' => $faker->lexify('???????????????'),
'parent_id' => null,
'observations' => $faker->optional()->paragraph(3),
],
[
'name' => $faker->lexify('???????????????'),
'parent_id' => null,
'observations' => $faker->optional()->paragraph(3),
],
[
'name' => $faker->lexify('???????????????'),
'parent_id' => 1,
'observations' => $faker->optional()->paragraph(3),
],
[
'name' => $faker->lexify('???????????????'),
'parent_id' => 2,
'observations' => $faker->optional()->paragraph(3),
],
[
'name' => $faker->lexify('???????????????'),
'parent_id' => 3,
'observations' => $faker->optional()->paragraph(3),
],
[
'name' => $faker->lexify('???????????????'),
'parent_id' => 5,
'observations' => $faker->optional()->paragraph(3),
],
[
'name' => $faker->lexify('???????????????'),
'parent_id' => 5,
'observations' => $faker->optional()->paragraph(3),
],
[
'name' => $faker->lexify('???????????????'),
'parent_id' => 7,
'observations' => $faker->optional()->paragraph(3),
],
[
'name' => $faker->lexify('???????????????'),
'parent_id' => 7,
'observations' => $faker->optional()->paragraph(3),
],
[
'name' => $faker->lexify('???????????????'),
'parent_id' => 8,
'observations' => $faker->optional()->paragraph(3),
],
[
'name' => $faker->lexify('???????????????'),
'parent_id' => 8,
'observations' => $faker->optional()->paragraph(3),
],
);
foreach($items as $item) {
Directory::factory()->create($item);
}
}
}
D) Routes on web.php
I've defined the 4 functions to deal with DragNDrop, Rename, Delete and Create.
Route::name('api.')->prefix('api/')->group(function() {
Route::post('/treeview/dnd', 'ApiController#treeviewDnd')->name('treeviewdnd');
Route::post('/treeview/rename', 'ApiController#treeviewRename')->name('treeviewrename');
Route::post('/treeview/delete', 'ApiController#treeviewDelete')->name('treeviewdelete');
Route::post('/treeview/create', 'ApiController#treeviewCreate')->name('treeviewcreate');
});
E) The API Controller
class ApiController extends Controller
{
// Move Node on Directory Tree
public function treeviewDnd()
{
$directory = Directory::find(request()->source);
if ($directory) {
if (request()->destination) {
if (request()->destination == '#') {
$directory->parent_id = null;
} else {
$directory->parent_id = request()->destination;
}
}
$directory->update();
}
}
// Rename Node on Directory Tree
public function treeviewRename()
{
$directory = Directory::find(request()->dbid);
if ($directory) {
$name = request()->name;
if ($name) {
$directory->name = $name;
$directory->update();
}
}
}
// Delete Node on Directory Tree
public function treeviewDelete()
{
$directory = Directory::find(request()->id);
if ($directory) {
$directory->delete();
}
}
// Create Node on Directory Tree
public function treeviewCreate()
{
$directory = [
"name" => request()->name,
"parent_id" => request()->parentid,
];
$result = Directory::create($directory);
return $result;
}
}
F) Include tree on blade.php
<div id="stackoverflowtree" class="tree-demo"></div>
G) I've created a section "SCRIPTS" on my base blade, so I can include scripts at the end of the page using the section tag.
#section('scripts')
<script>
"use strict";
var tree = {!! $treeJS !!};
var treeId = '#stackoverflowtree';
var nodeSelected = undefined;
var KTTreeview = function () {
var _demostackoverflow = function() {
$(treeId).jstree({
"core" : {
"themes" : {
"responsive": false
},
// so that create works
"check_callback" : function (operation, node, node_parent, node_position, more) {
if (operation === 'delete_node') {
if (confirm('#lang("global.confirmation_title")') == true) {
return true;
}
else {
return false;
}
} else {
return true;
}
},
'data': tree,
},
"types" : {
"default" : {
"icon" : "fa fa-folder text-primary"
},
"file" : {
"icon" : "fa fa-file text-primary"
}
},
"state" : { "key" : "demo2" },
"plugins" : [ "dnd", "state", "types", "sort", "contextmenu" ],
"sort" : function(a, b) {
if (a && b && this) {
var a1 = this.get_node(a);
var b1 = this.get_node(b);
if (a1.icon == b1.icon){
return a1.text.toLowerCase().localeCompare(b1.text.toLowerCase());
} else {
return a1.icon.toLowerCase().localeCompare(b1.icon.toLowerCase());
}
}
},
"contextmenu": {
"items": function ($node) {
var tree = $(treeId).jstree(true);
return {
"Rename": {
"label": "#lang('global.directory_rename')",
"action": function (obj) {
tree.edit($node);
}
},
"Create": {
"label": "#lang('global.directory_create')",
"action": function (obj) {
$node = tree.create_node($node);
tree.edit($node);
}
},
"Delete": {
"label" : "#lang('global.directory_delete')",
"action" : function(obj) {
tree.delete_node($node);
}
}
};
}
}
})
.bind("move_node.jstree", function(e, data) {
var treeInst = $(treeId).jstree(true);
var parentNodeResult = null;
if (data.parent != '#') {
var aux = treeInst.get_node(data.parent);
parentNodeResult = aux.original.dbid;
} else {
parentNodeResult = '#';
}
$.ajax({
url: "{{ route('api.treeviewdnd') }}",
type:'POST',
data: {
"_token" : "{{ csrf_token() }}",
"source": data.node.original.dbid,
"destination": parentNodeResult,
},
success: function(data) {
console.log(data);
}
});
})
.bind("select_node.jstree", function(evt, data){
console.log("select");
nodeSelected = data.node;
$("#tree-subtitle").html(data.node.text)
})
.bind("rename_node.jstree", function (e, data) {
if (data.node.text && data.text != data.old) {
$.ajax({
url: "{{ route('api.treeviewrename') }}",
type:'POST',
data: {
"_token" : "{{ csrf_token() }}",
"dbid": data.node.original.dbid,
"name": data.text,
},
success: function(data) {
toastr.success('#lang("global.success_message")', '#lang("global.success_title")');
},
error: function(data) {
toastr.error('#lang("global.error_required")', '#lang("global.error_title")');
}
});
}
})
.bind("create_node.jstree", function (e, data) {
var treeInst = $(treeId).jstree(true)
var parentNode = treeInst.get_node(data.parent)
$.ajax({
url: "{{ route('api.treeviewcreate') }}",
type:'POST',
data: {
"_token" : "{{ csrf_token() }}",
"entityid": {{ $entity->id }},
"parentid": parentNode.original.dbid,
"name": data.node.text,
},
success: function(response) {
data.node.original = { "dbid" : response.id };
},
error: function(response) {
toastr.error('#lang("global.error_message")', '#lang("global.error_title")');
}
});
})
.bind("delete_node.jstree", function (e, data) {
$.ajax({
url: "{{ route('api.treeviewdelete') }}",
type:'POST',
data: {
"_token" : "{{ csrf_token() }}",
"id": data.node.original.dbid,
},
success: function(data) {
toastr.success('#lang("global.success_message")', '#lang("global.success_title")');
},
error: function(data) {
toastr.error('#lang("global.error_message")', '#lang("global.error_title")');
}
});
});
}
return {
//main function to initiate the module
init: function () {
_demostackoverflow();
}
};
}();
jQuery(document).ready(function() {
KTTreeview.init();
});
</script>
#endsection
H) I almost forgot. The creation of the tree structure on the server side, the page Controller:
<?php
namespace App\Http\Controllers;
use App\Models\Directory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class EntityController extends Controller
{
private function getTreeJS($entity, $path_id, &$treejs)
{
$directories = Directory::where('entity_id', $entity->id)->where('parent_id', $path_id)->get();
$treejs .= '[';
foreach($directories as $directory) {
$treejs .= '{';
$treejs .= ' "dbid" : "' . $directory->id . '", ';
$treejs .= ' "text" : "' . $directory->name . '", ';
$treejs .= '"children" : ';
$treejs .= $this->getTreeJS($entity, $directory->id, $treejs);
$treejs .= '}, ';
}
$treejs .= ']';
}
public function details(Entity $entity, Property $property = null)
{
// Create Tree JS
$treejs = '';
$this->getTreeJS($entity, null, $treejs);
return view('admin.entities.details', [
'treeJS' => $treejs,
]);
}
}
I) The messages I've used to show some output to the user are in language files /resources/lang/en/ in Laravel:
<?php
return [
// Success
'success_title' => 'Success!',
'success_message' => 'Operation successfully.',
// Errors
'error_title' => 'Ups! There was an error.',
'error_required' => 'You must fill the information.',
'error_message' => 'It was not possible to finish the operation.',
'confirmation_title' => 'Do you confirm?',
'confirmation_success' => 'Operation successfully.',
'directory_rename' => 'Rename',
'directory_create' => 'Create folder',
'directory_delete' => 'Delete folder'
];
Conclusion:
I've used an extra variable called dbid for each tree folder corresponding to the ID on my database table.
Using that DB Id, I can use it on each operation by finding the exact node using the jstree 'get_node'.
I've just started learning Laravel and this is not the perfect solution but it was my approach to handle my requirements. Feel free to use it and change it your own way.
This is my image:

Migrating from Legacy stripe checkout to the new version in codeigniter

I am working on a project which will work as a marketplace website. I already have stripe library as an initial payment method where will receive payment from customers from the website but it seems like the old version of stripe has been upgraded and I want to adopt the new version.
public function stripe_payment_post()
{
require_once(APPPATH . 'third_party/stripe/vendor/autoload.php');
try {
$token = $this->input->post('payment_id', true);
$email = $this->input->post('email', true);
$payment_amount = $this->input->post('payment_amount', true);
$currency = $this->input->post('currency', true);
//Init stripe
$stripe = array(
"secret_key" => $this->payment_settings->stripe_secret_key,
"publishable_key" => $this->payment_settings->stripe_publishable_key,
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
//customer
$customer = \Stripe\Customer::create(array(
'email' => $email,
'source' => $token
));
//charges
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $payment_amount,
'currency' => $currency,
'description' => trans("stripe_checkout")
));
//add to database
$data_transaction = array(
'payment_method' => "Stripe",
'payment_id' => $token,
'currency' => $currency,
'payment_amount' => get_price($payment_amount, 'decimal'),
'payment_status' => $this->input->post('payment_status', true),
);
} catch (\Stripe\Error\Base $e) {
$this->session->set_flashdata('error', $e->getMessage());
$data = array(
'status' => 0,
'redirect' => generate_url("cart", "payment")
);
echo json_encode($data);
} catch (Exception $e) {
$this->session->set_flashdata('error', $e->getMessage());
$data = array(
'status' => 0,
'redirect' => generate_url("cart", "payment")
);
echo json_encode($data);
}
}
// Here is the client side
<script src="https://checkout.stripe.com/v2/checkout.js"></script>
<script>
var handler = StripeCheckout.configure({
key: '<?php echo $this->payment_settings->stripe_publishable_key; ?>',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
currency: '<?php echo $currency; ?>',
token: function (token) {
var data = {
'payment_id': token.id,
'email': token.email,
'currency': '<?php echo $currency; ?>',
'payment_amount': '<?php echo $total_amount; ?>',
'payment_status': 'success',
'sys_lang_id': sys_lang_id
};
data[csfr_token_name] = $.cookie(csfr_cookie_name);
$.ajax({
type: "POST",
url: base_url + "stripe-payment-post",
data: data,
success: function (response) {
var obj = JSON.parse(response);
if (obj.result == 1) {
window.location.href = obj.redirect;
} else {
location.reload();
}
}
});
}
});
document.getElementById('btn_stripe_checkout').addEventListener('click', function (e) {
handler.open({
name: '<?php echo html_escape($this->general_settings->application_name); ?>',
description: '<?php echo trans("stripe_checkout"); ?>',
amount: '<?php echo $total_amount; ?>'
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function () {
handler.close();
});
</script>
You can find documentation describing this migration here: https://stripe.com/docs/payments/checkout/migration

Build dynamically ChartJs Datasets for JSON Ajax response in PHP

I am having a problem with building JSON in PHP, as a response on Ajax call for populating dynamically datasets for ChartsJs.
In PHP I have an return of Ajax call that works for 1 ChartJs Dataset:
<?php
$returnData['line'] = array(
'type' => 'line',
'title' => $title,
'labels' => array('Jan','Feb','March','April','Mai'),
'datasets' => array(
array(
'data' => array(10,20,15,45,21),
'borderColor' => "#f7464a",
'label' => "Label 1",
'fill' => false
)
)
);
echo json_encode($returnData);
?>
JavaScript that builds the Chart:
$.ajax({
url: "div.php",
type: "POST",
dataType: 'json',
success: function(rtnData) {
$.each(rtnData, function(dataType, data) {
var ctx = document.getElementById("myChart").getContext("2d");
var config = {
type: data.type,
data: {
datasets: data.datasets,
labels: data.labels
},
options: {
responsive: true,
title: {
display: true,
text: data.title
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#333'
}
}
}
};
window.myPie = new Chart(ctx, config);
});
},
error: function(rtnData) {
alert('error' + rtnData);
}
});
Now my question, when I have Data for 5 or more Datasets:
//Data
$title = "MyTitle";
$labels= array('Jan','Feb','March','April','Mai');
//Datasets
$linelabels= array('Line1','Line2','Line3','Line4','Line5');
$mydata1 = array(10,20,15,45,21);
$mydata2 = array(21,45,15,20,10);
$mydata3 = array(10,20,15,45,21);
$mydata4 = array(21,45,15,20,10);
$mydata5 = array(10,20,15,45,21);
$colors = array("#f7464a","#8e5ea2","#f7464a","#8e5ea2","#f7464a");
How can I build those Datasets dynamically in the JSON response? For example:
'datasets' => array(
for(i=0:i<5;i++)
{
array(
'data' => array($mydata1[i]),
'borderColor' => $colors[i],
'label' => $linelabels[i],
'fill' => false
),
}
)
SOLVED. To create dynamically Json for Ajax response for Charts, maybe can help someone out:
$returnData2['line'] = array(
'type' => 'line',
'title' => 'my Title',
'labels' => array('Jan','Feb','March','April','Mai'),
'datasets' => array(
array(
'data' => array(10,20,15,45,21),
'borderColor' => "#f7464a",
'label' => "Label 1",
'fill' => false
),
array(
'data' => array(21,45,15,20,10),
'borderColor' => "#8e5ea2",
'label' => 'Line2',
'fill' => false
),
array
(
'data' => array(10,20,15,45,21),
'borderColor' => "#f7464a",
'label' => 'Line3',
'fill' => false
),
array
(
'data' => array(21,45,15,20,10),
'borderColor' => "#8e5ea2",
'label' => 'Line4',
'fill' => false
),
array(
'data' => array(10,20,15,45,21),
'borderColor' => "#f7464a",
'label' => 'Line5',
'fill' => false
)
)
);
echo json_encode($returnData2);
I used this construct, I admit it is not the finest way, but it works. :)
$title = "MyTitle";
$labels= array('Jan','Feb','March','April','Mai');
$linelabels= array('Line1','Line2','Line3','Line4','Line5');
$mydata1 = array(10,20,15,45,21);
$mydata2 = array(21,45,15,20,10);
$mydata3 = array(35,24,20,18,11);
$mydata4 = array(18,5,34,17,42);
$mydata5 = array(23,17,34,12,45);
$colors = array("#E74C3C","#76448A","#148F77","#D4AC0D","#1ABC9C");
$returnData = new stdClass();
$returnData->line = new stdClass();
$returnData->line->type = 'line';
$returnData->line->title = 'my Title';
$returnData->line->labels = $labels;
$returnData->line->datasets = new stdClass();
$dataset = array();
for($i=0;$i<5;$i++)
{
$mydata = array();
if($i==0)
$mydata = $mydata1;
else if($i==1)
$mydata = $mydata2;
else if($i==2)
$mydata = $mydata3;
else if($i==3)
$mydata = $mydata4;
else if($i==4)
$mydata = $mydata5;
$datasets = new stdClass();
$datasets->data = $mydata;
$datasets->borderColor = $colors[$i];
$datasets->label = $linelabels[$i];
$datasets->fill = false;
$dataset[] = $datasets;
}
$returnData->line->datasets = $dataset;
echo json_encode($returnData);
Ajax response for bulding Charts:
$.ajax({
url: "div.php",
type: "POST",
dataType: 'json',
success: function(rtnData) {
$.each(rtnData, function(dataType, data) {
var ctx = document.getElementById("myChart").getContext("2d");
var config = {
type: data.type,
data: {
datasets: data.datasets,
labels: data.labels
},
options: {
responsive: true,
title: {
display: true,
text: data.title
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#333'
}
}
}
};
window.myPie = new Chart(ctx, config);
});
},
error: function(rtnData) {
alert('error' + rtnData);
}
});
And the result in Canvas:
enter image description here

Why am I getting error 500 (Internal Server Error) on my ajax?

the problem begins when I try to use my data to the server. once I uncomment this line $data_product = $this->item->addProduct($descripcion,$cost_price,$selling_price,$wprice,$stock); I get the problem 500 Internal Server Error, but I dont know why if I have everything ok, ids,names, etc. I want to send my array to the server. how can I debug this error and fix it? I tried it to see my logs, and there are nothing..
this is the link: http://alasksoft.tk/inventory/product
login credentials: admin - admin
controller
public function addProduct(){
$descripcion = $this->input->post('description');
$cost_price = $this->input->post('cost_price');
$selling_price = $this->input->post('selling_price');
$wprice = $this->input->post('wprice');
$stock = $this->input->post('stock');
$data_product = $this->item->addProduct($descripcion,$cost_price,$selling_price,$wprice,$stock);
$data = array(
'description' => $descripcion,
'cost_price' => $cost_price,
'selling_price' => $selling_price,
'wprice' => $wprice,
'stock' => $stock
);
$this->json($data_product);
}
model
public function addProduct($descripcion,$cost_price,$selling_price,$wprice,$stock){
$data = array(
'descripcion' => $descripcion,
'precio_compra' => $cost_price,
'precio_venta' => $selling_price,
'precio_mayoreo' => $wprice,
'existencia' => $stock
);
$query = $this->db->insert('storelte_articulos',$data);
return $query->result_array();
}
ajax
$('#add').on('click',function(){
$("#description").mask("(999) 999-9999");
$("#new_product").validate();
BootstrapDialog.show({
message: function(dialog) {
var $message = $('<div></div>');
var pageToLoad = dialog.getData('pageToLoad');
$message.load(pageToLoad);
return $message;
},
data: {
'pageToLoad': URL_GET_VIEW_PRODUCT
},
closable: false,
buttons:[{
id: 'btn-ok',
cssClass: 'btn-primary',
icon: 'glyphicon glyphicon-send',
label: ' Save',
action: function (e) {
var description = $('#description').val();
var cost_price = $('#cost_price').val();
var selling_price = $('#selling_price').val();
var wprice = $('#wprice').val();
var stock = $('#stock').val();
if($("#new_product").valid()){
$.ajax({
url: URL_GET_ADD_PRODUCT,
type: 'POST',
data: {description: description, cost_price: cost_price, selling_price: selling_price, wprice: wprice, stock: stock}
}).done(function (e) {
console.log(e);
});
}
}
},{
id: 'btn-cancel',
cssClass: 'btn-danger',
icon: 'glyphicon glyphicon-remove',
label: ' Cancel',
action: function (e) {
e.close();
}
}]
});
});

Categories