Live search in Laravel with Ajax - laravel-5

Hello team I failed to display data after type to the search button there is no error that displayed
Here is my controller
public function search(Request $request)
{
if ($request->ajax()) {
$output = "";
$products = DB::table('particulars')->where('item_name', 'LIKE', '%' . $request->search . "%")->get();
if ($products) {
foreach ($products as $key => $product) {
$output .= '<tr>' .
'<td>' . $product->id . '</td>' .
'<td>' . $product->item_name . '</td>' .
'<td>' . $product->quantity . '</td>' .
'<td>' . $product->price . '</td>' .
'</tr>';
}
return Response($output);
}
}
}
my view
<td>
<div class="row">
<div class="col-lg-12" style="">
<div class="input-group">
<div class="input-group-addon">
<span class="glyphicon glyphicon-search"></span>
</div>
<input type="text" class="form-control" id="search" name="search" placeholder="Search here...">
</div>
</div>
</div>
</td>
Here is the script
<script type="text/javascript">
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '/search',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
})
</script>
but I failed to retrieve data and show no error please team help me

Related

Laravel 5 simple search box using GET method

I want to search code for enter an admin.
web.php
Route::get('/document', 'DocumentController#document')->name('document');
DocumentController.php
public function document()
{
$keyword = request('code');
$documents = Document::document($keyword)->latest()->get();
return view('Home.content.documents', compact('documents'));
}
Document.php
public function scopeDocument($query, $keywords)
{
$keywords = explode(' ',$keywords);
foreach ($keywords as $keyword) {
$query->where('code' , 'LIKE' , '%' . $keyword . '%');
}
return $query;
}
documents.blade,php
<form action="{{ route('document') }}" method="get">
<div class="form-group">
<label for="code">Code</label>
<input type="text" class="form-control col-sm-4" id="code" name="code">
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>
<div class="text-center">
#foreach($documents as $document)
<h1 class="m-3">{{ $document->first_name }} {{ $document->last_name }}</h1>
<img src="images/documents/{{ $document->image }}" class="img-fluid">
#endforeach
</div>
Why this code is not working?

Foreach in Yajra DataTable Laravel

I'm trying to put a foreach loop inside my datatable but it wont work,
P.S. if I remove the foreach everything works fine already,
attached here is my code
$Product = Product::query();
$colors = Color::all();
return Datatables::eloquent($Product)
->addColumn('category_name', function($row) {
$category = Category::select('name')->where('id', $row->category_id )->pluck('name')->toArray();
return $category;
})
->addColumn('add_color', function($row) {
$return =
'<form class="form-inline" method="post" action="/procurement/add-product" style="max-width: 170px;">
<input type="hidden" name= "product_id" value="' . $row->id . '">
<div class="form-group">
<select name="color_id" class="form-control" required autofocus>
'.foreach ($colors as $color){.'
<option value="test">test</option>'.}.'
</select>
</div>';
return $return;
});
That won't work, you're attaching a foreach into a string
What you may do is perform the foreach first to prepare the items you want to attach in that string.
E.g.,
<option>something</option>
<option>something more</option>
Before setting the $return do the foreach:
->addColumn('add_color', function($row) {
$options = ''
// here we prepare the options
foreach ($colors as $color) {
$options .= '<option value="test">$color</option>';
}
$return =
'<form class="form-inline" method="post" action="/procurement/add product" style="max-width: 170px;">
<input type="hidden" name= "product_id" value="'.$row->id.'">
<div class="form-group">
<select name="color_id" class="form-control" required autofocus>' . $options . '</select>
</div>';
return $return;
})
You need to perform foreach outside your return. and then you also need no use or import the $color variable inside your data table. something like this ..
$Product = Product::query();
$colors = Color::all();
return Datatables::eloquent($Product)
->addColumn('category_name', function($row) {
$category = Category::select('name')->where('id', $row->category_id )->pluck('name')->toArray();
return $category;
})
->addColumn('add_color', function($row) use ($colors) {
$options = '';
foreach ($colors as $color) {
$options .= '<option value="test">$color</option>';
}
$return =
'<form class="form-inline" method="post" action="/procurement/add-product" style="max-width: 170px;">
<input type="hidden" name= "product_id" value="' . $row->id . '">
<div class="form-group">
<select name="color_id" class="form-control" required autofocus>
</select>
</div>';
return $return;
});

dropzone server implementation

