Laravel ajax respond appending to body but not to #results - ajax

I have problem with outputting results from search in a div with id 'results' if I append the results to body they show up but when I change it to #results it's never appearing.
Search box is in navigation in master.blade.php and every other page includes it.
master.blade.php
<form id="search_form" action="/search" method="get" autocomplete="off" class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" id="search_text" onkeyup="search_data(this.value);" placeholder="Search">
</div>
<div id="result">
<table style="width:100%">
#if (isset($results) && count($results) > 0)
#foreach( $results as $business )
<tr>
<td>{{ $business->logo }}</td>
<td>{{ $business->name}}</td>
</tr>
#endforeach
#endif
</table>
</div>
</div>
</form>
Controller:
public function search($search_value) {
$search_text = $search_value;
if ($search_text==NULL) {
$data= Business::all();
} else {
$data=Business::where('name','LIKE', '%'.$search_text.'%')->get();
}
//$data = $data->toArray();
return view('master')->with('results',$data);
}
Ajax:
function search_data(search_value) {
$.ajax({
url: '/searching/' + search_value,
type: 'post',
dataType: 'html',
success: function(data) {
$('#results').append(data);
},
error: function(data) {
$('body').html(data);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
Route::
Route::post('/searching/{search}', 'SearchController#search');
If I actually look into ajax response, result is there:
<table style="width:100%">
<tr>
<td></td>
<td>dasd</td>
</tr>
</table>
But it never appears on the page! It does if the append is changed to body.
//edit
I have a loading gif which worked fine but now it never dissapears and each time it executed ajax, it doesn't want to dissapear too:
$(document).ajaxStart(function() { Pace.restart(); });
$(window).on('load', function () {
setTimeout(function(){
$('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
});
}); // set the time here
});
$(document).ready(function() {
setTimeout(function() {
$(".messages").fadeOut(5000);
});
setTimeout(function() {
$(".messages").fadeOut(5000);
});
});
css:
.se-pre-con {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
opacity: 0.5;
background-color: #6d6968;
background: url(../images/default.gif) center no-repeat #fff;
}

jQuery.ajaxSetup({
beforeSend: function (xhr, data) {
$('.se-pre-con').show();
},
complete: function ()
{
$('.se-pre-con').hide();
}
});

Related

Google chart does not redraw the chart based on a new Ajax filter

How can I make this code update the google chart with new Ajax call data? When I submit from the dropdown list I see the updated data in the echoed results but the chart does not update. It seems like I have place the submit code in the wrong place.
<title>Google Chart in PHP and MySQL</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var drawChart;
$(document).ready(function () {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON",
success: function (result) {google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(function () {drawChart(result);
});
}
});
$(".submit").click(function() {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON",
success: function (result) {google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(function () {drawChart(result);
});
}
});
});
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'HowMany');
var dataArray = [];
$.each(result, function (i, obj) {
dataArray.push([obj.Gender, parseInt(obj.HowMany)]);
});
data.addRows(dataArray);
var piechart_options = {
title: 'Gender breakdown',
width: 470,
height: 270,
colors: ['#800080', '#b200ff']
};
var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));
piechart.draw(data, piechart_options);
}
});
</script>
</head>
<body>
<center>
<img src="logo.png" style="width:200px;height:60px;">
</center>
<hr style="border: 4px solid blue;" />
<table class="columns" style="width:120%">
<tr>
<td>
<label>Gender filter</label>
<?php
//Connect to our MySQL database using the PDO extension.
$pdo = new PDO('mysql:host=localhost;dbname=panel', 'root', '');
//Our select statement. This will retrieve the data that we want.
$sql = "SELECT DISTINCT Gender FROM employee GROUP BY Gender";
//Prepare the select statement.
$stmt = $pdo->prepare($sql);
//Execute the statement.
$stmt->execute();
//Retrieve the rows using fetchAll.
$Ngender = $stmt->fetchAll();
?>
<!--Start here -->
<form method="post" action="indexdash2.php">
<select name="filter">
<option value="" disabled selected hidden>Choose a filter</option>
<?php foreach($Ngender as $Ngender): ?>
<option value="<?= $Ngender['Gender']; ?>"><?= $Ngender['Gender']; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="submit" value="Find">
</form>
</td>
</table>
<hr style="border: 4px solid blue;" />
<h2>DEMOGRAPHICS</h2>
<table class="columns">
<tr>
<td>
<div id="piechart_div" style="border: 1px solid #ccc"></div>
</td>
</tr>
</table>
</body>
</html>
Any help will be appreciated! I am pretty sure I have missed something basic as I am new to this.
first, google's load method only needs to be called once per page load.
afterwards, you can draw the chart, or charts, as many times as needed.
next, google's load method will also wait on the page to load by default.
so we can use load in place of jquery's ready method.
recommend loading google first,
then make the call to get the data and draw the chart.
see following snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
function getData() {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON"
}).done(function (result) {
drawChart(result);
});
}
$('.submit').click(getData);
getData();
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'HowMany');
$.each(result, function (i, obj) {
data.addRow([obj.Gender, parseInt(obj.HowMany)]);
});
var piechart_options = {
title: 'Gender breakdown',
width: 470,
height: 270,
colors: ['#800080', '#b200ff']
};
var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));
piechart.draw(data, piechart_options);
}
});

