I'm trying to get data in form usin ajax
So I'm using the following code :
$(document).on('click', '.edit', function(){
var id = $(this).attr('id');
$('#form_result').html('');
$.ajax({
url:"castingss/"+id+"/edit",
dataType:"json",
success:function(html){
$('#casting_name').val(html.data.casting_name);
$('#casting_cin').val(html.data.casting_cin);
$('#casting_email').val(html.data.casting_email);
$('#casting_phone').val(html.data.casting_phone);
$('#casting_age').val(html.data.casting_age);
$('#casting_sexe').val(html.data.casting_sexe);
$('#casting_city').val(html.data.casting_city);
$('#casting_address').val(html.data.casting_address);
$('#store_image').html("<img src={{ URL::to('/') }}/images/" + html.data.casting_photo + " width='70' class='img-thumbnail' />");
$('#store_image').append("<input type='hidden' name='hidden_image' value='"+html.data.casting_photo+"' />");
$('#hidden_id').val(html.data.id);
$('.modal-title').text("Edit New Record");
$('#action_button').val("Edit");
$('#action').val("Edit");
$('#formModal').modal('show');
}
})
});
When I execute I get this exception :
"message": "",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
I understood that the url is undefind , how can I sove this problem ?
EDIT
I was following this tutorial enter link description here
they don't define a route for this URL
EDIT2
Route::get('/', function () {
return view('auth.login');
});
//auth route for both
Route::group(['middleware' => ['auth']], function() {
Route::get('/dashboard', 'App\Http\Controllers\DashboardController#index')->name('dashboard');
});
// for Manager de filial
Route::group(['middleware' => ['auth', 'role:manager_de_filiale']], function() {
Route::get('/dashboard/myprofile', 'App\Http\Controllers\DashboardController#myprofile')->name('dashboard.myprofile');
});
// for AccountManager
Route::group(['middleware' => ['auth', 'role:account_manager']], function() {
Route::get('/dashboard/postcreate', 'App\Http\Controllers\DashboardController#postcreate')->name('dashboard.postcreate');
});
Route::group(['middleware' => ['auth']], function() {
Route::get('/castings', 'App\Http\Controllers\DashboardController#casting')->name('dashboard');
});
//for adding a new casting
Route::group(['middleware' => ['auth']], function() {
Route::post('castingss', 'App\Http\Controllers\CastingController#store');
});
Route::get('castingss', 'App\Http\Controllers\CastingController#getdata');
Route::get('castingss', [App\Http\Controllers\CastingController::class, 'getdata'])->name('castingss.getdata');
My Controller:
function getdata(Request $request)
{
if(request()->ajax())
{
return datatables()->of(Casting::latest()->get())
->addColumn('action', function($data){
$button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Edit</button>';
$button .= ' ';
$button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
return $button;
})
->rawColumns(['action'])
->make(true);
}
return view('Casting.castingss');
}
public function edit($id)
{
if(request()->ajax())
{
$data = Casting::findOrFail($id);
return response()->json(['data' => $data]);
}
}
Any Idea ?
I SOLVE IT BY adding that to my web page :
Route::get('castingss/{id}/edit', [App\Http\Controllers\CastingController::class, 'edit']);
Related
BLADE FILE
<td><button class="deleteuser" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >DELETE</button>
</td>
AJAX
$(document).ready( function () {
$(".deleteuser").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
});
CONTROLLER
public function destroyuser($id){
$this->authorize('Admin');
User::find($id)->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
return view('viewuser');
}
If I click on delete button, there is no response. Any suggestion or correction will be appreciated. Thanks in advance
I don't know if the JS is in a different file but to check if the "$( document ).ready()" is working add a console.log() call at the beginning.
$(document).ready( function () {console.log("document is ready")
$(".deleteuser").click(function(){
Refresh the page and check if "document is ready" is logged to the console.
If it isn't then the javascript is not loading
Check if the route is properly defined
You can replace your url as this and check:
var id = data.id;
var url = "{{route('your_route',":id") }}";
url = url.replace(':id', id);
pass url in your ajax url param
Or make above changes:
BLADE FILE
<td>
<button style="background-color: red;" onclick="clickOffConfirmed" title="Delete" class="btn btn-sm btn-clean btn-icon btn-icon-md delete"><i class="la la-trash" style="color: white;"></i></button>
</td>
SCRIPT
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function ()
{
var obj = $(this);
var id=$(this).closest('td').find(".delete_id").val();
var result = confirm("Are you sure want to delete?");
if(result)
{
$.ajax(
{
type: "POST",
url: "{{route('delete_method')}}",
data: {
'_token': $('input[name="_token"]').val(),
'id': id
},
cache: false,
success: function (data)
{
if (data.status === 'success')
{
window.location = "{{route('redirect_route')}}";
toastr["success"]("Deleted Successfully", "Success");
}
else if (data.status === 'error')
{
location.reload();
toastr["error"]("Something went wrong", "Opps");
}
}
});
}
});
});
</script>
Controller
public function delete_method(Request $request)
{
$del = ModelName::findOrFail($request->id)->delete();
if($del)
{
return response()->json(['status' => 'success']);
}
else{
return response()->json(['status' => 'error']);
}
}
Route
Route::post('/test/delete','TestController#delete_method')->name('delete_method');
In your ajax codes, change this:
url: "user/delete/"+id,
To:
url: "{{ url('user/delete') }}/" + id
If your ajax codes are inside of your blade file also you can use this way:
url: "{{ route('YOUR_ROUTE_NAME', $user->id) }}/"
You incorrectly define delete function!
change
User::find($id)->delete($id);
To
User::find($id)->delete();
I want to retrieve data from DB to my user Dashboard. User Identify using Contact No.
I run AJAX query to retrieve all adds. its running well.
but I need to retrieve data under his user ID (ContactNo). here I add AJAX code.
user data avaiable in AUTH -> {{ Auth::user()->ContactNo }}
$(document).ready(function($){
//alert("jquery running");
getAll();
});
//getting all rows from the database
function getAll() {
$.ajax({
url: '{{ route('Myadds', app()->getLocale()) }}',
type: 'GET',
})
.done(function(data) {
alert("run")
$.each(data, function(index, val) {
$('#data').append('<tr>')
$('#data').append('<td>'+val.id+'</td>')
$('#data').append('<td>'+val.Sdescription+'</td>')
$('#data').append('<td>'+val.created_at+'</td>')
$('#data').append('<td><button class="btn btn-xs btn-danger" data-id="'+val.id+'">Delete</button><button class="btn btn-xs btn-info" data-id="'+val.id+'">Edit</button></td>')
$('#data').append('</tr>')
});
})
.fail(function() {
alert("fail")
console.log("error");
})
}
</script>
You need to pass de contactNo parameter in your query:
function getAll() {
$.ajax({
url: '{{ route('Myadds', app()->getLocale()) }}',
type: 'GET',
data: {
contact_no: contactNo,
},
})
.done(function(data) {
alert("run")
$.each(data, function(index, val) {
$('#data').append('<tr>')
$('#data').append('<td>'+val.id+'</td>')
$('#data').append('<td>'+val.Sdescription+'</td>')
$('#data').append('<td>'+val.created_at+'</td>')
$('#data').append('<td><button class="btn btn-xs btn-danger" data-id="'+val.id+'">Delete</button><button class="btn btn-xs btn-info" data-id="'+val.id+'">Edit</button></td>')
$('#data').append('</tr>')
});
})
.fail(function() {
alert("fail")
console.log("error");
})
}
So in your controller now you can filter:
public function getData(Request $request){
$contact_no = $request->contact_no;
$query = DB::table('my_table');
if($contact_no){
$query->where('contact_no',$contact_no)
}
return response()->json($query->get());
}
Or directly use the session of the user:
public function getData(Request $request){
$contact_no = Auth::user()->ContactNo;
$query = DB::table('my_table');
$query->where('contact_no',$contact_no)
return response()->json($query->get());
}
public function Myadds(){
try{
return add::where('userID', Auth::user()->ContactNo)->get();
}catch(Exception $e){
return 'false';
}
}
i trying to create a crud system using vue js and laravel.
i already create api route and more...
but when i click submit i got message 405 (Method Not Allowed)
here my AddArtist.vue file
<form #submit.prevent="add">
<input type="text" class="form-control" v-model="artist.name" placeholder="Artist Name">
<button class="btn btn-success" type="submit">Save</button>
</form>
<script>
export default {
data: function () {
return {
errors: [],
image: '',
artist: {
name: '',
}
}
},
methods: {
add() {
axios.post('/api/artist/store-artist', this.$data.artist)
.then((response) => {
alert('Success add Artist')
console.log(response)
})
},
},
mounted() {
console.log('Add Artist Mounted.')
}
}
</script>
and my api.php route
Route::group(['middleware' => 'cors'], function(){
Route::post('addartist/store-artist', 'ArtistController#store');
});
and here my controller ArtistController.php
public function store(Request $request)
{
$input = $request->all();
dd($input);
}
and the last is my model Artist.php
class Artist extends Model
{
protected $table = 'artist';
protected $fillable = ['artist_name', 'date_birth', 'cover', 'gender'];
}
that is typo error:
change addartist/store-artist to artist/store-artist in route
Your api is :
Route::group(['middleware' => 'cors'], function(){
Route::post('addartist/store-artist', 'ArtistController#store');
});
and you are doing :
axios.post('/api/artist/store-artist', this.$data.artist)
.then((response) => {
alert('Success add Artist')
console.log(response)
})
I need to add a Laravel Dynamic Dependent Dropdown. Im confused..
In my database, i have both categories and their childrens.
Account_id =0 => Categorie
Account_id =1 => Sub Categorie of category or subcategory with id =1
Account_id =2 => Sub categorie of category or subcategory with id =2
This is my actual code :
Method:
public function index()
{
$categories = Account::where('account_id', '=', 0)->get();
$allCategories = Account::where('account_id', '=', 0)-
>pluck('account_name','id');
return view('Account.list',compact('categories', 'allCategories')); //
set the path of you templates file.
}
public function children(Request $request)
{
return Account::where('account_id', $request->account_id)->pluck('account_name', 'id');
}
View:
<div class="form-group">
{!! Form::label('account_id', 'Parent Category:')!!}
{!! Form::select('account_id', $allCategories, ['placeholder' =>
'Choose Category'])!!}
</div>
<div class="form-group">
{!! Form::label('children', 'Child category:')!!}
{!! Form::select('children', [], null, ['placeholder' => 'Choose child
category'])!!}
</div>
Route:
Route::get('/categories', [
'uses' => 'AccountController#index',
'as' => 'categories'
]);
Route::get('/categories/children', [
'uses' => 'AccountController#children',
'as' => 'categories.children'
]);
JS:
<script>
$('#account_id').change(function(e) {
var parent = e.target.value;
$.get('/categories/children?account_id=' + account_id, function(data) {
$('#children').empty();
$.each(data, function(key, value) {
var option = $("<option></option>")
.attr("value", key)
.text(value);
$('#children').append(option);
});
});
});
</script>
try this first create new route
Route::post('subchildren/youcontroller', [
'as' => 'children.categories',
'uses' => 'youUrlController\yourController#childrenCategory',
]);
next create route go to controller create new method
public function childrenCategory(Request $request)
{
try {
$subCategory= subCategory::where('category_id', $request->nameSelectCategoryinYourView)->get();
return response()->json(['subCategory' => $subCategory], 200);
} catch (Exception $e) {
return response()->json(['error' => 'Error'], 403);
}
}
next in your view
<div class="form-group m-b-40">
<select name="subCategory" class="form-control p-0" id='subCategory'></select>
</div>
next in your javascript
jQuery(document).ready(function($) {
$('#FirstSelect').change(function () {
$('#subCategory').empty();
var Category = $(this).val();
datos = {
tipo : Category
},
$.ajax({
url: '{{ route('children.categories') }}',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: datos,
success: function (argument) {
arreglo = {id:"a", tipo:""};
argument.detalles.unshift(arreglo);
$.each(argument.subCategory, function(index, el) {
var opcion = '<option value="'+ el.id +'">'+ el.subCategoryName+'</option>';
$('#subCategory').append( opcion );
});
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
})
});
});
So I've been learning Laravel and was getting into making DataTables. However, my 'editItem' route is not being able to get any information when I click 'Edit' button. It shows Error 405.
DataTable view (dt.blade.php) -
HTML part where the table is displayed
<div class="table-responsive text-center">
<table class="table table-borderless" id="table">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Name</th>
<th class="text-center">Created At</th>
<th class="text-center">Updated At</th>
<th class="text-center">Actions</th>
</tr>
</thead>
#foreach($users as $user)
<tr class="user{{$user->id}}">
<td >{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->created_at}}</td>
<td>{{$user->updated_at}}</td>
<td><button class="edit-modal btn btn-info"
value="{{$user->id}},{{$user->name}}">
<span class="glyphicon glyphicon-edit"></span> Edit
</button>
<button class="delete-modal btn btn-danger"
value="{{$user->id}},{{$user->name}}">
<span class="glyphicon glyphicon-trash"></span> Delete
</button></td>
</tr>
#endforeach
</table>
</div>
JS part in the same file
<script>
$(document).ready(function() {
$('#table').DataTable();
} );
</script>
<script>
$(document).on('click', '.edit-modal', function() {
$('#footer_action_button').text("Update");
$('#footer_action_button').addClass('glyphicon-check');
$('#footer_action_button').removeClass('glyphicon-trash');
$('.actionBtn').addClass('btn-success');
$('.actionBtn').removeClass('btn-danger');
$('.actionBtn').removeClass('delete');
$('.actionBtn').addClass('edit');
$('.modal-title').text('Edit');
$('.deleteContent').hide();
$('.form-horizontal').show();
var stuff = $(this).val().split(',');
console.log($(this).val());
fillmodaluser(stuff)
$('#myModal').modal('show');
});
$(document).on('click', '.delete-modal', function() {
$('#footer_action_button').text(" Delete");
$('#footer_action_button').removeClass('glyphicon-check');
$('#footer_action_button').addClass('glyphicon-trash');
$('.actionBtn').removeClass('btn-success');
$('.actionBtn').addClass('btn-danger');
$('.actionBtn').removeClass('edit');
$('.actionBtn').addClass('delete');
$('.modal-title').text('Delete');
$('.deleteContent').show();
$('.form-horizontal').hide();
var stuff = $(this).val().split(',');
console.log($(this).val('info'));
$('.did').text(stuff[0]);
$('.dname').html(stuff[1]);
$('#myModal').modal('show');
});
function fillmodaluser(details){
$('#fid').val(details[0]);
$('#name').val(details[1]);
}
$('.modal-footer').on('click', '.edit', function() {
$.ajax({
type: 'post',
url: '../public/editUser',
user: {
'_token': $('input[name=_token]').val(),
'id': $('#fid').val(),
'name': $('#name').val()
},
success: function(user) {
if (user.errors){
$('#myModal').modal('show');
if(user.errors.name) {
$('.name_error').removeClass('hidden');
$('.name_error').text("Name can't be empty !");
}
if(user.errors.email) {
$('.email_error').removeClass('hidden');
$('.email_error').text("Email must be a valid one !");
}
}
else {
$('.error').addClass('hidden');
$('.user' + users.id).replaceWith("<tr class='users" + users.id + "'><td>" +users.id + "</td><td>" + users.name+"</td><td>" + "</td><td>" + "</td><td><button class='edit-modal btn btn-info' user-info='" + users.id+","+users.name+"'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' user-info='" + users.id+","+users.name+"' ><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
}}
});
});
$('.modal-footer').on('click', '.delete', function() {
$.ajax({
type: 'post',
url: '../public/deleteUser',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
user: {
'_token': $('input[name=_token]').val(),
'id': $('.did').text()
},
success: function(user) {
$('.user' + $('.did').text()).remove();
}
});
});
</script>
And lastly, the web.php
Route::get('/dt', 'UserController#dt');
Route::get('/editUser', function (Request $request) {
$rules = array (
'name' => 'required|alpha',
);
$validator = Validator::make(Input::all(), $rules );
if ($validator->fails ())
return Response::json ( array (
'errors' => $validator->getMessageBag()->toArray ()
) );
else {
$user->id = User::find ( $request->id );
$user->name = ($request->name);
$user->save ();
return response ()->json ( $user );
}
});
Route::get ('/deleteUser', function (Request $request) {
User::find ( $request->id )->delete ();
return response ()->json ();
});
The JSON error that shows to me is "{"errors":{"name":["The name field is required."]}}"
My question is that, the info can be split fine in the JQuery here when I press the Edit button; it is able to show the info of the row I've selected. I don't understand why the same values aren't getting sent to my editUser route?
change all get method to post , because you are using post in client side
Route::post('/dt', 'UserController#dt');
Route::post('/editUser', function (Request $request) {
$rules = array (
'name' => 'required|alpha',
);
$validator = Validator::make(Input::all(), $rules );
if ($validator->fails ())
return Response::json ( array (
'errors' => $validator->getMessageBag()->toArray ()
) );
else {
$user->id = User::find ( $request->id );
$user->name = ($request->name);
$user->save ();
return response ()->json ( $user );
}
});
Route::post ('/deleteUser', function (Request $request) {
User::find ( $request->id )->delete ();
return response ()->json ();
});
Seems your urls should not be '../public/' (in your ajax requests) but it should match what you typed in your file web.php