I just started using the dropzone plugin and i'm using laravel in my project. I want to know how to get the files uploaded so i can store them in my database. this is my view :
<form action="{{route('realisation.storeimg')}}" method="POST" files="true" enctype="multipart/form-data"
data-toggle="validator" role="form" class="dropzone" id="my-awesome-dropzone">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="table table-striped" class="files" id="previews">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail/></span>
</div>
<div>
<p class="name" data-dz-name></p>
<strong class="error text-danger" data-dz-errormessage></strong>
</div>
<div>
<p class="size" data-dz-size></p>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100"
aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
</div>
<div>
<button class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i>
<span>Start</span>
</button>
<button data-dz-remove class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel</span>
</button>
<button data-dz-remove class="btn btn-danger delete">
<i class="glyphicon glyphicon-trash"></i>
<span>Delete</span>
</button>
</div>
</div>
</div>
<input type="hidden" name="realisation_id" value="{{$realisation->id}}">
</form>
my route for the upload:
Route::post('/storeimg',[
'as'=>'realisation.storeimg',
'uses'=>'RealisationController#storeimg'
]);
my controller:
public function storeimg (Request $request)
{
$realisation = Realisation::where('id','realisation_id')->first();
if($request->file('image')) {
foreach ($request->file('image') as $image) {
$realisation_image = Realisationimg::where('realisation_id','realisation_id')->first();
File::delete($realisation_image->image);
File::delete($realisation_image->image_thumb);
$extension = $image->getClientOriginalExtension();
$name = substr($image->getClientOriginalName(), 0, -4);
list($width, $height) = getimagesize($image);
$imgname = str_slug($name, '_');
$filename = $imgname.'.'.$extension;
if(file_exists('uploads/realisationimg/cover/' . $filename)){
do {
$newname = $imgname.'_'.str_random(3) . '.' . $extension;
}
while(file_exists('uploads/realisationimg/cover/' . $newname));
$filename = $newname;
}
$path = 'uploads/realisationimg/cover/'.$filename;
$path_thumb = 'uploads/realisationimg/thumb/'.$filename;
$save = Image::make($image->getRealPath())->resize(1600, null, function ($constraint){
$constraint->aspectRatio();
})->save($path);
$save = Image::make($image->getRealPath())->resize(1600, null, function ($constraint){
$constraint->aspectRatio();
})->save($path_thumb);
$realisation_image->image = $path;
$realisation_image->image_thumb = $path_thumb;
$realisation_image->realisation_id = $id;
$realisation_image->save();
}
}
Session::flash('ajouter','ok');
return redirect(route('realisation.edit',['id'=>$request->get('realisation_id')]));
}
in the dropzone.js file i changed the default options to the following:
uploadMultiple: true,
paramName: "image",
when i submit the dropzone form nothing gets executed (no files are stored and nothing in my database). can someone point to me my mistake? thanks.
Here is s sample code that might help.
Route:
Route::post('/storeimg', 'GalleryController#storeimg')
->name('realisation.storeimg');
Controller:
public function storeimg(Request $request)
{
$path = $request->file('file')->store('public/photo');
if (!$path)
return url('storage');
$dirs = explode('/', $path);
if ($dirs[0] === 'public')
$dirs[0] = 'storage';
$data['image'] = url(implode('/', $dirs));
Photo::create($data);
session()->flash('success', 'Photos uploaded successfully');
return response()->json(['success'=>$data['image']]);
}
View: Just open file to send files to controller.
{!! Form::open([ 'route' => [ 'realisation.storeimg'], 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'image-upload' ]) !!}
{!! Form::close() !!}
<link rel="stylesheet" href="../dropzone.min.css">
<script src="../dropzone.min.js"></script>
<script type="text/javascript">
Dropzone.options.imageUpload = {
maxFilesize : 1,
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};
//Remove Photo
$("body").on("click",".remove-item",function(){
var id = $(this).parent("td").data('id');
var c_obj = $(this).parents("tr");
console.log(id);
$.ajax({
dataType: 'json',
type:'delete',
url: url + '/' + id,
}).done(function(data){
c_obj.remove();
});
});
</script>
This is result in a dropzone box where you can add multiple photos at a time

Multidimensional input with codeigniter not setting second array correct

