draggable rows using ajax in laravel - javascript

i'm here trying to make a draggable rows for table and update the change in the database, so i follow on tutorial the drag and drop works fine but the changes not save in the database.
this is the tutorial i'm follow
https://shareurcodes.com/blog/create-drag-and-droppable-datatables-using-jquery-ui-sortable-in-laravel
and here my codes
searchController
class SearchController extends Controller {
public function index() {
// $customers = Customer::all();
$customers = Customer::orderBy('order', 'ASC') - > select('id', 'first_name', 'last_name', 'email', 'phone') - > get();
return view('search.search', compact('customers'));
}
public function updateOrder(Request $request) {
$customers = Customer::all();
//$customer = Customer::findOrFail($id);
foreach($customers as $customer) {
$customer - > timestamps = false;
$id = $customer - > id;
foreach($request - > order as $order) {
if ($order['id'] == $id) {
$customer - > update(['order' => $order['id']]);
}
//if($order['id'] = $id){
// $customer->update($request->all());
// }
}
}
return response('Update Successfully', 200);
}
}
search.blade.php
<script type="text/javascript">
$(function() {
$("#table").DataTable();
$("#tablecontents").sortable({
items: "tr",
// cursor: 'move',
opacity: 0.6,
update: function() {
sendOrderToServer();
}
});
function sendOrderToServer() {
let order = [];
$('tr.row1').each(function(index) {
order.push({
id: $(this).attr('data-id'),
position: index + 1
});
});
$.ajax({
type: "POST",
dataType: "json",
url: "{{ url('search.search') }}",
data: {
order: order,
_token: '{{csrf_token()}}'
},
success: function(response) {
if (response.status == "success") {
console.log(response);
} else {
console.log(response);
}
}
});
}
});
</script>
route
Route::post('search/search','searchController#updateOrder');
this is the table
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('phone');
$table->integer('order');
$table->timestamps();
when i drag and drop this error in the console
jquery.min.js:4 POST http://adminproject.test/search.search 404 (Not Found)

Can you try changing ajax route like below
url: "{{ url('search/search') }}"

it was a silly mistake,
just change the url in javascript
from
url: "{{ url('search.search') }}",
to
url: "{{ url('search') }}",

Related

pagination automatically sending multiple requests with laravel

hello guys recently I am developing a new website which have multiple filters so I use the session-based filter with laravel
it is working fine if I use only the Show filter one time but when I switch to another filter, it is sending multiple requests(as much time I repeat the filter)
when someone clicks the filter this code will run
<------- Laravel route where I am sending a request it returns me a HTML file and I am rendering in my div tag where I have all lists ------->
public function filter(Request $request){
$course = Course::query();
if (isset($request->show)) {
Session::put('show',$request->show);
$show = $request->show;
}
if(isset($request->type)){
$course->where('type',$request->type);
}
if (isset($request->ratting)) {
$course->where('ratting','>=',$request->ratting);
Session::put('ratting',$request->ratting);
}
if(isset($request->short_type))
{
$type = $request->short_type;
$course = $this->checkSort($course,$type);
Session::put('short',$type);
}
if (Session::has('search')) {
$search = Session::get('search');
$course->where(function($q) use ($search){
$q->where('title', 'LIKE', '%'.$search.'%')
->orWhere('slug', 'LIKE', '%'.$search.'%')
->orWhere('description', 'LIKE', '%'.$search.'%')
->orWhere('keyword', 'LIKE', '%'.$search.'%');
});
}
if(Session::has('show') && !isset($request->show)){
$show = Session::get('show');
}
if(Session::has('ratting') && !isset($request->ratting)){
$course->where('ratting','>=',Session::get('ratting'));
}
if(Session::has('short') && !isset($request->short)){
$type = Session::get('short');
$course = $this->checkSort($course,$type);
}
$course->select('id', 'title', 'slug', 'description', 'created_at', 'regular_price', 'sell_price', 'thumbnail','ratting','status');
return view('site.courses.ajax-listing',[
'active' => 'courses',
'type' => $request->type,
'courses' => $course->where('status',1)->paginate(isset($show) ? $show : 10),
]);
}
public function checkSort($courses,$type){
if($type == "alphabetically_a_z")
{
$courses->orderBy('title', 'ASC');
}
if($type == "alphabetically_z_a")
{
$courses->orderBy('title', 'DESC');
}
if($type == "date_new_to_old")
{
$courses->orderBy('created_at', 'ASC');
}
if($type == "date_old_to_new")
{
$courses->orderBy('created_at', 'DESC');
}
if($type == "popular")
{
$courses->where('is_popular', 1);
}
return $courses;
}
<------------------------------------------->
In the search input have route where i will send request
<input type="text" hidden id="search-url" value="{{route('ajax-search-course')}}">
<--------- Javascript Code ----->
$(document).ready(function(){
var url = "{{route('ajax-search-course')}}";
var Jobtype = "1";
var value;
$("input[name='RattingRadioDefault']:radio").change(function(){
value = $("[name=RattingRadioDefault]:checked").val();
ajaxFilter(url + "?ratting="+value+ "&type=" + Jobtype);
});
$("input[name='ShowingRadioDefault']:radio").change(function(){
value = $("[name=ShowingRadioDefault]:checked").val();
ajaxFilter(url + "?show=" + value + "&type=" + Jobtype);
});
$("input[name='ShortingRadioDefault']:radio").change(function(){
value = $("[name=ShortingRadioDefault]:checked").val();
console.log("this is value",value,$("[name=ShortingRadioDefault]:checked").val());
ajaxFilter(url + "?short_type=" + value + "&type=" + Jobtype);
});
});
function ajaxFilter(url, data = null) {
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function(data) {
// console.log("this is return data",data);
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function(jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
console.log("this is error", errorMessage);
}
});
}
<------------- Javascript pagination page ----------->
//Ajax Paginatio
$(document).one('click', '#ajaxPagination ul li a', function (e) {
console.log("ajax pagination function is running",$(this).attr("href"),"and",$(e).attr("href"));
e.preventDefault();
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
var url = $(this).attr("href")+"&"+ "type=" + $('#data_sort_filter').attr('job-type'),
data = '';
e.preventDefault();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function (jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
}
});
});
i was trying to add a multiple filters system with the session. now i have this error pagination function running as much i am repeating filters i want to solve this please help me it is a very important to project for me

