i want to know how to get laravel javascript query for my chart
why does it always return the data without making a pie chart, always to the json view
code in view:
<script>
// get data from database using Ajax or fetch
fetch('/api/data')
.then(response => {
let data = response.data;
let ctx = document.getElementById('myChart').getContext('2d');
let myChart = new Chart(ctx, {
type: 'pie',
data: data
});
})
.catch(error => {
console.log(error);
});
code in controller:
$data = DB::table('suara')
->groupBy('suara')
->pluck(DB::raw('sum(jml_suara) as sum'), 'suara')
->toarray();
// format data for pie chart
$labels = [];
$values = [];
foreach ($data as $item => $key) {
$labels[] = $item;
$values[] = $key;
}return response()->json([
'labels' => $labels,
'datasets' => [
[
'data' => $values,
'backgroundColor' => ['#FF6384', '#36A2EB', '#FFCE56', '#F44336']
]
]
]);
Related
Hello there
Hope you will be doing good.I want to download txt file generated on the fly from the controller of laravel i have search alot but could not find any solution.Please help out i will be very thankful.
Blade code with axios request
submitHandler:function(form,e){
var btn=document.querySelector("#BtnSubmit");
btn.style.display="none";var img=document.createElement("img");
img.setAttribute("src",base_url+'front/images/loading.gif');
var loader=document.querySelector("#loader");loader.appendChild(img);
var url="<?php echo route('database.export-txtProcess');?>";
var cur_url="<?php echo route('database.export-txt');?>";
//var tblExportSelect = $("#tblExportSelect").val();
var pushArray = [];
$.each($("#tblExportSelect option:selected"), function(){
pushArray.push($(this).data("id"));
});
var data = new FormData();
data.append('tblExportSelect',pushArray);
//$("#tblExportSelect").val(selected);
axios({
method: 'POST',
url: url,
data: data,
})
.then(function(res){
console.log(res);
})
e.preventDefault();
}
});
Controller Method
public function exportTxtProcess(Request $request){
/*dd($request->tblExportSelect);*/
$tables = explode(",", $request->tblExportSelect);
$destinationPath = public_path('/');
$result;
foreach ($tables as $table) {
$outputs = DB::select("SELECT * FROM $table");
$today = date("Y-m-d");
$fileName = $table."-".$today;
$fp = fopen($destinationPath . "$fileName.txt","wb");
foreach ($outputs as $output) {
$output = (array)$output;
#array_shift($output);
$removeUserId = #$output['user_id'];
$created_at = #$output['created_at'];
$updated_at = #$output['updated_at'];
if (($key = array_search($removeUserId, $output)) !== false) {
unset($output[$key]);
}
if (($key1 = array_search($created_at, $output))) {
unset($output[$key1]);
}
if (($key2 = array_search($updated_at, $output))) {
unset($output[$key2]);
}
if (is_null($created_at) OR $created_at == '') {
unset($output['created_at']);
}
if (is_null($updated_at) OR $updated_at == '') {
unset($output['updated_at']);
}
$netResult = $this->getTableFields($table,$output);
fwrite($fp,$netResult);
}
$result = fclose($fp);
}
/*$arr = array(['Good' => true,'message' => 'Data has been successfully imported.'], 200);
echo json_encode($arr);*/
if ($result) {
$pathToFile = $destinationPath . "$fileName.txt";
$downloaded = response()->download($pathToFile)->deleteFileAfterSend();
}
}
I want to download when txt file which is created as above but instead of download it streaming in the console.
Thank in advance
You have to pass the headers. Most importantly you are not returning the reponse.
$headers = [
'Content-type' => 'text/plain',
'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
'Content-Length' => sizeof($content)
];
return response()->download($pathToFile, $fileName,$headers)->deleteFileAfterSend();
This is my ajax code which fetches all data from data and display in the table, but when I input an alphabet in search-box, it again fetches complete data inside the table
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "<?php echo base_url() ?>Appconfig/get_masteradmin_data?query="+query,true);
xhttp.onload= function()
{
if (xhttp.status >=200 && xhttp.status <400)
{
var data= JSON.parse(xhttp.responseText);
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<tr>'+
'<td>'+data[i].full_name+'</td>'+
'<td>'+data[i].username+'</td>'+
'<td>'+data[i].designation+'</td>'+
'<td>'+data[i].department+'</td>'+
'<td>'+data[i].official_mobile_no+'</td>'+
'<td>'+data[i].official_email_id+'</td>'+
'<td>'+data[i].select_user_type+'</td>'+
'<td>'+data[i].permission+'</td>'+
'</tr>';
}
showdata.insertAdjacentHTML('beforeend',html);
}
else
{
console.log("Try again after some time");
}
};
xhttp.send();
}
$('#search').keyup(function(){
var search = $(this).val();
//console.log(search);
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
This is my model for fetching data from my mongodb collection.
public function get_masteradmin_data($query)
{
$mongo = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$query= '';
//$filter = ['full_name' => 'www'];
$regex = new MongoDB\BSON\Regex ($query);
$filter = ['full_name'=>$regex,];
$options =[
'projection' => [
'_id' => 0,
'full_name' => 1,
'username' => 1,
'designation'=> 1,
'department'=> 1,
'official_mobile_no'=> 1,
'official_email_id'=> 1,
'select_user_type'=> 1,
'permission'=> 1,
],
'sort' => [
'_id' => -1
],
];
$query = new MongoDB\Driver\Query($filter, $options);
//$readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$result = $mongo->executeQuery('justrack_db.master_admin', $query);
$res = array();
foreach($result as $r)
{
$res[] = $r;
}
return json_encode($res,true);
//return $res;
}
This is my controller for displaying data. I am not sure, but I think there is some issue in my controller, as I tried to echo $query but it shows nothing. I am not able to understand how to fix this.
public function get_masteradmin_data()
{
$query = '';
$this->load->model('AppconfigModel');
$this->master_admin();
if($this->input->post('query'))
{
$query = $this->input->post('query');
}
$result= $this->AppconfigModel->get_masteradmin_data($query);
echo ($result);
}
In my controller when I remove the html from the code and take message then it works fine but when I used it will give error
POST http://localhost/buyWatch/public/addwatch 500 (Internal Server Error)
/*******************************************************
Ajax code here:
<script>
insertdata();
function insertdata(){
$(document).ready(function() {
$('#form_output').hide();
$("#watch-form").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax( {
url:"{{ route('add_watch.postdata') }}",
method: "POST",
data:formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(data) {
if(data.error.length > 0)
{
$('#form_output').show();
var data=data.error ;
var errors = data.responseJSON;
//var error_html = '';
$('.alert ul').html(errors);
/* for(var count = 0; count < data.error.length; count++)
{
error_html += data.error[count];
$('.alert').html(error_html);
}//for loop end*/
// $('#form_ul').html(error_html);
}//if condition
else{
console.log(data.success);
$('.alert').html("sucess fully updated");
$("#watch-form")[0].reset();
}//else end here
}
});
});
});//end document
}//insertData end function
</script>
Controller here:
public function store(Request $request)
{
$validation = Validator::make($request->all(), [
'watch_name' => 'required',
'watch_price' => 'required',
'watch_quantity' => 'required',
'image1' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'image2' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'image3' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'watch_size' => 'required',
'discription' => 'required',
]);
if($request->ajax())
{
/// $error_array = array();
$success_output = array();
if ($validation->fails())
{
foreach($validation->messages()->getMessages() as $field_name => $messages)
{
// $error_array[] = $messages;
$error_array = '<li>'.$messages.'</li>';
}
}else{
$success_output = '<div class="alert alert-success">Data Inserted</div>';
}
$output = array(
'error' => $error_array,
'success' => $success_output
);
echo json_encode($output);
}
}
Can u give us the response of XPOST http://foobar/addWatch ?
update 3
Please see answer below! Can provide further explanation there on request if needed
Update 2
js
$archiveLayout.on('click',loadMoreButtonID,function(){
let pageCount = $(this).attr('data-page'),
nextPage = parseInt( $(this).attr('data-page') ) + 1;
let getParams;
_.each($loadMoreButton, function(item) {
let thisData = window.$(item).data()
getParams = thisData;
});
console.log(getParams);
$.post(ajaxurl, getParams,function(response){
// var json_obj = JSON.parse(res);
console.log(response);
console.log(response.data);
}).done(function(){
$('#load-more').attr('data-page', nextPage);
});
});
php function
add_action('wp_ajax_more_all_posts', __NAMESPACE__ . '\\ajax_more_all_posts');
add_action('wp_ajax_nopriv_more_all_posts', __NAMESPACE__ . '\\ajax_more_all_posts');
function ajax_more_all_posts()
{
$response = array(
'data' => Timber::compile(array('templates/blocks/content.twig'), $context)
);
wp_send_json($response);
}
HTML is retunred, but it's only 1 post and the data isn't populating the twig markup.
old****
So on my blog page, I want to load more posts, and I'm wondering if I can just append the response data to the posts array aleady on the page. Or if need to build it out a certain way to allow for that.
Any tips/help etc would be greatly appreciated.
code samples below
I have the following set up in in my twig file:
{% for post in posts %}
{% set postCount = loop.index %}
{% set postImage = TimberImage(post.get_field('preview_image_post'))|resize('medium_large') %}
{% include "blocks/content.twig" with {post: post} %}
{% endfor %}
Outputs the posts onto the page just fine.
I then make an ajax request doing the following:
window.axios.get(fancySquaresRestUrl + 'wp/v2/posts', {
params: getParams
})
.then(function (response) {
// append the entire repsonese? wasn't working, could be doing it wrong
_.each( response.data, function( post, index ) {
//append each object on its own maybe???
});
})
.catch(function (error) {
console.log(error);
});
The full answer is as follows: (this is not appending anything to the Timber/Post Object, this is appending HTML from the data that get's passed to the twig file)
Any questions or comments you have about the below code feel free to ask.
The js used:
$archiveLayout.on('click',loadMoreButtonID,function(){
var $this = $(this);
var pageCount = $(this).attr('data-pageCount');
var nextPage = parseInt($(this).attr('data-page')) + 1;
var getParams = void 0;
_.each($loadMoreButton, function (item) {
var thisData = window.$(item).data();
getParams = thisData;
});
getParams.pagecount = pageCount;
// console.log(getParams);
$loader.fadeIn();
$loadMoreButton.fadeOut();
$.post(ajaxurl, getParams, function (response) {
// var json_obj = JSON.parse(res);
// console.log(response);
//console.log(response.data);
if(response === 'nomore'){
$loadMoreButton.fadeOut();
} else {
for(var hp = 0; hp < response.length; hp++){
$('[data-js="append-content"]').append(response[hp].data);
$this.attr('data-pageCount', Number(pageCount)+1);
}
$loadMoreButton.fadeIn();
}
}).done(function () {
$loader.fadeOut();
// $('#load-more').attr('data-page', nextPage);
});
});
the function being called:
add_action('wp_ajax_more_all_posts', __NAMESPACE__ . '\\ajax_more_all_posts');
add_action('wp_ajax_nopriv_more_all_posts', __NAMESPACE__ . '\\ajax_more_all_posts');
function ajax_more_all_posts()
{
$cat_id = $_REQUEST[ 'cat' ] or $_GET[ 'cat' ];
$paged = $_REQUEST['pagecount'];
$cat = $_REQUEST['dataCat'];
$args = [
'cat' => $cat_id,
'posts_per_page' => 9,
'post_status' => 'publish'
];
if($paged != ""){
$args['paged'] = $paged;
}
$posts = Timber::get_posts($args);
$message = [];
if($posts){
foreach($posts as $post){
$response = array(
'data' => Timber::compile('templates/blocks/content.twig', ['post' => $post])
);
$message[] = $response;
}
} else {
$message = "nomore";
}
wp_reset_query();
wp_reset_postdata();
wp_send_json($message);
die();
}
I already did something close. My solution was to render at the ajax and send the html.
So my Ajax calls a php and at the php I do this:
For this example my ajax call the get_php_logic action.
At the php action I do my logic to render the twig, at the final i return as Json response.
$response = array(
'data' => Timber::compile(array('template.twig'), $context)
);
wp_send_json($response);
So this way my response.data will be html ready to append or replace.
I am having trouble passing SQL data from my controller to my view. I have verified the information shows up from my model. I don't know JSON very well but I'm trying to learn. My goal is to populate a chart with two fields that are just numbers into this highcharts javascript. Please help, thank you!
Controller
function dashboard() {
// Tickets in Queue
$query = $this->mhedash_model->maint_pending_tickets();
$result3 = $query->result_array();
$this->table->set_heading('Work Number', 'Vehicle Number','Submit Date','Submit Time');
$data['table']['Vehicle in Queue'] = $this->table->generate_table($result3);
// Active Tickets
$query = $this->mhedash_model->select_active();
$result = $query->result_array();
$this->table->set_heading('Service Number','Start Date','Mechanic','Vehicle Number','Description','Type');
$data['table']['Vehicles Actively Being Worked On'] = $this->table->generate_table($result);
// Tickets Waiting On Parts
$query = $this->mhedash_model->select_pending_parts();
$result2 = $query->result_array();
$this->table->set_heading('Service Number','Start Date','Mechanic','Vehicle Number','Description','Type');
$data['table']['Waiting For Parts'] = $this->table->generate_table($result2);
//Graph - Availble Highreaches
$query = $this->mhedash_model->graph_available_hr();
$result4 = $query->result_array();
$data['row'][''] = $this->table->generate_table($result4);
$query = $this->mhedash_model->graph_available_dt();
$result5 = $query->result_array();
$data['row'][''] = $this->table->generate_table($result5);
$series_data[] = array('name' => 'available', 'data' => (int)$result4);
$series_data[] = array('name' => 'not_available', 'data' => (int)$result5);
$this->view_data['series_data'] = json_encode($series_data, JSON_NUMERIC_CHECK);
// Load view
$data['page_title'] = 'MHE Dashboard';
$data['main_content'] = 'mhe/mhe_dashboard_view';
$data['array'] = $result;
$data['array2'] = $result2;
$data['array3'] = $result3;
print json_encode($series_data);
//echo json_encode($series_data, JSON_NUMERIC_CHECK);
return $this->load->view('includes/template',$data);
}
View that has the highcharts javascript
var chart;
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
xAxis: {
categories: ['one', 'two']
},
plotOptions: {
series: {
allowPointSelect: true
}
},
series: [{
data: [<?php echo join($series_data, ',') ?>]
}]
});
// the button action
$('#button').click(function () {
var chart = $('#container').highcharts(),
selectedPoints = chart.getSelectedPoints();
if (chart.lbl) {
chart.lbl.destroy();
}
chart.lbl = chart.renderer.label('You selected ' + selectedPoints.length + ' points', 100, 60)
.attr({
padding: 10,
r: 5,
fill: Highcharts.getOptions().colors[1],
zIndex: 5
})
.css({
color: 'white'
})
.add();
});
});
</script>
Also, this is what prints when I print son_encode for my $series_data
[{"name":"available","data":1},{"name":"not_available","data":1}]