On my controller function get form I get my banner images and I also use multidimensional array in my view
For some reason, the second banner_image title not showing but the value has been placed on the first array instead?
print_r($_POST)
Question How am I able to make sure that no matter how many banner images I select it can set the multidimensional array correct for each post.
public function getForm()
{
$banner_id = $this->uri->segment(5);
if ($banner_id)
{
$data['action'] = 'admin/design/banners/edit/' . $banner_id;
} else {
$data['action'] = 'admin/design/banners/add';
}
$banner_info = $this->admin_model_banner->getBanner($banner_id);
if ($this->input->post('banner_name')) {
$data['banner_name'] = $this->input->post('banner_name');
} elseif (!empty($banner_info)) {
$data['banner_name'] = $banner_info['banner_name'];
} else {
$data['banner_name'] = '';
}
if ($this->input->post('banner_status')) {
$data['banner_status'] = $this->input->post('banner_status');
} elseif (!empty($banner_info)) {
$data['banner_status'] = $banner_info['status'];
} else {
$data['banner_status'] = '';
}
$banner_images = array();
$banner_images_post = $this->input->post('banner_image');
if (isset($banner_images_post)) {
$banner_images = $this->input->post('banner_image');
} elseif (isset($banner_id)) {
$banner_images = $this->admin_model_banner->getBannerImages($banner_id);
}
$data['banner_images'] = array();
foreach ($banner_images as $banner_image)
{
if (is_file(FCPATH . 'image/' . $banner_image['image'])) {
$image = $banner_image['image'];
$thumb = $banner_image['image'];
} else {
$image = '';
$thumb = 'catalog/no_image.jpg';
}
$data['banner_images'][] = array(
'image' => $image,
'thumb' => $this->model_tool_image->resize($thumb, 100, 100),
'title' => $banner_image['title'],
'sort_order' => $banner_image['sort_order']
);
}
$data['placeholder'] = $this->model_tool_image->resize('catalog/no_image.jpg', 100, 100);
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('design/banner_form_view', $data);
}
View
<?php echo $header;?>
<div class="container">
<?php
$form = array(
'id' => '',
'role' => 'form',
'class' => 'form-horizontal'
);
echo form_open_multipart($action, $form);?>
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body">
<div class="form-group">
<label class="col-lg-2">Banner Status</label>
<div class="col-lg-10">
<input type="text" name="banner_name" class="form-control" placeholder="Enter Banner Name" value="<?php echo $banner_name;?>" size="50"/>
<?php echo form_error('banner_name', '<div class="text-danger" style="margin-top: 2rem;">', '</div>'); ?>
</div>
</div>
<div class="form-group">
<label class="col-lg-2">Banner Name</label>
<div class="col-lg-10">
<?php
$options = array('1' => 'Enabled', '0' => 'Disabled');
echo form_dropdown('banner_status', $options, $banner_status, array('class' => 'form-control'));
?>
</div>
</div>
<table id="images" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td class="text-left">Title</td>
<td class="text-left">Image</td>
<td>Sort Order</td>
</tr>
</thead>
<tbody>
<?php $image_row = 0; ?>
<?php foreach ($banner_images as $banner_image) { ?>
<tr id="image-row<?php echo $image_row; ?>">
<td class="text-left">
<input type="text" name="banner_image[<?php echo $image_row; ?>][title]" value="<?php echo $banner_image['title']; ?>" class="form-control">
</td>
<td class="text-left">
<a href="" id="thumb_image_<?php echo $image_row; ?>" data-toggle="image" class="img-thumbnail">
<img src="<?php echo $banner_image['thumb']; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" />
</a>
<input type="hidden" name="banner_image[<?php echo $image_row; ?>][image]" value="<?php echo $banner_image['image']; ?>" id="input_image_<?php echo $image_row; ?>" /></td>
<td class="text-right"><input type="text" name="banner_image[<?php echo $image_row; ?>][sort_order]" value="<?php echo $banner_image['sort_order']; ?>" placeholder="Sort Order" class="form-control" /></td>
<td class="text-left">
<button type="button" onclick="$('#image-row<?php echo $image_row; ?>').remove();" class="btn btn-danger"><i class="fa fa-trash" aria-hidden="true"></i></button></td>
</tr>
<?php $image_row++; ?>
<?php } ?>
</tbody>
<tfoot>
<tr>
<td colspan="3"></td>
<td class="text-left">
<button type="button" onclick="addImage();" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button>
</td>
</tr>
</tfoot>
</table>
</div>
<div class="panel-footer">
<div class="text-right"><button type="submit" class="btn btn-primary"><i class="fa fa-floppy-o" aria-hidden="true"></i> Save</button></div>
</div>
</div>
<?php echo form_close();?>
</div>
<script type="text/javascript">
var image_row = <?php echo $image_row; ?>;
function addImage()
{
html = '<tr id="image-row' + image_row + '">';
html += '<td class="text-left">';
html += '<input type="text" name="banner_image[<?php echo $image_row; ?>][title]" class="form-control" value="">';
html += '</td>';
html += '<td class="text-left">';
html += '<a href="" id="thumb_image_' + image_row + '" data-toggle="image" class="img-thumbnail">';
html += '<img src="<?php echo $placeholder; ?>" data-placeholder="<?php echo $placeholder; ?>"/>';
html += '</a>';
html += '<input type="hidden" name="banner_image[' + image_row + '][image]" value="" id="input_image_' + image_row + '" />';
html += '</td>';
html += '<td class="text-right">';
html += '<input type="text" name="banner_image[' + image_row + '][sort_order]" value="" placeholder="Sort Order" class="form-control" />';
html += '</td>';
html += '</tr>';
$('#images tbody').append(html);
image_row++;
}
</script>
Solved
After doing some investigation I found problem was to do with
name="banner_image[<?php echo $image_row; ?>][title]"
On script, I forgot to add it like
name="banner_image[' + image_row + '][title]"
Working now