How to update select option datatable laravel for current row or id

i have problem to update selected option .The database can be update ,but it update for all data .i just want to update current row only
javascript :
$(document).ready(function () {
$('#table_refund').on('change' ,'select', function() {
var data= $(this).closest('tr');
var status = $('option:selected',this).val();
alert(status);
$.ajax({
type: "get",
url: "/financial/approve/refund",
data: {status: status },
dataType: "JSON",
success: function (response) {
$('.alert').show();
}
});
});
controller:
public function studentrefund(Request $req)
{
//update table
data = Refund::find($req->userid);
$data->status = $req->status;
$data->save();
return response()->json(['success'=>'Saved successfully.']);
}
You Need to check particular Id and that userID so you get current row.
Controller::
public function studentrefund(Request $req)
{
//update table
$data = Refund::where('id',$req->id)->where('userid',$req->userid)->first();
$data->status = $req->status;
$data->save();
return response()->json(['success'=>'Saved successfully.']);
}
You can Use fundOrFail the findOrFail and firstOrFail methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown laravel.com/docs/5.1/eloquent#retrieving-single-models
public function studentrefund(Request $req)
{
//validate user id
request()->validate([
'userid' => 'required',
]);
//update table
$data = Refund::findOrFail($req->userid);
$data->status = $req->status;
$data->save();
return response()->json(['success'=>'Saved successfully.']);
}
option :
<select id="table_refund">
<option data-id="{{ $row->id }}" value="Aktive">Test Data</option>
</select>
Jquery :
$(document).ready(function() {
$('#table_refund').on('change', 'select', function() {
var id = $(this).data('id');
var status = $('option:selected', this).val();
$.ajax({
type: "POST",
url: "{{ url('financial/approve/refund') }}",
data: {
"id": id,
"status": status,
},
dataType: "JSON",
success: function(response) {
$('.alert').show();
}
});
});
Controller :
public function studentrefund(Request $request)
{
$data = Refund::findOrFail($request->id);
$data->status = $request->status;
$data->save();
return response()->json(['success'=>'Saved successfully.']);
}

How to delete image with ajax in laravel

I am trying to delete a record from my products table, each product has an image. I don't know how to delete the image from the file where it is stored.
Product.js
$(document).ready(function() {
$("#btn-delete").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/product/' + $("#frmDeleteProduct input[name=product_id]").val(),
dataType: 'json',
success: function(data) {
$("#frmDeleteProduct .close").click();
window.location.reload();
},
error: function(data) {
console.log(data);
}
});
});
});
function deleteProductForm(product_id) {
$.ajax({
type: 'GET',
url: '/product/' + product_id,
success: function(data) {
$("#frmDeleteProduct #delete-title").html("¿Do you want to delete this product (" + data.products.name + ")?");
$("#frmDeleteProduct input[name=product_id]").val(data.products.id);
$('#deleteProductModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
ProductController.php
I read that I need to put something like this in my controller File::delete('img/products/' . $image); but I don't now how.
public function destroy($id)
{
//File::delete('img/products/' . $image);
$products = Product::destroy($id);
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
You need to pass as a parameter to File::delete() the full path when your image was save. For example, if your images were in a laravel storage path in the subdirectory img/products/, and the name of the image is the id of the product with the .jpg extension, you can do this:
public function destroy($id)
{
$fullImgPath = storage_path("img/products/$id.jpg");
if(File::exists($fullImgPath)) {
File::delete($fullImgPath);
}
$products = Product::destroy($id);
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
But if you have the name of the image in your Product model, you can do this:
public function destroy($id)
{
$product = Product::find($id);
$fullImgPath = storage_path("img/products/".$product->image_name);
if(File::exists($fullImgPath)) {
File::delete($fullImgPath);
}
$product->delete();
return response()->json([
'error' => false,
'products' => $product->id,
], 200);
}

Infinite scroll in Symfony using Ajax

I wanted to show products from db using infinite scroll.
Here is my Controller:
$start=0;
$limit= 6;
$query = $repository->createQueryBuilder('classified')
->join('classified.statusId','status')
->andWhere('status.name=:status')
->setParameter('status','active')
->setFirstResult($start)
->setMaxResults($limit)
->getQuery();
$results = $query->getResult();
if ($request->isXmlHttpRequest()){
$list = $this->renderView('search-result.html.twig', [
'results' => $results
]);
$response = new JsonResponse();
$response->setData(array('classifiedList' => $list));
return $response;
}
Ajax:
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
getmoredata();
}
})
function getmoredata() {
$.ajax({
type: "GET",
url: "{{ path('classified_list', {'type' : 'all'}) }}",
dataType: "json",
cache: false,
success: function (response) {
$('.card-deck').append(response.classifiedList);
$('#spinner').hide();
console.log(response);
},
error: function (response) {
console.log(response);
}
});
}
So now what is happening is the first 6 results is repeatedly showing when the scrolling is triggered. I know this is not correct and I don't expect this to work properly. But what I don't know is what is the next step.
So do I need to add paginator or something?
Any help would be appreciated,Thanks!
You need to track whether your ajax is requesting or not, so it will not do request multiple times when window reach the scroll limit. Also, you need to track the offset and whether you have more data to loads. e.g
window.__isFetching = false;
window.__offset = 0;
window.__hasMoreData = true;
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
if(!window.__isFetching && window.__hasMoreData) {
getmoredata();
}
}
})
function getmoredata() {
window.__isFetching = true;
$.ajax({
type: "GET",
// NOTE, you can pass current offset here in url
url: "{{ path('classified_list', {'type' : 'all', }) }}"+"&offset="+window.__offset,
dataType: "json",
cache: false,
success: function (response) {
$('.card-deck').append(response.classifiedList);
$('#spinner').hide();
console.log(response);
// Note that here, server side response must have next offset and hasMoreData attribut.
window.__isFetching = false;
window.__hasMoreData = response.hasMoreData;
window.__offset = response.offset
},
error: function (response) {
console.log(response);
}
});
}
in server side , which is symfony, you might want to do something like:
// Get offset from request query
$start= $request->query->get('offset');
$limit= 6;
$query = $repository->createQueryBuilder('classified')
->join('classified.statusId','status')
->andWhere('status.name=:status')
->setParameter('status','active')
->setFirstResult($start)
->setMaxResults($limit)
->getQuery();
$results = $query->getResult();
if ($request->isXmlHttpRequest()){
$list = $this->renderView('search-result.html.twig', [
'results' => $results
]);
$response = new JsonResponse();
// And add offset and hasMoreData fields in response
$response->setData(array(
'classifiedList' => $list,
'offset' => $start += 1
'hasMoreData' => count($list) < ($limit * &start)
)
);
return $response;

laravel 5.3: HTTP/1.0 405 Method Not Allowed

route:
Route::post('serial', 'HomeController#serial');
Route::get('doctorlist',['as'=>'doctorlist','uses'=>'HomeController#doctorlist']);
script:
#section('scripts')
<script>
$(document).ready(function() {
src = "{{ route('doctorlist') }}";
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
});
});
</script>
controller:
public function doctorlist(Request $request)
{
$query = $request->get('term','');
$doctors=Doctors::where('doctors_name','LIKE','%'.$query.'%')->get();
$data=array();
foreach ($doctors as $doctor) {
$data[]=array('value'=>$doctor->doctors_name,'id'=>$doctor->serial_no);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}
it always goes to serial route. not going doctorlist

Categories