Build dynamically ChartJs Datasets for JSON Ajax response in PHP - 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

Related

How to use widget kartik select2 with ajax & templates in yii2

I want to display more than 1 information when searching, so I use select2 ajax & templates. It use json. I change the url and I make function on my controller. But I have a problem. It can not show anything. What's the problem? This is my code:
view
$formatJs = <<< 'JS'
var formatProduct = function (product) {
if (product.loading) {
return product.text;
}
var markup =
'<div class="row">' +
'<div class="col-sm-5">' +
'<b style="margin-left:5px">' + product.name + '</b>' +
'</div>' +
'<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + product.ean_no + '</div>' +
'<div class="col-sm-3"><i class="fa fa-star"></i> ' + product.desc + '</div>' +
'</div>';
return '<div style="overflow:hidden;">' + markup + '</div>';
};
var formatProductSelection = function (product) {
return product.name || product.text;
}
JS;
// Register the formatting script
$this->registerJs($formatJs, \yii\web\View::POS_HEAD);
// script to parse the results into the format expected by Select2
$resultsJs = <<< JS
function (data, params) {
params.page = params.page || 1;
return {
// Change `data.items` to `data.results`.
// `results` is the key that you have been selected on
// `actionJsonlist`.
results: data.results
};
}
JS;
Select2
echo Select2::widget([
'name' => 'kv-repo-template',
'value' => '14719648',
'initValueText' => 'kartik-v/yii2-widgets',
'options' => ['placeholder' => 'Search for a repo ...'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 1,
'ajax' => [
'url' => Url::to(['/bom/product/productlist']),
'dataType' => 'json',
'delay' => 250,
'data' => new JsExpression('function(params) { return {q:params.term, page: params.page}; }'),
'processResults' => new JsExpression($resultsJs),
'cache' => true
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('formatProduct'),
'templateSelection' => new JsExpression('formatProductSelection'),
],
]);
controller
public function actionProductlist($search = NULL, $code = NULL)
{
header('Content-type: application/json');
$clean['more'] = false;
$query = new \yii\db\Query;
if(!is_Null($search))
{
$mainQuery = $query->select('code, name, description, volume')
->from('product');
$command = $mainQuery->createCommand();
$rows = $command->queryAll();
$clean['results'] = array_values($rows);
}
else
{
if(!is_null($code))
{
$clean['results'] = ['ean_no'=> $code, 'name' => Product::find($code)->nama,
'description' => Product::find($code)->description, 'volume' => Product::find($code)->volume];
}else
{
$clean['results'] = ['ean_no' => 123, 'name' => 'None found', 'description' => 'None found', 'volume' => 'None found'];
}
}
echo \yii\helpers\Json::encode($clean);
exit();
}
on mozilla when i open the inspect element console. there is an error message like this :
TypeError: data.slice is not a function
S2
Try to remove
'processResults' => new JsExpression($resultsJs),

DataTable Odd Behavior when Deleting Data

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();
}
});
}
}
});

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();
}
}]
});
});

Laravel AJAX put method 405 error