pagination links will not work

On my users index page I am trying to set up the CI Pagination. But when I click on the 2nd link will load a error page "Unable to load page"; I have spent all day on it and will not load on the same page. I use hmvc I am not sure if that effects it?
How can I make it load on same page. As what most tutorials I have watched show. Like the tuts plus tutorial.
$config['base_url'] = 'http://localhost/codeigniter-project/';
URL http://localhost/codeigniter-project/admin/users/
Route $route['admin/users'] = "admin/user/users/index";
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends MX_Controller {
public function __construct() {
parent::__construct();
$this->lang->load('admin/user/users', 'english');
$this->load->model('admin/user/users_model');
if (!$this->user->logged()) {
redirect('admin');
}
}
public function index() {
$this->document->setTitle($this->lang->line('heading_title'));
$data['heading_title'] = $this->lang->line('heading_title');
$this->load->library('setting');
$this->load->library('pagination');
$config = array();
$config["base_url"] = base_url('admin/users');
$config['total_rows'] = $this->db->get('user')->num_rows();
$config["per_page"] = $this->setting->get('config_limit_admin');
$config["uri_segment"] = 3;
$this->pagination->initialize($config);
$data['user'] = $this->db->get('user', $config["per_page"], $this->uri->segment(3));
return $this->load->view('user/users_list', $data);
}
}
View
<?php echo Modules::run('admin/common/header/index');?><?php echo Modules::run('admin/common/column_left/index');?>
<div id="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<?php if ($this->session->flashdata('error')) { ?>
<div class="alert alert-danger"><i class="fa fa-times-circle"></i> <?php echo $this->session->flashdata('error');?></div>
<?php } ?>
<?php if ($this->session->flashdata('success')) { ?>
<div class="alert alert-success"><i class="fa fa-check-circle"></i> <?php echo $this->session->flashdata('success');?></div>
<?php } ?>
</div>
</div>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title"><?php echo $heading_title; ?></h3></div>
<div class="panel-body">
<?php
echo '<div class="table-responsive">';
echo '<table class="table table-striped table-bordered table-hover">';
echo '<thead>';
echo '<tr>';
echo '<td class="text-center">' . "User ID" . '</td>';
echo '<td class="text-center">' . "Username" . '</td>';
echo '<td class="text-center">' . "Status" . '</td>';
echo '<td class="text-center">' . "Date Added" . '</td>';
echo '<td class="text-center">' . "Action" . '</td>';
echo '</tr>';
echo '</thead>';
foreach ($user->result() as $row) {
echo '<tbody>';
echo '<tr>';
echo '<td class="text-center">' . $row->user_id .'</td>';
echo '<td class="text-center">' . $row->username .'</td>';
echo '<td class="text-center">' . $row->status .'</td>';
echo '<td class="text-center">' . $row->date_added .'</td>';
echo '<td class="text-center">' . anchor("admin/users/edit/" . $row->user_id, '<div class="btn btn-primary text-right" role="button"><i class="fa fa-pencil"></i>
Edit</div>') .'</td>';
echo '</tr>';
echo '</tbody>';
}
echo '</table>';
echo '</div>';
echo '<div class="row">';
echo '<div class="col-sm-6 text-left">';
echo $this->pagination->create_links();
echo '</div>';
echo '</div>';
?>
</div><!-- . Panel Panel-Body -->
</div><!-- . Panel Panel-Default -->
</div><!-- . Columns -->
</div><!-- . Row -->
</div><!-- . Container-fluid-->
</div><!-- #Content -->
<?php echo Modules::run('admin/common/footer/index');?>
I just had a brain storm and added $route['admin/users/(:num)'] = "admin/user/users/index/$1"; and now links work.

Resources