I make CRUD operation by using laravel, ajax and the blade form is (modal), the (create method) works fine, but the (update method) doesn't work, in spite of its functionality is the same of (update method) I Think the issue is:
- the form kyes (name atrribute) doesn't send to the controller, In spite of the keys contain values and their names are the same in controller request.
- when press Edit button the modal and inputs values appear like that:
- when press save changes, it says that there are no requests come from ajax:
Routes:
Route::get('/register',[RegisterController::class,'index']);
Route::post('/register-create',[RegisterController::class,'store'])->name('register.create');
Route::get('/register-edit/{id}',[RegisterController::class,'edit'])->name('register.edit');
Route::post('/register-update/{id}',[RegisterController::class,'update'])->name('register.update');
Blade page the issue begging of ( "Modal for edit" comment") :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax CRUD Modal</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA 058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
{{--jquery and ajax--}}
<script src="https://code.jquery.com/jquery-3.1.1.min.js">
{{--jquery and ajax--}}
{{--Bootstrab --}}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5 76PVCmYl" crossorigin="anonymous"></script>
{{--Bootstrab --}}
{{--validate jquery --}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
{{-- validate jquery --}}
</head>
<body>
<div >
<div id="msg-succ" style="display: none" >
<button type="text"
id="type-error">Registered Successfully</button>
</div>
<div style="margin-bottom: 60px"></div>
<table id="userTable" >
<button data-toggle="modal" data-target="#addUser">Add New User</button>
<thead>
<tr>
<th scope="col">First Name</th>
<th scope="col">Middle Name</th>
<th scope="col">Last Name</th>
<th scope="col">Email</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
@if(isset($users) && $users->count()>0)
@foreach($users as $user)
<tr>
<td>{{$user-> firstName}}</td>
<td>{{$user-> middleName}}</td>
<td>{{$user-> lastName}}</td>
<td>{{$user-> email}}</td>
<td>
<div role="group"
aria-label="Basic example">
<button id="getUser" data-id="{{ $user->id }}" data-toggle="modal" data-target="#editUser">Edit User</button>
</div>
<div role="group"
aria-label="Basic example">
<a user_id = "{{$user -> id}}" href="">Delete</a>
</div>
</td>
</tr>
@endforeach
@endif
</tbody>
</table>
</div>
<!-- Modal for create -->
<div id="addUser" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div role="document">
<div >
<div >
<h5 id="exampleModalLongTitle">Add New User</h5>
<button type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div >
<form id="userForm">
@csrf
<div >
<label for="exampleInputEmail1">First Name</label>
<input type="text" onblur="" name="firstName" id="firstName" placeholder="Enter First Name">
<small id="firstName_error" ></small>
</div>
<div >
<label for="exampleInputEmail1">Middle Name</label>
<input type="text" name="middleName" id="middleName" placeholder="Enter Middle Name">
<small id="middleName_error" ></small>
</div>
<div >
<label for="exampleInputEmail1">Last Name</label>
<input type="text" name="lastName" id="lastName" placeholder="Enter Last Name">
<small id="lastName_error" ></small>
</div>
<div >
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="email" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" >We'll never share your email with anyone else.</small>
<small id="email_error" ></small>
</div>
<div >
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" id="exampleInputPassword1" placeholder="Password">
<small id="password_error" ></small>
</div>
<div >
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password_confirmation" id="exampleInputPassword1" placeholder="Confirm Your Password">
<small id="password_confirmation_error" ></small>
</div>
</form>
</div>
<div >
<button type="button" data-dismiss="modal">Close</button>
<button type="button" id="save_user" >Save changes</button>
</div>
</div>
</div>
</div>
<!-- Modal for edit -->
<div id="editUser" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div role="document">
<div >
<div >
<h5 id="exampleModalLongTitle">Add New User</h5>
<button type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div >
<form id="editForm">
@csrf
<div >
<label for="firstNameEdit">First Name</label>
<input type="text" onblur="" name="firstNameUpdate" id="firstNameEdit" placeholder="Enter First Name">
<small id="firstName_edit_error" ></small>
</div>
<div >
<label for="middleNameEdit">Middle Name</label>
<input type="text" name="middleNameUpdate" id="middleNameEdit" placeholder="Enter Middle Name">
<small id="middleName_edit_error" ></small>
</div>
<div >
<label for="lastNameEdit">Last Name</label>
<input type="text" name="lastNameUpdate" id="lastNameEdit" placeholder="Enter Last Name">
<small id="lastName_edit_error" ></small>
</div>
<input type="hidden" id="userIdEdit" name="userIdEdit" value="">
<div >
<label for="emailEdit">Email address</label>
<input type="email" name="emailUpdate" id="emailEdit" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" >We'll never share your email with anyone else.</small>
<small id="email_edit_error" ></small>
</div>
<div >
<button type="button" data-dismiss="modal">Close</button>
<button type="button" id="update_user" >Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$(document).on('click', '#save_user', function(e){
e.preventDefault();
$('#firstName_error').text('');
$('#middleName_error').text('');
$('#lastName_error').text('');
$('#email_error').text('');
$('#password_error').text('');
$('#password_confirmation_error').text('');
var formData = new FormData($('#userForm')[0]);
console.log(formData)
$.ajax({
type: 'post',
enctype: 'multipart/form-data',
url: "{{route('register.create')}}",
data: formData,
processData: false,
contentType: false,
cache: false,
success: function (response){
if(response){
$("#userTable tbody").prepend('<tr><td>' response.firstName '</td><td>' response.middleName '</td><td>' response.lastName '</td><td>' response.email '</td></tr>')
$('#userForm')[0].reset();
$('#addUser').modal('hide');
$('#msg-succ').show();
}
}, error: function (reject){
var response = $.parseJSON(reject.responseText);
$.each(response.errors, function(key, val){
$("#" key "_error").text(val[0]);
});
}
});
});
$('body').on('click', '#getUser', function (event) {
event.preventDefault();
var user_id = $(this).data('id');
console.log(user_id)
$.get('register-edit/' user_id, function (data) {
$('#firstNameEdit').val(data.firstName);
$('#middleNameEdit').val(data.middleName);
$('#lastNameEdit').val(data.lastName);
$('#emailEdit').val(data.email);
$('#userIdEdit').val(user_id);
})
});
$(document).on('click', '#update_user', function(e){
e.preventDefault();
$('#firstName_edit_error').text('');
$('#middleName_edit_error').text('');
$('#lastName_edit_error').text('');
$('#email_edit_errorr').text('');
// var formData = new FormData($('#editForm')[0]);
var firstName = $("#firstNameEdit").val();
var middleName = $("#middleNameEdit").val();
var lastName = $("#lasttNameEdit").val();
var email= $("#emailEdit").val();
var user_id = $("#userIdEdit").val();
console.log(firstName)
console.log(middleName)
console.log(user_id)
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'post',
enctype: 'multipart/form-data',
url: "{{url('register-update')}}" '/' user_id,
data: {
firstNameUpdate:firstName,
middleNameUpdate:middleName,
lastNameUpdate:lastName,
emailUpdate:email,
},
processData: false,
contentType: false,
cache: false,
success: function (response){
if(response){
$("#userTable tbody").prepend('<tr><td>' response.firstName '</td><td>' response.middleName '</td><td>' response.lastName '</td><td>' response.email '</td></tr>')
$('#userForm')[0].reset();
$('#editUser').modal('hide');
$('#msg-succ').show();
}
}, error: function (reject){
var response = $.parseJSON(reject.responseText);
$.each(response.errors, function(key, val){
$("#" key "_edit_error").text(val[0]);
});
}
});
});
</script>
</body>
</html>
controller:
<?php
namespace App\Http\Controllers;
use App\Http\Requests\RegisterRequest;
use App\Http\Requests\RegisterRequestUpdate;
use App\Models\User;
use Illuminate\Support\Facades\Request;
class RegisterController extends Controller
{
public function index(){
$users = User::get();
return view('pages.register',compact('users'));
}
public function store(RegisterRequest $request){
$user = User::create([
'firstName' => $request->firstName,
'middleName' => $request->middleName,
'lastName' => $request->lastName,
'email' => $request->email,
'password' => $request->password,
]);
if($user)
return response()->json($user);
else
return response()->json([
'status' => false,
'msg' => 'SomeThing Error Try Again',
]);
}
public function edit($id){
$userData = User::find($id);
return response()->json($userData);
}
public function update(RegisterRequestUpdate $request, $id){
$user = User::find($id);
if (!$user)
return response()->json([
'status' => false,
'msg' => 'SomeThing Error Try Again',
]);
else
$user->update([
'firstName' => $request->firstNameUpdate,
'middleName' => $request->middleNameUpdate,
'lastName' => $request->lastNameUpdate,
'email' => $request->email,
]);
return response()->json($user);
}
}
Request:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterRequestUpdate extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'firstNameUpdate' => ['required', 'string', 'max:255'],
'middleNameUpdate' => ['required', 'string', 'max:255'],
'lastNameUpdate' => ['required', 'string', 'max:255'],
'emailUpdate' => ['required', 'string', 'email', 'max:255', 'unique:users'],
];
}
}
CodePudding user response:
Simply remove the processData: false from your ajax request and it should be working fine.
You can simply do an ajax request with the following code
$.ajax({
type: 'post',
url: "{{url('register-update')}}" '/' user_id,
data: {
firstNameUpdate:firstName,
middleNameUpdate:middleName,
lastNameUpdate:lastName,
emailUpdate:email,
},
success: function (response){
if(response){
$("#userTable tbody").prepend('<tr><td>' response.firstName '</td><td>' response.middleName '</td><td>' response.lastName '</td><td>' response.email '</td></tr>')
$('#userForm')[0].reset();
$('#editUser').modal('hide');
$('#msg-succ').show();
}
}, error: function (reject){
var response = $.parseJSON(reject.responseText);
$.each(response.errors, function(key, val){
$("#" key "_edit_error").text(val[0]);
});
}
});
You can read more about the processData property here.
CodePudding user response:
You forgot to add the token. You can edit your code like this
data: {
firstNameUpdate:firstName,
middleNameUpdate:middleName,
lastNameUpdate:lastName,
emailUpdate:email,
_token: {{ csrf_token }}
}, 