Laravel Ajax working fine on page reload but when I use Ajax to filter data pagination with jsscroll does not work

Pagination links working fine as normal pages when I refresh the whole page but when i reload just data with ajax pagination does not loading next pages
$.ajax({
url: '{{route('apply.filters')}}',
type:'get',
data: {cities:cities,
category:category
},
success: function (data) {
// $(".contentlist").load(location.href + " .contentlist");
$('.contentlist').html(data);
},
error: function(xhr, status, errorThrown) {
console.log(xhr.responseText);
}
});
this is my controller function
public function filter(Request $request)
{
try {
set_time_limit(390);
$country=null;
if(Auth::check() && $country==null){
$country=Auth::user()->lat->country??'';
}if(Session::has('country') && $country==null){
$country=Session::get('country.0');
}
if(isset($request->cities)){
$data =[
'products' => Product::where([['category',$request->category],['country',$country??'']])->whereIn('city',$request->cities)->where('status',1)->Orderby('id','desc')->paginate(8),
];
}
if(isset($data)){
return response()->json(view('front.home.ajaxindex',$data)->render());
}else{
return redirect()->route('home');
}
} catch(\Exception $e) {
return back()->with('error',$e->getMessage());
}
}
this is my jsscroll function working normally fine but not loading data comes with ajax
$('ul.pagination').hide();
$(function() {
$('.contentlist').jscroll({
autoTrigger: true,
loadingHtml: '<img class="center-block" src="{{asset('front_assets/images/Spinner-1s-200px.gif')}}" width="100" alt="Loading..." />', // MAKE SURE THAT YOU PUT THE CORRECT IMG PATH
padding: 0,
nextSelector: '.pagination li.active + li a',
contentSelector: 'div.contentlist',
loadOnScroll: false,
callback: function() {
$('ul.pagination').remove();
$('.elements').each(function(){
var thisH = $(this).height();
if (thisH > maxHeight) {
maxHeight = thisH;
}
$(this).height(maxHeight);
});
}
});
});
this is my ajaxindex page this is new page only created for making html which is appended in the main page if data exists
#foreach($products as $product)
<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12 item-cell">
<div class="listingscontent elements">
#if(\Illuminate\Support\Facades\Auth::guard('admin')->check())
<i id="{{$imgs->id??''}}" onclick="deletes('{{$product->id}}',this)" class="fa fa-close fa-lg pull-right" style="margin-left: -20px; mix-blend-mode: hard-light; color: rgb(0, 255, 255); "></i>
<a style=" position: absolute;" class="pull-left" href="{{route('edit.add',['id' => preg_replace('/-{2,}/','-',str_replace([" ", "'", "/","(",")","#","#"], '-',$product->title??'')).'-'.$product->id??''])}}"> <i class="fa fa-pencil-square-o fa-lg" style="mix-blend-mode: hard-light; color: rgb(0, 255, 255); "></i></a>
#endif
<a style="color: #ea1b25" href="{{route('details',['id' => preg_replace('/-{2,}/','-',str_replace([" ", "'", "/","(",")","#","#"], '-',$product->title??'')).'-'.$product->id??''])}}">
#if(isset($product->atachedImage))
<img class="listings" src="{{asset($product->atachedImage->path.$product->atachedImage->name??'noimage.jpg')}}" title="{{$product->title??''}}_image" alt="">
#else
<img class="listings" src="{{asset('images/noimage.jpg')}}" title="{{$product->title??''}}_image">
#endif
<h5 class="text-capitalize title" title="{{$product->title??''}}">{{str_limit($product->title??'',19)}}</h5></a>
</div>
</div>
#endforeach
{{$products->appends(request()->except('page'))->links()??''}}

