I'km trying the autocomplete by selecting data from DB and getting back the response as json but all I got is internal server error, could it be a problem of csrf token?
this is the script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
$('input:text').bind({
});
$("#auto").autocomplete({
minLength:2,
source: '{{ URL('getdata') }}'
});
});
</script>
and this in the controller:
public function getData(){
$term = Input::get('term');
$data = DB::table('items')->distinct()->select('item_name')->where('word', 'LIKE', $term.'%')->groupBy('word')->take(10)->get();
foreach ($data as $v) {
$return_array[] = array('value' => $v->word);
}
return Response::json($return_array);
}
Problem was in getData function, this one works.
public function getData(){
$term = Input::get('term');
$data = DB::table('items')->distinct()->select('item_name')->where('item_name', 'LIKE', $term.'%')->groupBy('item_name')->take(10)->get();
foreach ($data as $v) {
$return_array[] = array('value' => $v->item_name);
}
return Response::json($return_array);
}
inspector.js:44 GET http://127.0.0.1:8000/product/autocomplete?terms=d 500 (Internal Server Error) #
*This is my Controller,
public function autosearch(Request $request){
// dd($request->all());
$query = $request->get('term','');
$allproducts = Product::where('product_title','LIKE','%'.$query.'%')->get();
$data = array();
foreach($allproducts as $product)
{
$data[] = array('value'=>$product->product_title,'id'=>$product->id);
}
if(count($data))
{
return $data;
}
else{
return ['value'=>"No Result Found",'id'=>''];
}
}
This is my script tag:
<script>
$(document).ready(function(){
var path = "{{route('autosearch')}}"
$('#search_text').autocomplete({
source:function(request,response)
{
$.ajax({
url:path,
dataType:"JSON",
data:{
term:request.term
},
success:function(data)
{
response(data);
}
});
},
minLength:1,
});
});
</script>
This is my HTML Form:
<div class="col d-none d-xl-block">
<label class="sr-only" for="searchproduct">Search</label>
<div class="input-group">
<input id="search_text" type="search" name="search" class="form-control py-2 pl-5 font-size-15 border-right-0 height-40 border-width-2 rounded-left-pill border-primary typeahead" placeholder="Search for Products" aria-label="Search for Products" aria-describedby="searchProduct1" autocomplete="off" required>
<div class="input-group-append">
<button class="btn btn-primary height-40 py-2 px-3 rounded-right-pill" type="submit" id="searchProduct1">
<span class="ec ec-search font-size-24"></span>
</button>
</div>
</div>
</div>
Related
i am building a project with laravel where i am able to fetch the record from database into my modal but the problem is everytime do i update my modal then the options values in both the select also gets incremented with the same fetched result. How to avoid that. Here i am pasting two images before and after of edit and also what i have done till now. Please help me to complete it.
Before Image
After Image
My modal part
Edit
<div class="modal" id="editModal" tabindex="-1" role="dialog" aria-labelledby="insertModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title font-weight-bold" id="insertModalLabel">EditCustomer</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p><b>Please note:</b> Fields marked with <span class="control-label"></span> is mandatory</p>
<form action="{{ url('admin/update_product') }}" method="post" class="edit_database_operation">
#csrf
<input class="form-control" type="hidden" name="eid" id="eid">
{{-- <input class="form-control" type="hidden" name="brand_id" id="brand_id">
<input class="form-control" type="hidden" name="category_id" id="category_id"> --}}
<div class="form-row">
<div class="form-group col-md-6">
<label for="eproduct_category" class="control-label">Product Category</label>
<select id="eproduct_category" class="form-control" name="eproduct_category">
</select>
</div>
<div class="form-group col-md-6">
<label for="eproduct_brand" class="control-label">Product Brand</label>
<select id="eproduct_brand" class="form-control" name="eproduct_brand">
</select>
</div>
</div>
<button type="submit" class="btn btn-primary text-left">Submit</button>
</form>
</div>
</div>
</div>
</div>
The script part
$(document).on('click','.edit_product',function(e){
e.preventDefault();
var url = $(this).attr('data-href');
console.log(url);
$.ajax({
url:url,
method:"GET",
success:function(fb){
var resp = $.parseJSON(fb);
console.log(resp);
$('#eid').val(resp.id);
var brand_id = resp.brand_id;
brand_edit(brand_id);
var category_id = resp.category_id;
category_edit(category_id);
}
});
return false;
});
function brand_edit(brand_id){
url = '/admin/edit_product_brand/'+brand_id;
console.log(url);
$.ajax({
url:url,
method:"GET",
success:function(fb){
console.log(fb);
$('#eproduct_brand').append(fb);
}
});
return false;
}
function category_edit(category_id){
url = '/admin/edit_product_category/'+category_id;
console.log(url);
$.ajax({
url:url,
method:"GET",
success:function(fb){
console.log(fb);
$('#eproduct_category').append(fb);
}
});
return false;
}
$(document).on('submit','.edit_database_operation',function(e){
e.preventDefault();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url:url,
method:"POST",
data:data,
success:function(fb){
var resp = $.parseJSON(fb);
// console.log(resp);
if(resp.status=='true'){
toastr.success(resp.message,'Success');
$('#editModal').modal('hide');
$('.edit_database_operation')[0].reset();
$("#example1").load(" #example1 > *");
$("#example2").load(" #example2 > *");
// $('.edit_database_operation')[0].reset();
$("#eproduct_category").data("default-value",$("#eproduct_category").val());
}else if(resp.status=='false'){
$.each( resp.message, function( key , value ) {
toastr.error(value + '<br>','Error');
});
}else if(resp.status=='false-1'){
toastr.error(resp.message,'Error');
}
}
});
return false;
});
The Controller part
public function product_edit($id){
$edit = Product::where('id',$id)->first();
$arr = array('id'=>$edit->id,'category_id'=>$edit->category_id,'brand_id'=>$edit->brand_id);
echo json_encode($arr);
}
public function edit_product_brand($id){
$brande = Brand::where('status','active')->orderBy('id','DESC')->get();
$output = '';
// $output .= '';
foreach ($brande as $brand){
$brand_id = $brand->id;
$brand_name = $brand->brand_name;
$output .= '<option value="'.$brand_id.'" '.(($brand_id == $id) ? 'selected="selected"':"").'>'.$brand_name.'</option>';
}
// $output .='</select>';
return $output;
}
public function edit_product_category($id){
$category = Category::where('status','active')->orderBy('id','DESC')->get();
$output = '';
if(!$category->isEmpty()){
foreach ($category as $brand){
$category_id = $brand->id;
$category_name = $brand->category_name;
$output .= '<option value="'.$category_id.'" '.(($category_id == $id) ? 'selected="selected"':"").'>'.$category_name.'</option>';
}
}
return $output;
}
public function update_product(Request $request){
$update = Product::where('id',$request->eid)->first();
$validator = Validator::make($request->all(),
[
'eproduct_category'=>'required',
'eproduct_brand'=>'required',
],[
'eproduct_category.required'=>'Please enter product category',
'eproduct_brand.required'=>'Please enter product brand',
]);
if(!$validator->fails()){
$update->name = $request->eproduct_name;
$update->category_id = $request->eproduct_category;
$update->brand_id = $request->eproduct_brand;
if($update->update()){
$arr = array('status'=>'true','message'=>'Updated Successfully');
}else{
$arr = array('status'=>'false-1','message'=>'Not Updated');
}
}else{
$arr = array('status'=>'false','message'=>$validator->errors()->all());
}
echo json_encode($arr);
}
In your jquery code you have use .append() to append new options inside your select-box which just insert new elements to the end of each element in the set of matched elements.So that's the reason it was showing double values.
Instead use .html() to replace all element which are there inside your select-box. So you just need to change :
$('#eproduct_brand').append(fb);
To
$('#eproduct_brand').html(fb);
Same you do for eproduct_category as well.
This is controller College.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class College extends CI_Controller
{
public function __construct() {
parent::__construct();
$this->load->model('College_model');
}
public function index() {
$this->load->view('college_view');
}
function get_autocomplete() {
if (isset($_GET['term'])) {
$result = $this->college_model->search_college($_GET['term']);
if (count($result) > 0) {
foreach ($result as $row) {
$arr_result[] = array(
'name' => $college_name,
'description' => $row->college_description,
);
echo json_encode($arr_result);
}
}
}
}
}
?>
This is College_model.php
<?php
class College_model extends CI_Model
{
function get_all_college() {
$result = $this->db->get('college');
return $result;
}
function search_college($name) {
$this->db->like('college_name', $name, 'both');
$this->db->order_by('college_name', 'ASC');
$this->db->limit(10);
return $this->db->get('college')->result();
}
}
?>
This is view page college_view.php
<div class="tab-content py-3 px-3 px-sm-0 m-auto" id="nav-tabContent">
<div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
<form action="http://vufind.carli.illinois.edu/vf-aru/Search/Home" method="get" role="search" target="vufind" name="searchForm">
<div class="input-group lrcInputs">
<input value="1" name="start_over" type="hidden">
<label></label>
<input class="form-control" id="college" name="college" type="text" placeholder="Search for books, ebooks, & media">
<div class="input-group-btn">
<button class="btn btn-success lrcSearchButton" type="submit"><i class="fa fa-search" aria-hidden="true"></i></button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#college').autocomplete({
source: "<?php echo site_url('college/get_autocomplete'); ?>",
select: function (event, ui) {
$('[name="college"]').val(ui.item.name);
}
});
});
</script>
How to remove the error of 404 not found. if need more code or file i will help.
i m getting error in chrome console as GET http://localhost/apluscollege/college/get_autocomplete?term=as 404 (not found) jquery.min.js
i m making a search bar using autocomplete using jQuery ana ajax
I'm trying to retrieve errors when a user fills a form submitted using ajax. I'm following this tutorial. I'm not getting the result expected despite the logic I think should be right.
Here is my blade view code :
#extends('layouts.layout')
#section('title','Soumettre thématique')
#section('content')
<body>
<div class="container_fluid">
<div class="row">
<div class="alert alert-danger print-error-msg" style="display: none;">
#if($errors->any())
<ol style="color: red">
#foreach($errors->all() as $error)
<li>
{{$error}}
</li>
#endforeach
</ol>
#endif
</div>
</div>
</div>
<form method="POST" action=" {{route('themes.store')}} ">
#csrf
<!-- Intitulé du thème -->
<input type="text" name="intitule" id="intitule" placeholder="Intitulé du thème" required><br>
<!-- Catégorie -->
<select name="categorie" required>
<option value="">-- Catégorie --</option>
<option value="web">Développement web</option>
<option value="appMobile">Programmation application mobile</option>
<option value="secure">Sécurisation</option>
<option value="other">Autre</option>
</select> <br>
<!-- Filière désirée -->
<input type="checkbox" name="filiere[]" id="GL" value="GL" required>
<label for="GL">Génie Logiciel</label><br>
<input type="checkbox" name="filiere[]" id="SI" value="SI" required>
<label for="SI">Sécurité Informatique</label><br>
<input type="checkbox" name="filiere[]" id="IM" value="IM" required>
<label for="IM">Internet et Multimédia</label><br>
<input type="checkbox" name="filiere[]" id="SIRI" value="SIRI" required>
<label for="SIRI">Systèmes d'Information et Réseaux Informatiques</label><br>
<!-- Descriptif -->
<textarea name="description" id="description" placeholder="Description de la thématique" required>{{old('description')}} </textarea><br>
<input type="submit" name="submit" id="submit" value="Ajouter">
<span id="error-message" class="text-danger"></span>
<span id="success-message" class="text-success"></span>
</form>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(function (){
var itsChecked = null;
$('input[type=checkbox]').on('click', function(){
if($('input[type=checkbox]:checked').length > 0){ //S'il y a au moins 1 ([...].length > 0) ckecked
// alert('At least one is checked');
$('#GL').removeAttr("required");
$('#SI').removeAttr("required");
$('#IM').removeAttr("required");
$('#SIRI').removeAttr("required");
}
else if(!$('input[type=checkbox]:checked').length > 0){ //S'il n'y a aucun checked (!(at least 1)>0)
// alert('None is checked');
$('#GL').attr('required','');
$('#SI').attr('required','');
$('#IM').attr('required','');
$('#SIRI').attr('required','');
}
});
$('#submit').on('click',function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var intitule = $("input[name='intitule']").val();
var categorie = $("select[name='categorie']").val();
var filiereChecked = [];
$.each($("input[type='checkbox']:checked"), function(){
filiereChecked.push($(this).val());
});
var filiere = filiereChecked.join(", ");
var filiere = filiere.toString();
$.ajax({
url: "{{route('themes.store')}}",
type: 'POST',
data: {
_token:_token,
intitule:intitule,
categorie:categorie,
filiere:filiere
},
success: function(data){
if($.isEmptyObject(data.error)){
alert(data.success);
}
else{
// console.log(data.error);
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg (msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','block');
$.each( msg, function( key, value ) {
$(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
</script>
</body>
#endsection
The controller store function :
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(),[
'intitule' => 'unique:themes,intitule'
]);
$theme = new Theme;
$theme->intitule = $request->input('intitule');
$theme->description = $request->input('description');
$theme->categorie = $request->input('categorie');
$request->merge([
'filiere' => implode(',', (array) $request->get('filiere'))
]);
$theme->filiereDesiree = $request->input('filiere');
$theme->save();
if ($validator->passes()) {
return response()->json(['success'=>'Added new records.']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
The problem is I'm not getting a message at all, either success or error may it be. I don't know where I'm doing wrong there.
P.S:
I've already used Ajax to submit this form. I did it using XMLHttpRequest object. The problem was I do not know how to use the 422 status to return errors using this XHR object. I've looked for it but found nothing really helpful.. So I changed this method to use here the ajax() jquery function which seems to be more used. Still not getting the messages.. It's the first time I try to manage the validation errors using Ajax. Your help would be very welcome
You can use this on your controller.
return response()->json(array('errors'=>$validator->getMessageBag()->toArray(),));
and in javascript try to use this one
success: function(data){
if(data.error){
printErrorMsg(data.error);
}
else{
alert(data.success);
}
}
ajax code
$.ajax({
url: "{{route('themes.store')}}",
type: 'POST',
data: {
_token:_token,
intitule:intitule,
categorie:categorie,
filiere:filiere
},
success: function(data){
if(data.error){
printErrorMsg(data.error);
}
else{
alert(data.success);
}
}
});
Controller
public function store(Request $request)
{
$validator = \Validator::make($request->all(),[
'intitule' => 'unique:themes,intitule'
]);
if ($validator->fails()) {
return response()->json(array('error'=>$validator->getMessageBag()->toArray(),));
}
$theme = new Theme;
$theme->intitule = $request->input('intitule');
$theme->description = $request->input('description');
$theme->categorie = $request->input('categorie');
$request->merge([
'filiere' => implode(',', (array) $request->get('filiere'))
]);
$theme->filiereDesiree = $request->input('filiere');
$theme->save();
return response()->json(array('success'=>'Added new records.',));
}
Oops this is my fault... I've just figured why it was not working. I've placed this in my blade view
#if($errors->any())
<ol style="color: red">
#foreach($errors->all() as $error)
<li>
{{$error}}
</li>
#endforeach
</ol>
#endif
instead of the <ul> </ul> tags that the javascript code is looking for to output the errors. Thank you all
You can use Laravel Request for your validation.
php artisan make:request ThemeCreateRequest
Controller
use App\Http\Request\ThemeCreateRequest
public function store(ThemeCreateRequest $request)
{
$theme = new Theme;
$theme->intitule = $request->input('intitule');
$theme->description = $request->input('description');
$theme->categorie = $request->input('categorie');
$request->merge([
'filiere' => implode(',', (array) $request->get('filiere'))
]);
$theme->filiereDesiree = $request->input('filiere');
$theme->save();
if ($validator->passes()) {
return response()->json(['success'=>'Added new records.']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
App\Http\Request\ThemeCreateRequest.php
public function authorize()
{
return true;
}
public function rules()
{
return [
'intitule' => 'required|unique',
];
}
I am developing an application where i display/edit/delete data from Mysql table using laravel and datatables. I get this error when trying to add or edit data and update it in Mysql table:
Here is code:
<!DOCTYPE html>
<html>
<head>
<title>Datatables Server Side Processing in Laravel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h3 align="center">Datatables Server Side Processing in Laravel</h3>
<br />
<div align="right">
<button type="button" name="add" id="add_data" class="btn btn-success btn-sm">Add</button>
</div>
<br />
<table id="student_table" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Action</th>
<th><button type="button" name="bulk_delete" id="bulk_delete" class="btn btn-danger btn-xs"><i class="glyphicon glyphicon-remove"></i></button></th>
</tr>
</thead>
</table>
</div>
<div id="studentModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" id="student_form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Data</h4>
</div>
<div class="modal-body">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<span id="form_output"></span>
<div class="form-group">
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
</div>
<div class="form-group">
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="student_id" id="student_id" value="" />
<input type="hidden" name="button_action" id="button_action" value="insert" />
<input type="submit" name="submit" id="action" value="Add" class="btn btn-info" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#student_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('ajaxdata.getdata') }}",
"columns":[
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "action", orderable:false, searchable: false},
{ "data":"checkbox", orderable:false, searchable:false}
]
});
$('#add_data').click(function(){
$('#studentModal').modal('show');
$('#student_form')[0].reset();
$('#form_output').html('');
$('#button_action').val('insert');
$('#action').val('Add');
$('.modal-title').text('Add Data');
});
$('#student_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"{{ route('ajaxdata.postdata') }}",
method:"POST",
data:form_data,
dataType:"json",
success:function(data)
{
if(data.error.length > 0)
{
var error_html = '';
for(var count = 0; count < data.error.length; count++)
{
error_html += '<div class="alert alert-danger">'+data.error[count]+'</div>';
}
$('#form_output').html(error_html);
}
else
{
$('#form_output').html(data.success);
$('#student_form')[0].reset();
$('#action').val('Add');
$('.modal-title').text('Add Data');
$('#button_action').val('insert');
$('#student_table').DataTable().ajax.reload();
}
}
})
});
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
$('#form_output').html('');
$.ajax({
url:"{{route('ajaxdata.fetchdata')}}",
method:'get',
data:{id:id},
dataType:'json',
success:function(data)
{
$('#first_name').val(data.first_name);
$('#last_name').val(data.last_name);
$('#student_id').val(id);
$('#studentModal').modal('show');
$('#action').val('Edit');
$('.modal-title').text('Edit Data');
$('#button_action').val('update');
}
})
});
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
if(confirm("Are you sure you want to Delete this data?"))
{
$.ajax({
url:"{{route('ajaxdata.removedata')}}",
mehtod:"get",
data:{id:id},
success:function(data)
{
alert(data);
$('#student_table').DataTable().ajax.reload();
}
})
}
else
{
return false;
}
});
$(document).on('click', '#bulk_delete', function(){
var id = [];
if(confirm("Are you sure you want to Delete this data?"))
{
$('.student_checkbox:checked').each(function(){
id.push($(this).val());
});
if(id.length > 0)
{
$.ajax({
url:"{{ route('ajaxdata.massremove')}}",
method:"get",
data:{id:id},
success:function(data)
{
alert(data);
$('#student_table').DataTable().ajax.reload();
}
});
}
else
{
alert("Please select atleast one checkbox");
}
}
});
});
</script>
</body>
</html>
Controller:
<?php
namespace App\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use App\Student;
use Yajra\DataTables\DataTables;
class AjaxdataController extends Controller
{
function index()
{
return view('student.ajaxdata');
//http://127.0.0:8000/ajaxdata
}
function getdata()
{
$students = Student::select('id', 'first_name', 'last_name');
return DataTables::of($students)
->addColumn('action', function($student){
return '<i class="glyphicon glyphicon-edit"></i> Edit<i class="glyphicon glyphicon-remove"></i> Delete';
})
->addColumn('checkbox', '<input type="checkbox" name="student_checkbox[]" class="student_checkbox" value="{{$id}}" />')
->rawColumns(['checkbox','action'])
->make(true);
}
function postdata(Request $request)
{
$validation = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
]);
$error_array = array();
$success_output = '';
if ($validation->fails())
{
foreach($validation->messages()->getMessages() as $field_name => $messages)
{
$error_array[] = $messages;
}
}
else
{
if($request->get('button_action') == "insert")
{
$student = new Student([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name')
]);
$student->save();
$success_output = '<div class="alert alert-success">Data Inserted</div>';
}
if($request->get('button_action') == 'update')
{
$student = Student::find($request->get('student_id'));
$student->first_name = $request->get('first_name');
$student->last_name = $request->get('last_name');
$student->save();
$success_output = '<div class="alert alert-success">Data Updated</div>';
}
}
$output = array(
'error' => $error_array,
'success' => $success_output
);
echo json_encode($output);
}
function fetchdata(Request $request)
{
$id = $request->input('id');
$student = Student::find($id);
$output = array(
'first_name' => $student->first_name,
'last_name' => $student->last_name
);
echo json_encode($output);
}
function removedata(Request $request)
{
$student = Student::find($request->input('id'));
if($student->delete())
{
echo 'Data Deleted';
}
}
function massremove(Request $request)
{
$student_id_array = $request->input('id');
$student = Student::whereIn('id', $student_id_array);
if($student->delete())
{
echo 'Data Deleted';
}
}
}
web.php:
Route::get('ajaxdata', 'AjaxdataController#index')->name('ajaxdata');
Route::get('ajaxdata/getdata', 'AjaxdataController#getdata')->name('ajaxdata.getdata');
Route::post('ajaxdata/postdata', 'AjaxdataController#postdata')->name('ajaxdata.postdata');
Route::get('ajaxdata/fetchdata', 'AjaxdataController#fetchdata')->name('ajaxdata.fetchdata');
Route::get('ajaxdata/removedata', 'AjaxdataController#removedata')->name('ajaxdata.removedata');
Route::get('ajaxdata/massremove', 'AjaxdataController#massremove')->name('ajaxdata.massremove');
Only delete is working. Also i want to use select-checkbox attribute of datatable but it doesn't work, like this one link for the line color on selection but with multiple selections.
Thanks to #Alaksandar Jesus Gene i solved this issue by changing the post request by a get request for the postdata function inside web.php file and inside the view related script code. Now that it works my second concern still unresolved.
Can u try this
$(document).on('click', '.edit', function () {
data = {};
data.id = $(this).attr("id");
data.first_name = "User"; //$('#first_name').val();
data.last_name = "hello"; //$('#last_name').val();
data.student_id = $(this).attr("id");
data.action = 'Edit';
data.button_action = 'update';
$('#form_output').html('');
$.ajax({
url: "{{route('ajaxdata.fetchdata')}}",
method: 'post',
data: data,
dataType: 'json',
success: function (data) {
// $('#studentModal').modal('show');
// $('.modal-title').text('Edit Data');
console.log("data", data);
},
error: function(err){
console.log("err", err);
}
})
});
Route::post('ajaxdata/postdata', 'AjaxdataController#postdata')->name('ajaxdata.postdata');
The router expects post request but you are sending GET request. Please change the method as shown
In laravel, I'm trying to update several tables and rows. i have items that are to be received and checked by 2 different users.
in my show.blade.php, i have this verify button and submit button depending on the user.
#if (($current_user_id != $saved_receiver_id) && ($saved_receiver_id != $not_yet_received))
<div class="row padder m-b">
<div class="col-md-12">
<label for="received_by" class="pull-left" >Received by:</label> <span class="fa"></span>
<input type="hidden" name="receiver_id" value="{{ $saved_receiver_id }}" >{{ $receiver_username }}</input>
</div>
</div>
<div class="row padder m-b">
<div class="col-md-12">
<label for="received_date" class="pull-left" >Received date:</label> <span class="fa"></span>
<input type="hidden" name="received_date" value="{{ $received_date }}" >{{ $received_date }}</input>
</div>
</div>
<input type="hidden" name="purchase_orders_id" value="{{ $purchase_order_number }}">
<input type="hidden" name="checker_id" value="{{ $current_user_id }}">
<div class="row padder m-b">
<div class="col-md-12">
<label for="final_checker_remarks" class="pull-left" >Final Remarks</label>
<textarea class="form-control col-md-12" name="final_checker_remarks" value="{{ $final_checker_remarks }}" id="final_checker_remarks">{{ $final_checker_remarks }}</textarea>
</div>
</div>
<br />
<div class="row">
<div class="col-md-12">
<button type="button" class="pull-right btn btn-success btn-sm submit-btn" id="update-form-submit" data-action="verified">Verified</button>
</div>
</div>
#else
<div class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-info btn-sm submit-btn" id="update-form-submit" data-action="submit">Submit List</button>
</a>
</div>
#endif
now in my ReceivesController.php, i have this postUpdate function,
public function postUpdate(Request $request)
{
if (! $request->ajax()) {
abort(404);
}
$items = json_decode($request->items);
$action = json_decode($request->action);
if(!count($items) && !count($items->purchase_item_id)){
return false;
}
$cnt = count($items->purchase_item_id);
// Receiver Submit function
if ($action == "submit") {
// Saves the received id of the one who received to purchase order table
DB::table('purchase_orders')
->where('id', $items->purchase_orders_id)
->update([
'receiver_id' => $items->receiver_id,
]);
// Saves the quantity received and receiver remarks to purchase items table
for($i=0; $i<$cnt; $i++){
DB::table('purchase_items')
->where('id', $items->purchase_item_id[$i])
->update([
'quantity_received' => $items->quantity_received[$i],
'receiver_remarks' => $items->receiver_remarks[$i],
]);
}
// Items Received Success Message
$message = 'Items Received';
}
// QA or Checker Finalize function
else {
// Saves the checker id, and final checker remarks of the one who made the QA to purchase order table
DB::table('purchase_orders')
->where('id', $items->purchase_orders_id)
->update([
'checker_id' => $items->checker_id,
'final_checker_remarks' => $items->final_checker_remarks,
]);
// Saves the quality received and checker remarks to purchase items table
for($i=0; $i<$cnt; $i++){
$quality_received = $items->quality_received;
if(is_array($items->quality_received)){
$quality_received = $items->quality_received[$i];
}
$checker_remarks = $items->checker_remarks;
if(is_array($items->checker_remarks)){
$checker_remarks = $items->checker_remarks[$i];
}
$quantity_received = $items->quantity_received;
if(is_array($items->quantity_received)){
$quantity_received = $items->quantity_received[$i];
}
$receiver_remarks = $items->receiver_remarks;
if(is_array($items->receiver_remarks)){
$receiver_remarks = $items->receiver_remarks[$i];
}
DB::table('purchase_items')
->where('id', $items->purchase_item_id[$i])
->update([
'quality_received' => $quality_received,
'checker_remarks' => $checker_remarks,
'quantity_received' => $quantity_received,
'receiver_remarks' => $receiver_remarks,
]);
// Increments or Adds the quantity received to items table
DB::table('items')
->where('purchase_items.id', $items->purchase_item_id[$i])
->join('purchase_items', 'items.id', '=', 'purchase_items.item_id')
->increment('items.measurement', $items->quantity_received[$i]);
}
/ / Items Finalized Success Message
$message = 'Items Verified';
}
// Returns Success Message
return response()->json([
'success' => true,
'message' => $message
]);
}
Now my problem is only the first letter of the word that is typed in the input area are being saved, and in others they are not saved, however, in other, it can be saved. I know its weird, but i cant find which part of my codes is doing such result, what is it that i need to do for me to update my tables correctly? Thanks in advance for the help.
Update: Here is my receive-form-function.js
/* ========================================================================
* Initialize Pages
* ======================================================================== */
$(initialPages);
/* ========================================================================
* Major function
* ======================================================================== */
/* ==== function to init this page === */
function initialPages($) {
// if($('#receives-list-table').length){
// DataTables("#receives-list-table", "receives");
// }
if($('#receiveItems-list-table').length){
$("#receiveItems-list-table").DataTable({
responsive: true,
ordering: false,
});
}
$('#update-form-submit').on('click', function(){
var action = $(this).data('action');
updateReceiveItem(action);
});
clearInputs();
}
/* === dataTables === */
function DataTables(selector, controller) {
$(selector).DataTable({
responsive: true,
processing: true,
serverSide: true,
ajax: url+'/'+controller+'/paginate'
});
}
function updateReceiveItem(action){
loadingModal('show','Updating ....');
ajaxCsrfToken();
var data = $('#receiveItems_id').serializeArray();
data = JSON.stringify(data);
// data = JSON.parse(data);
data = JSON.stringify($('#receiveItems_id').serializeObject());
// data = $('#receiveItems_id').serializeObject();
$.ajax({
url: url+'/receives/update',
type: 'post',
data: {'items':data, 'action': action},
dataType: 'json',
complete: function() {
loadingModal('close');
},
error: function(result) {
},
success: function(result) {
successAlert('#receiveItems-result', result.message);
// if (result.success) {
// $('input, select, textarea').attr('disabled', true);
// } else {
// alert(result.message);
// }
}
});
console.log(data);
return false;
}
/**
* Use to format serialize data and convert to json data
*
* Usage: JSON.stringify($('form').serializeObject())
*/
$.fn.serializeObject = function() {
var o = Object.create(null),
elementMapper = function(element) {
element.name = $.camelCase(element.name);
return element;
},
appendToResult = function(i, element) {
var node = o[element.name];
if ('undefined' != typeof node && node !== null) {
o[element.name] = node.push ? node.push(element.value) : [node, element.value];
} else {
o[element.name] = element.value;
}
};
$.each($.map(this.serializeArray(), elementMapper), appendToResult);
console.log(o);
return o;
};
my $.fn.serializeObject = function() above seems to have the bug, i tried using another $.fn.serializeObject = function(), and it gave me the json object that i want. here is the $.fn.serializeObject = function() that i am using now.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};