I'm trying to send data through AJAX put method. I don't know what I'm doing wrong.
All code posible code
link
My route file
Route::resource('restaurant', 'RestaurantController');
RestaurantController
public function update(Request $request, $id)
{
$rules = array (
'address_id' => 'required|alpha',
'name' => 'required|alpha',
'description' => 'required',
'phone' => 'required',
'email' => 'required|email',
'homemade' => 'required'
);
$validator = Validator::make ( Input::all (), $rules );
if ($validator->fails ())
return Response::json ( array (
'errors' => $validator->getMessageBag ()->toArray ()
) );
else {
$items = Restaurant::find ($id);
$items->address_id = ($request->address_id);
$items->name = ($request->name);
$items->description = ($request->description);
$items->phone = ($request->phone);
$items->email = ($request->email);
$items->homemade = ($request->homemade);
$items->save ();
return response ()->json ( $items );
}
}
ajax request
$('.modal-footer').on('click', '.edit', function() {
$.ajax({
type: 'PUT',
url: '/restaurant',
data: {
'_token': $('input[name=_token]').val(),
'id': $("#fid").val(),
'address_id': $('#address_id').val(),
'name': $('#name').val(),
'description': $('#description').val(),
'phone': $('#phone').val(),
'email': $('#email').val(),
'homemade': $('#homemade').val(),
'lat': $('#lat').val(),
'lng': $('#lng').val(),
'bank_name': $('#bank_name').val(),
'bank_code': $('#bank_code').val(),
'paypal_email': $('#paypal_email').val(),
'paypal_merchantname': $('#paypal_merchantname').val(),
'zipcode': $('#zipcode').val(),
'easypeisa': $('#easypeisa').val(),
'cod': $('#cod').val()
},
success: function(data) {
if (data.errors){
$('#myModal').modal('show');
if(data.errors.address_id) {
$('.address_id_error').removeClass('hidden');
$('.address_id_error').text("address_id name can't be empty !");
}
if(data.errors.name) {
$('.name_error').removeClass('hidden');
$('.name_error').text("name can't be empty !");
}
if(data.errors.description) {
$('.description_error').removeClass('hidden');
$('.description_error').text("description must be a valid one !");
}

Display Zend Form Validation error in Ajax

There is a Zend Registration Form. Having as input username, email, password and confirm password. Validator for email is following:
$this->add(array(
'name' => 'email_reg',
'required' => true,
'filters' => array(
array(
'name' => 'StripTags',
),
array(
'name' => 'StringTrim',
),
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\EmailAddress::INVALID_FORMAT => 'Email address format is invalid'
),
),
),
array(
'name' => 'Db\NoRecordExists',
'options' => array(
'table' => 'user',
'field' => 'email',
'adapter' => $sm->get ( 'Zend\Db\Adapter\Adapter' ),
'messages' => array(
NoRecordExists::ERROR_RECORD_FOUND => 'E-mail address already exists'
),
),
),
),
));
There are 4 validators: Required Type, e-amil format and if there is someone with following e-mail in database.
Error messages will be:
- E-mail is required
- Email address format is invalid
- E-mail address already exists
Problem Trying to catch error messages and output using ajax. In RegisterController having following function:
public function ajaxAction()
{
if (!$this->request->isPost()) {
return $this->redirect()->toRoute(NULL,
array( 'controller' => 'index'
)
);
}
$form = $this->getServiceLocator()->get('RegisterForm');
$form->setInputFilter(new RegisterFilter($this->getServiceLocator()));
$post = $this->request->getPost();
$form->setData($post);
$response = $this->getResponse();
$hello = 1;
if (!$form->isValid()){
// email is invalid; print the reasons
$json= $form->getMessages();
$response->setContent(\Zend\Json\Json::encode($json));
}
return $response;
}
And jQuery file:
$( document ).ready(function() {
var urlform = "register/ajax";
$("#btnRegister").click( function() {
$("#Register").submit( function() {
return false;
});
$.ajax({
url: urlform,
type: 'POST',
dataType: 'json',
async: true,
data: $(".form-signin").serialize(),
success: function (data) {
$("#rCheck").text(data);
console.log(data);
},
error: function (data) {
$("#rCheck").text(data);
console.log(data);
}
});
});
});
In Console i got something like this https://imagizer.imageshack.us/v2/558x205q90/661/uC09Da.png and in div with id #rCheck getting [Object][Object].
From the image you provided the error messages are correctly returned. The error is that you are trying to write directly an Object into your div.
You should have seached how to read an object with JavaScript. Try with this code :
success: function (data) {
data.forEach(function(datum) {
Object.keys(datum).forEach(function (key) {
$('<p>'+obj[key]+'</p>').appendTo('#rCheck');
});
});
console.log(data);
},
Or you may also do that within your ajaxAction :
$messages = array();
$errors = $form->getMessages();
foreach($errors as $key=>$row)
{
if (!empty($row) && $key != 'submit') {
foreach($row as $keyer => $rower)
{
$messages[$key][] = $rower;
}
}
}
if (!empty($messages)){
$response->setContent(\Zend\Json\Json::encode($messages));
}
return $response;
Here's is a good post on how to use Zend\Form with Ajax validation.

Categories