how can I change pdf from datatable for pdf for serverside html2pdf?

I want to change my button pdf from buttons datatable for my pdf from server, but in the same position how can I do it? my url from html2pdf http://localhost/store_websocket/inventory/pdf and I want to change the button from pdfmaker from datatable in the position for my url for html2pdf because I want researching datatables fails with 1k or more rows then I decide server side procesing
controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class PDF extends MY_Controller {
public function __construct(){
parent::__construct();
}
public function index(){
require_once(APPPATH.'third_party/html2pdf/vendor/autoload.php');
$data['products'] = $this->products->datatable();
//print_r($data);
$template_pdf = $this->load->view('view_pdf', $data, TRUE);
$html2pdf = new HTML2PDF('P', 'A4', 'en');
$html2pdf->WriteHTML($template_pdf);
$html2pdf->Output('exemple.pdf');
}
}
view
<style type="text/css">
P {text-align:justify;font-size: 12pt;}
li {text-align:justify;font-size: 12pt;}
table.page_footer {width: 100%; border: none; border-top: solid 1px #000000; }
table.products {border-collapse: collapse; width: 100%;}
table.products th,td {text-align: left; padding: 8px;}
table.products thead tr{font-size: 9.5pt}
table.products th {background-color: #34495e; color: white;}
tbody tr {background-color: #f2f2f2;}
</style>
<page backtop="14mm" backbottom="14mm" backleft="10mm" backright="10mm" style="font-size: 12pt">
<page_footer>
<table class="page_footer">
<tr>
<td style="width: 100%; text-align: right">
page [[page_cu]]/[[page_nb]]
</td>
</tr>
</table>
</page_footer>
<div style="width:100%;text-align:center;">
<h1><b>List Inventory</b></h1>
</div>
<table class="products">
<thead>
<tr>
<th>Codigo</th>
<th>Descripcion</th>
<th>Precio compra</th>
<th>Precio venta</th>
<th>Precio mayoreo</th>
<th>Existencia</th>
</tr>
</thead>
<tbody>
<?php foreach ($products as $key): ?>
<tr>
<td><?php echo $key['id']?></td>
<td><?php echo $key['descripcion']?></td>
<td><?php echo $key['precio_compra']?></td>
<td><?php echo $key['precio_venta']?></td>
<td><?php echo $key['precio_mayoreo']?></td>
<td><?php echo $key['existencia']?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</page>
AJAX
$(function(){
URL_GET_DATATABLE = BASE_URL+'inventory/product/datatable';
URL_GET_VIEW_PRODUCT = BASE_URL+'inventory/product/getViewProduct';
URL_GET_ADD_PRODUCT = BASE_URL+'inventory/product/addProduct';
var table = $('#example').DataTable({
"lengthChange": false,
responsive: true,
dom: 'Blfrtip',
buttons: [{
extend: 'excelHtml5',
exportOptions:{
columns: [1,2,3,4,5,6]
}
},{
extend: 'csvHtml5',
exportOptions:{
columns: [1,2,3,4,5,6]
}
},{
extend: 'pdf',
exportOptions: {
columns: [1,2,3,4,5,6]
}
}],
ajax: {
url: URL_GET_DATATABLE,
type: 'POST',
},
columnDefs:[{
targets: -1,
data: null,
defaultContent: "<a href='#'><span class='glyphicon glyphicon-pencil'></span></a>"
},{
targets: 6,
render: function (data) {
return (data == 1) ? "<span class='label label-success'>active</span>":"<span class='label label-danger'>inactive</span>";
}
}],
fnRowCallback: function (data,nRow) {
if (nRow[6] == 0) {
$(data).css({'background-color':'#f2dede'})
}else if(nRow[6] == 1){
$(data).css({'background-color':'#dff0d8'})
}else{
}
}
});
$('#example tbody').on('click','a', function(e){
alert('thing');
});
$('#add').on('click',function(){
$("#description").mask("(999) 999-9999");
$("#new_product").validate();
BootstrapDialog.show({
type: BootstrapDialog.TYPE_PRIMARY,
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 min_stock = $('#min_stock').val();
var stock = $('#stock').val();
var max_stock = $('#max_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, min_stock: min_stock, stock: stock, max_stock: max_stock}
}).done(function (data) {
console.log(data);
if (data.msg == 'successfully added') {
$('#new_product')[0].reset();
table.ajax.reload();
}else if(data.min_stock == 'el stock no puede ser mayor al min'){
BootstrapDialog.show({
type: BootstrapDialog.TYPE_WARNING,
message: 'el stock no puede ser mayor al min'
});
}
});
return false;
}
}
},{
id: 'btn-cancel',
cssClass: 'btn-danger',
icon: 'glyphicon glyphicon-remove',
label: ' Cancel',
action: function (e) {
e.close();
}
}]
});
});
});

