Newbie web developer here. My target is to get the total users under my agents and display the count in my table. I displayed my target for now for the better visualization of my target (1 and 7). Additionally, I provided a screenshot below for my target with explanation. Any help will be appreciated. Thank you in advance, everyone.
Views:
//I used ajax for my table
<script>
$(document).ready(function(){
// Tables
$(".allTable").on("click", function(){
var view_id = $(this).data('id')
$.ajax({
url: "<?=site_url('network/view')?>",
type: "post",
dataType: "json",
data: {
view_id: view_id
},
success: function(data){
var tbody ="";
var item =data.post;
for(var key in item) {
tbody +="<tr>";
tbody += "<td>"+item[key].userID+"</td>";
tbody += "<td>"+item[key].account_type+"</td>";
tbody += "<td>"+item[key].firstname+" "+item[key].lastname+"</td>";
tbody += "<td>"+item[key].email+"</td>";
tbody += "<td>"+item[key].mobile+"</td>";
tbody += "<td>"+item[key].username+"</td>";
tbody += "<td>"+item[key].currentPoints+"</td>";
tbody +="</tr>"
}
$(".tbody").html(tbody);
$('#editModal').modal('show');
}
});
})
});
</script>
Controller:
public function view()
{
if ($this->input->is_ajax_request()) {
$view_id = $this->input->post('view_id');
if ($post = $this->networks->view($view_id)) {
$data = array('responce' => 'success', 'post' => $post);
} else {
$data = array('responce' => 'error', 'message' => 'failed to fetch record', 'total_user_count => count($post)');
}
echo json_encode($data);
} else {
echo "No direct script access allowed";
}
}
Model:
// This is what i used for my query to get the agents under my agents. (Hierarchy Style)
public function view($userID = 0){
$this->db->select("*");
$this->db->from("users");
$this->db->where( "uuid=".$userID);
$query = $this->db->get();
return $result = $query->result();
}
Related
I want to filter products in my category with price desc or asc or newest(id desc). But my ajax filter only action in first page
This is my view and script:
<script type="text/javascript">
function sort(value) {
$.ajax({
type: 'get',
url: '{!!URL::to('cate/update') !!}',
data: {'sort': value, 'id': {{ $id }} },
}).done(function (data) {
$('body').html(data)
}).fail(function (data) {
console.log(data);
});
}
</script>
This is my controller:
if ($request->sort == 1) {
$data['items'] = Product::where('prod_cate', $request->id)->orderby('promotion_price', 'asc')->paginate(3);
} else if ($request->sort == 2) {
$data['items'] = Product::where('prod_cate', $request->id)->orderby('promotion_price', 'desc')->paginate(3);
}else{
$data['items'] = Product::where('prod_cate', $request->id)->orderby('prod_id', 'desc')->paginate(3);
}
return view('frontend.product_type', $data);
This is my ajax request code
function ajaxRequest() {
var currentIndexDay = $('#fieldValue').text();
var currentIndexMonth = $('#monthFieldValue').text();
var companyG = $("#companyGname").val();
var timeline = $("#timeL").val();
var month = $("#monthSelect").val();
var year = $("#yearSelect").val();
var dateRange = $("#dateR").val();
$.ajax({
method: "POST",
url: "<?php echo base_url(); ?>index.php/admin/home/pie_chart",
data: { day: currentIndexDay, week: currentIndexMonth, companyGroup: companyG, timeline: timeline, month: month, year: year, daterange: dateRange}
}).done(function( msg ) {
$("#test").html(msg);
});
}
on Done function the recieved data will showed on the div which id is test which is returned from a controller
Here is my controller
public function pie_chart() {
$data = $this->Statisticsmodel->pie_data_all_day($day);
$ap = array();
if(!empty($data)) {
foreach($data as $d=>$value){
if($value->moodstatus == 1 ){
$ap['Ok'] = $value->total;
}elseif($value->moodstatus == 2) {
$ap['Bad'] =$value->total;
}elseif($value->moodstatus == 0) {
$ap['Good'] =$value->total;
}
}
}
echo json_encode($ap);
}
So how can i catch the output to use in somewhere else not only in a div
You need to change your controller function to this :
public function pie_chart() {
$day= $this->input->post('day') // fetch the post data
$data = $this->Statisticsmodel->pie_data_all_day($day);
$ap = array();
if(!empty($data)) {
foreach($data as $d=>$value){
if($value->moodstatus == 1 ){
$ap['Ok'] = $value->total;
}elseif($value->moodstatus == 2) {
$ap['Bad'] =$value->total;
}elseif($value->moodstatus == 0) {
$ap['Good'] =$value->total;
}
}
}
echo json_encode($ap);
}
Since the day was not fetched,so the $data was empty and you are getting the empty response.
Hope this helps.
Change your ajax function like
function ajaxRequest(getData) {
var currentIndexDay = $('#fieldValue').text();
var currentIndexMonth = $('#monthFieldValue').text();
var companyG = $("#companyGname").val();
var timeline = $("#timeL").val();
var month = $("#monthSelect").val();
var year = $("#yearSelect").val();
var dateRange = $("#dateR").val();
$.ajax({
method: "POST",
url: "<?php echo base_url(); ?>index.php/admin/home/pie_chart",
data: { day: currentIndexDay, week: currentIndexMonth, companyGroup: companyG, timeline: timeline, month: month, year: year, daterange: dateRange},
success:function(data) {
getData(data);
}
});
}
Use it in div as like
ajaxRequest(function(output){
$("#test").html(output);
});
Use it in your chart as
ajaxRequest(function(output){
$('#piechart').piechart({
data : output
});
});
I'm trying to download an excel file using ajax method in laravel.
Controller function:
$myFile = Excel::create($name, function ($excel) use ($export) {
$excel->sheet('Data', function ($sheet) use ($export) {
$sheet->fromArray($export);
$sheet->cells('A1:N1', function ($cells) {
$cells->setBackground('#dbdbdb');
$cells->setFontColor('#000000');
$cells->setFontWeight('bold');
$cells->setFont(array(
'family' => 'Calibri',
'size' => '9',
));
});
$sheet->setStyle(array(
'font' => array(
'name' => 'Calibri',
'size' => 9,
),
));
});
});
$myFile = $myFile->string('xlsx');
$response = array(
'name' => $name,
'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," . base64_encode($myFile),
);
return response()->json($response);
Ajax function:
$(document).on('click', '.ExportJobs', function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var ids = [];
$(".InvoiceCheckBox:checked").each(function(e) {
ids.push(this.value);
});
data = {
"ids": ids,
};
$.ajax({
method: "POST",
url: "/exportNew",
data: data,
success: function(response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
document.body.appendChild(a);
a.click();
a.remove();
}
});
});
But using above controller method is not returning excel formatted file if I change string value from xlsx to csv then csv formatted file is getting downloaded.
How do we make the excel formatted file downloaded? Any suggestions, Please!
I know this is quite late, but posting for others who struggle with same issue like me
I also needed to download excel from using Maatwebsite excel library by using ajax post call.
added a button to fire the ajax call to download excel file
<button onclick="downloadExcel()" id="btn-download-payroll" class="btn btn-dark-success btn-md" style="transform: translateY(50%); top: 50%; font-size: 13px;"><i aria-hidden="true" class="fa fa-cog mr-10"></i>
Download
</button>
Used following js code to post ajax request
function downloadExcel() {
var salaryMonth = $("#dp-salary-month").datepicker("getDate");
var department = $("#cbox-department");
var month = new Date(salaryMonth).getMonth() + 1;
var year = new Date(salaryMonth).getFullYear();
$.ajax({
xhrFields: {
responseType: 'blob',
},
type: 'POST',
url: '/downloadPayroll',
data: {
salaryMonth: month,
salaryYear: year,
is_employee_salary: 1,
department: department.val()
},
success: function(result, status, xhr) {
var disposition = xhr.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'salary.xlsx');
// The actual download
var blob = new Blob([result], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});
}
in routes/web.php file set the reoute for my controller
Route::post('/downloadPayroll', 'Payroll\\Process\\PayrollController#downloadPayroll');
Here I used maatwebsite/excel library to generate excel file with FromQuery approach but due to library update Excel::create has been replaced by Excel::download in "maatwebsite/excel": "^3.1" I used download method in my case here is my HelperClass to generate records according to my requirement
PayrollHelper.php
namespace App\Http\Helpers;
use App\PayrollEmployee;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
class PayrollHelper implements FromQuery
{
use Exportable;
public function forDepartment(int $department)
{
$this->department = $department;
return $this;
}
public function forMonth(string $month)
{
$this->month = $month;
return $this;
}
public function query()
{
// get the salary information for the given month and given department
return PayrollEmployee::query()->where(['salary_month' => $this->month,'department_id'=>$this->department]);
}
}
finally in my controller
class PayrollController extends Controller
{
public function downloadPayroll(Request $request)
{
$file_name = '';
try {
$requestData = $request->all();
$salary_month = $requestData['salaryMonth'];
$salary_year = $requestData['salaryYear'];
$department = $requestData['department'];
$is_employee_salary = boolval($requestData['is_employee_salary']);
$month = Carbon::createFromDate($salary_year, $salary_month);
$month_start = Carbon::parse($month)->startOfMonth();
$formated_month = Carbon::parse($month)->format('F Y');
$file_name = 'Employee_salary_' . $formated_month . '.xlsx';
// to download directly need to return file
return Excel::download((new PayrollHelper)->forMonth($month_start)->forDepartment($department), $file_name, null, [\Maatwebsite\Excel\Excel::XLSX]);
} catch (exception $e) {
}
}
}
After creating excel file return file to get as ajax response as blob
That's all
Just see the xhrFields to set responseType as blob and then see the ajax success part. Hope you everyone find the solution:
<script>
$(document).ready(function(){
$("#ExportData").click(function()
{
dataCaptureExport();
});
});
function dataCaptureExport(){
var FromDate = $('#dateFrom').val();
var ToDate = $('#dateTo').val();
var dataString = { FromDate: FromDate, ToDate:ToDate, _token: '{{csrf_token()}}'};
$.ajax
({
type: "POST",
url: '{{ route('invoice_details_export') }}',
data: dataString,
cache: false,
xhrFields:{
responseType: 'blob'
},
success: function(data)
{
var link = document.createElement('a');
link.href = window.URL.createObjectURL(data);
link.download = `Invoice_details_report.xlsx`;
link.click();
},
fail: function(data) {
alert('Not downloaded');
//console.log('fail', data);
}
});
}
It's late but help for others
You can do this way
In Ajax
$(document).on('click', '#downloadExcel', function () {
$("#downloadExcel").hide();
$("#ExcelDownloadLoader").show();
$.ajax({
url: '{{ route("admin.export_pending_submitted_tasks") }}',
method: "GET",
cache: false,
data: {
search_partner,
search_state,
search_city,
_token,
},
success: function (response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
document.body.appendChild(a);
a.click();
a.remove();
$("#downloadExcel").show();
$("#ExcelDownloadLoader").hide();
},
error: function (ajaxContext) {
$("#downloadExcel").show();
$("#ExcelDownloadLoader").hide();
alert('Export error: '+ajaxContext.responseText);
}
});
});
In Controller
// Get pending submitted tasks export excel
public function export_pending_submitted_tasks(Request $request){
$input = $request->input();
$pending_submitted_tasks = SubmittedTask::select('id', 'partner', 'se_id', 'description', 'created_at', 'status', 'updated_at');
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('partner_id', $input['search_partner']) : '';
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('state', 'like', '%'.$input['search_state'].'%') : '';
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('city', 'like', '%'.$input['search_city'].'%') : '';
$pendingTaskList = $pending_submitted_tasks->where('status', 'pending')->get();
if($pendingTaskList->count() > 0):
$myFile = Excel::raw(new ExportPendingTaskHelper($pendingTaskList), 'Xlsx');
$response = array(
'name' => "Pending-Task-List.xlsx",
'file' => "data:application/vnd.ms-excel;base64,".base64_encode($myFile)
);
return response()->json($response);
else:
return back()->with('message', 'No Pending tasks available to download!!');
endif;
}
If you are using jquery:
// In controller:
return Excel::download(new SomeExport, 'Some_Report.xlsx', null, [\Maatwebsite\Excel\Excel::XLSX]);
// Ajax:
$.ajax({
type: 'GET',
url: '{{ route("some.route") }}',
data: {
"_token": "{{ csrf_token() }}"
},
xhrFields:{
responseType: 'blob'
},
beforeSend: function() {
//
},
success: function(data) {
var url = window.URL || window.webkitURL;
var objectUrl = url.createObjectURL(data);
window.open(objectUrl);
},
error: function(data) {
//
}
});
here's my ajax request. i send request to controller to remove pictures
$(document).on("click", "button[data-delete]", function(e) {
var tour_id = $("form").attr("data-tour-id");
var gallery = {};
$("input:checkbox[class = checkbox]:checked").each(function(k){
gallery[k] = $(this).attr("data-gallery-id");
});
gallery = JSON.stringify(gallery);
bootbox.confirm({
message: "გსურთ აღნიშნული სურათის წაშლა?",
callback: function(result){ }
});
$("button[data-bb-handler='confirm']").on("click",function(){
$.ajax({
headers: {'X-CSRF-Token': $('meta[name="csrf_token"]').attr('content')},
url: "/{lang}/admin/tours/"+ tour_id +"/edit/removeGalleryPic/"+ gallery,
data : { id: tour_id, pics: gallery },
}).done(function() {
window.location.reload();
});
});
});
it works. so if request response 200(ok) page will be reloaded. but i have another form fields, and after being reloaded i want to save(flash) the values of these fields. so in controller i return input, but it returns empty array. here's my controller
public function removeGalleryPic($id, $pics)
{
$pics = json_decode($pics, true);
$tour_whole_gallery = Tour_gallery::where("tour_id", $id)->get();
if(count($tour_whole_gallery) > 0)
{
foreach($tour_whole_gallery as $gallery)
{
foreach($pics as $pic_id)
{
if($gallery->id == $pic_id)
{
unlink(public_path() . $gallery->path);
Tour_gallery::where("id", $pic_id)->delete();
}
}
}
}
return Input::all();
}
how should i return all input fields with their data? i also tried these
$request->all();
$request->flash();
redirect()->back()->withInput();
but result is the same.
you could try this:
$input = Input::all();
return response()->json($input);
am using asp.net mvc3, i have 2 tables in that i want to get data from dropdown based on this another dropdown has to perform.for example if i select country it has to show states belonging to that country,am using the following code in the controller.
ViewBag.country= new SelectList(db.country, "ID", "Name", "--Select--");
ViewBag.state= new SelectList("", "stateID", "Name");
#Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewBag.country, "-Select-")
#Html.DropDownListFor(model => model.state, (IEnumerable<SelectListItem>)ViewBag.state, "-Select-")
but by using this am able to get only the countries.
There is a good jQuery plugin that can help with this...
You don't want to refresh the whole page everytime someone changes the country drop down - an ajax call to simply update the state drop down is far more user-friendly.
Jquery Ajax is the best Option for these kind of questions.
Script Code Is Given below
<script type="text/javascript">
$(function() {
$("##Html.FieldIdFor(model => model.Country)").change(function() {
var selectedItem = $(this).val();
var ddlStates = $("##Html.FieldIdFor(model => model.state)");
$.ajax({
cache:false,
type: "GET",
url: "#(Url.Action("GetStatesByCountryId", "Country"))",
data: "countryId=" ,
success: function (data) {
ddlStates.html('');
$.each(data, function(id, option) {
ddlStates.append($('<option></option>').val(option.id).html(option.name));//Append all states to state dropdown through returned result
});
statesProgress.hide();
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to retrieve states.');
statesProgress.hide();
}
});
});
});
</script>
Controller:
public ActionResult GetStatesByCountryId(string countryId)
{
// This action method gets called via an ajax request
if (String.IsNullOrEmpty(countryId))
throw new ArgumentNullException("countryId");
var country = GetCountryById(Convert.ToInt32(countryId));
var states = country != null ? GetStatesByConutryId(country.Id).ToList() : new List<StateProvince>();//Get all states by countryid
var result = (from s in states
select new { id = s.Id, name = s.Name }).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Try this,
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
var Id = $("#Country").val();
$.ajax({
url: '#Url.Action("GetCustomerNameWithId", "Test")',
type: "Post",
data: { Country: Id },
success: function (listItems) {
var STSelectBox = jQuery('#state');
STSelectBox.empty();
if (listItems.length > 0) {
for (var i = 0; i < listItems.length; i++) {
if (i == 0) {
STSelectBox.append('<option value="' + i + '">--Select--</option>');
}
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
else {
for (var i = 0; i < listItems.length; i++) {
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
}
});
});
});
</script>
View
#Html.DropDownList("Country", (SelectList)ViewBag.country, "--Select--")
#Html.DropDownList("state", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")
Controller
public JsonResult GetCustomerNameWithId(string Country)
{
int _Country = 0;
int.TryParse(Country, out _Country);
var listItems = GetCustomerNameId(_Country).Select(s => new SelectListItem { Value = s.CountryID.ToString(), Text = s.CountryName }).ToList<SelectListItem>();
return Json(listItems, JsonRequestBehavior.AllowGet);
}