Uncaught ReferenceError: year is not defined in google chart using ajax/codeigniter

Good day. I want to make my column char working with database but I got this error says "Uncaught ReferenceError: year is not defined". here is my code.
JAVASCRIPT
function year()
{
var e = document.getElementById("selectyear");
var year = e.options[e.selectedIndex].text;
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('chartcontroller/chart/')?>/" + year,
type: "GET",
dataType: "JSON",
success: function(data)
{
drawChart1(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart1);
function drawChart1(data) {
var data = google.visualization.arrayToDataTable([
['Courses', 'S.Y. 2011-2012', 'S.Y. 2012-2013','S.Y. 2013-2014'],
for(var i = 1; i < data.length; i++) {
comment = data[i];
[comment.Course, comment.year_a, comment.year_b, comment.year_c],
}
]);
var options = {
title: 'ColumnChart',
hAxis: {title: 'Courses', titleTextStyle: {color: 'blue'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
//ajax end
and my view html
<div class="grid text-center" style="display: block;">
<h1 style=" color: black; font-size: 18px;">Summary of Daily Utilization of Library Holdings per Department</h1>
<div class="input-group">
<span class="input-group-addon">#</span>
<select id="selectyear" class="form-control selectyear" data-mobile="true" name="year" onchange="year();">
<?php
for ($i=$min_year; $i <= $max_year; $i++) {
echo "<option>".$i."</option>";
}
?>
</select>
</div>
<h1 style=" color: gray; font-size: 14px;">S. Y. 2011-2012, 2012-2013 & 2013-2014</h1>
<div id="chart_div1" class="chart" style="height: 400px; width: 100%;"></div>
<div id="chart_div2" class="chart" style="height: 400px; width: 100%;"></div>
in my controller
public function chart($year)
{
$data = $this->views->chart($year);
//Either you can print value or you can send value to database
echo json_encode($data);
}
no problem with ajax because when I do a debugging ajax successfully retrieve the value from database, the problem is when I put that value to my column chart like what I did in my code I've got that error.. help me please. this is the last problem I have to my thesis project.. thanks. I want to change the column chart value if the drop down has change.

ASP.NET MVC3: Ajax postback doesnot post complete data from the view

Hi Greetings for the day!
(1) The view model (MyViewModel.cs) which is bound to the view is as below...
public class MyViewModel
{
public int ParentId { get; set; } //property1
List<Item> ItemList {get; set;} //property2
public MyViewModel() //Constructor
{
ItemList=new List<Item>(); //creating an empty list of items
}
}
(2) I am calling an action method through ajax postback (from MyView.cshtml view) as below..
function AddItem() {
var form = $('#MyForm');
var serializedform = form.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/AddItem")',
cache: false,
data: serializedform,
success: function (html) {$('#MyForm').html(html);}
});
}
The below button click will call the ajax postback...
<input type="button" value="Add" class="Previousbtn" onclick="AddItem()" />
(3) I have an action method in the (MyController.cs controller) as below...
public ActionResult AddItem(MyViewModel ViewModel)
{
ViewModel.ItemList.Add(new Item());
return View("MyView", ViewModel);
}
Now the issue is, after returning from the action, there is no data in the viewmodel. But i am able to get the data on third postback !! Can you pls suggest the solution..
The complete form code in the view is below...
#model MyViewModel
<script type="text/javascript" language="javascript">
function AddItem() {
var form = $('#MyForm');
var serializedform = form.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/AddItem")',
cache: false,
data: serializedform,
success: function (html) {
$('#MyForm').html(html);
}
});
}
function RemoveItem() {
var form = $('#MyForm');
var serializedform = form.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/RemoveItem")',
cache: false,
data: serializedform,
success: function (html) {
$('#MyForm').html(html);
}
});
}
function SaveItems() {
var form = $('#MyForm');
var serializedform = forModel.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/SaveItems")',
cache: false,
data: serializedform,
success: function (html) {
$('#MyForm').html(html);
}
});
}
</script>
#using (Html.BeginForm("SaveItems", "MyController", FormMethod.Post, new { id = "MyForm" }))
{
#Html.HiddenFor(m => Model.ParentId)
<div>
<input type="button" value="Save" onclick="SaveItems()" />
</div>
<div>
<table>
<tr>
<td style="width: 48%;">
<div style="height: 500px; width: 100%; overflow: auto">
<table>
<thead>
<tr>
<th style="width: 80%;">
Item
</th>
<th style="width: 10%">
Select
</th>
</tr>
</thead>
#for (int i = 0; i < Model.ItemList.Count; i++)
{
#Html.HiddenFor(m => Model.ItemList[i].ItemId)
#Html.HiddenFor(m => Model.ItemList[i].ItemName)
<tr>
#if (Model.ItemList[i].ItemId > 0)
{
<td style="width: 80%; background-color:gray;">
#Html.DisplayFor(m => Model.ItemList[i].ItemName)
</td>
<td style="width: 10%; background-color:gray;">
<img src="#Url.Content("~/Images/tick.png")" alt="Added"/>
#Html.HiddenFor(m => Model.ItemList[i].IsSelected)
</td>
}
else
{
<td style="width: 80%;">
#Html.DisplayFor(m => Model.ItemList[i].ItemName)
</td>
<td style="width: 10%">
#if ((Model.ItemList[i].IsSelected != null) && (Model.ItemList[i].IsSelected != false))
{
<img src="#Url.Content("~/Images/tick.png")" alt="Added"/>
}
else
{
#Html.CheckBoxFor(m => Model.ItemList[i].IsSelected, new { #style = "cursor:pointer" })
}
</td>
}
</tr>
}
</table>
</div>
</td>
<td style="width: 4%; vertical-align: middle">
<input type="button" value="Add" onclick="AddItem()" />
<input type="button" value="Remove" onclick="RemoveItem()" />
</td>
</tr>
</table>
</div>
}
You must return PartialViewResult and then you can do something like
$.post('/controller/GetMyPartial',function(html){
$('elem').html(html);});
[HttpPost]
public PartialViewResult GetMyPartial(string id
{
return PartialView('view.cshtml',Model);
}
In my project i get state data with country id using json like this
in my view
<script type="text/javascript">
function cascadingdropdown() {
var countryID = $('#countryID').val();
$.ajax({
url: "/City/State",
dataType: 'json',
data: { countryId: countryID },
success: function (data) {
alert(data);
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
$.each(data, function (index, optiondata) {
alert(optiondata.StateName);
$("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
});
},
error: function () {
alert('Faild To Retrieve states.');
}
});
}
</script>
in my controller return data in json format
public JsonResult State(int countryId)
{
var stateList = CityRepository.GetList(countryId);
return Json(stateList, JsonRequestBehavior.AllowGet);
}
i think this will help you ....
I resolved the issue as below...
Issue:
The form code i have shown here is actually part of another view page
which also contains a form. So, when i saw the page source at
run-time, there are two form tags: one inside the other, and the
browser has ignored the inner form tag.
Solution:
In the parent view page, earlier i had used Html.Partial to render
this view by passing the model to it.
#using(Html.BeginForm())
{
---
---
#Html.Partial('/MyArea/Views/MyView',MyViewModel)
---
---
}
But now, i added a div with no content. On click of a button, i'm
calling an action method (through ajax postback) which then renders
the above shown view page (MyView.cshmtl) into this empty div.
#using(Html.BeginForm())
{
---
---
<div id="divMyView" style="display:none"></div>
---
---
}
That action returns a separate view which is loaded into the above
div. Since it is a separate view with its own form tag, i'm able to
send and receive data on each postback.
Thank you all for your suggestions on this :)

Resources