I am trying to make a crud small application to learn ajax, but I am facing serious problems here.
Here are some snippets, when I click on submit, the form doesn't do anything, just show me error 500 in chrome's console.And if I try to show something in success ajax function the request it's showing "undefined".
Thank you so much!
Here is my controller
public function store(Request $request)
{
$response = array(
'msg' => 'Thank you nephew'
);
$request->validate([
'name' => 'required|min:3',
'mobile' => 'required',
'address' => 'nullable',
'email' => 'nullable'
]);
$values = $request->all();
echo $values;
return Response::json($response);
}
Here is my Ajax script
<script>
$('#create-form').on('submit', function (event) {
event.preventDefault();
let name = $("input[name=name]").val();
let mobile = $("input[name=mobile]").val();
let email = $("input[name=email]").val();
let address = $("input[name=address]").val();
console.log(name);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').val()
}
});
$.ajax({
type: 'POST',
url: '{{ route('addresses.store') }}',
data: {name: name, mobile: mobile, email: email, address: address, token: $('input[name="_token"]').val()},
success: function (data) {
console.log(data);
}
});
});
</script>
Here is the blade modal
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create address</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="result"></div>
<form action="{{ route('addresses.store') }}" method="post" id="create-form">
#csrf
<div class="form-group">
<label for="">Name</label>
<input type="text" class="sequence-input" name="name"/>
</div>
<div class="form-group">
<label for="#">Mobile</label>
<input type="text" class="sequence-input" name="mobile"/>
</div>
<div class="form-group">
<label for="#">Address</label>
<textarea name="address" class="sequence-input" cols="30" rows="6"></textarea>
</div>
<div class="form-group">
<label for="#">Email Address</label>
<input type="text" class="sequence-input" name="email"/>
</div>
<div class="form-group">
<button type="submit" id="create" class="sequence-btn sequence-btn--primary">Create</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="sequence-btn sequence-btn--danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Try using single quotes on the name's value let mobile = $("input[name='mobile']").val(); and so on
Or
$.ajax({
type: 'POST',
url: '{{ route('addresses.store') }}',
data: $(this).serialize(),
success: function (data) {
console.log(data);
}
});
Your 500 error is caused by attempting to echo the array $values:
$values = $request->all();
echo $values; // <-- Your error is here.
Try using the dd helper method instead: dd($values)
Related
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 class="container">
<div id="msg-succ" style="display: none" class="mt-5 row mr-2 ml-2">
<button type="text" class="btn btn-lg btn-block btn-outline-success mb-2"
id="type-error">Registered Successfully</button>
</div>
<div style="margin-bottom: 60px"></div>
<table id="userTable" class="table">
<button class="btn btn-success mr-2" 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 class="btn-group" role="group"
aria-label="Basic example">
<button id="getUser" data-id="{{ $user->id }}" class="btn btn-primary" data-toggle="modal" data-target="#editUser">Edit User</button>
</div>
<div class="btn-group" role="group"
aria-label="Basic example">
<a user_id = "{{$user -> id}}" class="delete btn btn-danger" href="">Delete</a>
</div>
</td>
</tr>
#endforeach
#endif
</tbody>
</table>
</div>
<!-- Modal for create -->
<div class="modal fade" id="addUser" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Add New User</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="userForm">
#csrf
<div class="form-group">
<label for="exampleInputEmail1">First Name</label>
<input type="text" onblur="" name="firstName" class="form-control" id="firstName" placeholder="Enter First Name">
<small id="firstName_error" class="form-text text-danger"></small>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Middle Name</label>
<input type="text" name="middleName" class="form-control" id="middleName" placeholder="Enter Middle Name">
<small id="middleName_error" class="form-text text-danger"></small>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Last Name</label>
<input type="text" name="lastName" class="form-control" id="lastName" placeholder="Enter Last Name">
<small id="lastName_error" class="form-text text-danger"></small>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
<small id="email_error" class="form-text text-danger"></small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
<small id="password_error" class="form-text text-danger"></small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password_confirmation" class="form-control" id="exampleInputPassword1" placeholder="Confirm Your Password">
<small id="password_confirmation_error" class="form-text text-danger"></small>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="save_user" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<!-- Modal for edit -->
<div class="modal fade" id="editUser" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Add New User</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="editForm">
#csrf
<div class="form-group">
<label for="firstNameEdit">First Name</label>
<input type="text" onblur="" name="firstNameUpdate" class="form-control" id="firstNameEdit" placeholder="Enter First Name">
<small id="firstName_edit_error" class="form-text text-danger"></small>
</div>
<div class="form-group">
<label for="middleNameEdit">Middle Name</label>
<input type="text" name="middleNameUpdate" class="form-control" id="middleNameEdit" placeholder="Enter Middle Name">
<small id="middleName_edit_error" class="form-text text-danger"></small>
</div>
<div class="form-group">
<label for="lastNameEdit">Last Name</label>
<input type="text" name="lastNameUpdate" class="form-control" id="lastNameEdit" placeholder="Enter Last Name">
<small id="lastName_edit_error" class="form-text text-danger"></small>
</div>
<input type="hidden" id="userIdEdit" name="userIdEdit" value="">
<div class="form-group">
<label for="emailEdit">Email address</label>
<input type="email" name="emailUpdate" class="form-control" id="emailEdit" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
<small id="email_edit_error" class="form-text text-danger"></small>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="update_user" class="btn btn-primary">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'],
];
}
}
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.
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 }}
},
I have problem regarding inserting my data in the database, so I have module where I need to insert the information of the song. So I just test the lower version of the laravel (5.0 Laravel Version) and Ajax for submitting the request to the backend. Now when I press the submit button it shows error of.
TokenMismatchException in VerifyCsrfToken.php line 46:
Error:
One thing is the token is sending to the backend
I will share to you guys my sample code that I already created. Please see the codes below.
Routes::
Route::post('/add_song','HomeController#add_song');
Front End::
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$(document).ready(function(){
$('.btn_add_music').on('click',function(e){
var song_title = $('#song_title').val();
var song_artist = $('#song_artist').val();
var song_lyrics = $('#song_lyrics').val();
var currentToken = $('meta[name="csrf-token"]').attr('content');
// var data = new FormData();
// data.append('song_title',song_title);
// data.append('song_artist',song_artist);
// data.append('song_lyrics',song_lyrics);
// data.append('currentToken',currentToken);
var formData = '_token=' + $('.token').val();
$.ajax({
url: '/add_song',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
success:function(res) {
console.log(res);
},
error:function(err) {
console.log(res);
}
// ... Other options like success and etc
})
});
});
Back End::
public function add_song(Request $request) {
dd($request->all());
$song_title = $request->get('song_title');
$song_artist = $request->get('song_artist');
$song_lyrics = $request->get('song_lyrics');
return response()->json('Success Inserted');
}
Html::
<div class="modal fade" id="ModalSong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Ready to Add New Song?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<input type="hidden" class="token" name="_token" value="<?php echo csrf_token(); ?>">
<div class="col-md-6">
<div class="form-group">
<label for="title"><b>Title:</b></label>
<input type="text" class="form-control" id="song_title">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="artist"><b>Artist:</b></label>
<input type="text" class="form-control" id="song_artist">
</div>
</div>
</div>
<div class="form-group">
<label for="comment"><b>Lyrics:</b></label>
<textarea class="form-control" rows="5" id="song_lyrics"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-danger btn_add_music" type="button">Submit</button>
</div>
</form>
</div>
</div>
I believe you are sending your token wrong. That syntax seems off, but not my expertise area. Try the following instead.
var formdata= new FormData();
fd.append('_token', $('.token').val());
i am a beginner in using form validation in codeigniter, now i am trying to use form validation codeigniter library, why this is not executed? i already loaded the $this->load->library('form_validation'); at the top of my controller. I mean i want the output where it puts error below my input type. Why my error in array('required' => 'Error Message on rule2 for this field_name')); doesnt appear in my view. Only in Response at console
Here is my fullcode:
VIEW:
<div class="modal fade large" id="admin_create_acct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header btn-success">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Create Account</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" id="frm_create_user">
<div class="form-group">
<label for="userFName" class="control-label col-sm-4">First Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="userFName" id="userFName" placeholder="First name">
<div class="msg"></div><!-- form-group -->
</div><!-- col-sm-6 -->
</div><!-- form-group -->
<div class="form-group">
<label for="userMName" class="control-label col-sm-4">Middle Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="userMName" id="userMName" placeholder="Middle name">
<div class="msg"></div><!-- form-group -->
</div><!-- col-sm-6 -->
</div><!-- form-group -->
</form><!-- form-horizontal -->
<button type="button" id="btn_reg" onclick="create_User()" class="btn btn-primary">Create Account</button>
i am just trying one input type and some error for validating, now here is my Controller code:
public function reg_user(){
$this->form_validation->set_rules('userFName', 'userFName', 'trim|required',
array('required' => 'Error Message on First name ')
);
$this->form_validation->set_rules('userMName', 'userMName', 'trim|required',
array('required' => 'Error Message on Middle Name')
);
if ($this->form_validation->run() == FALSE) {
$result['type'] = 'error';
$result['message'] = validation_errors();
}else {
$result['type'] = 'success';
$result['message'] = 'Whooos..! Your Succes Message';
}
echo json_encode($result);
}
my ajax from view:
function create_User() {
$.ajax({
url: siteurl+"admin_controls/reg_user",
type: "POST",
data: $("#frm_create_user").serialize(),
dataType: "JSON",
success: function(data) {
alert(" User Successfully Added added! ");
$("#frm_create_user")[0].reset();
}
});
}
Please follow this Method.
Or
If you just copy and paste this code it will definately work, all you need to just change the controller name in the form action
public function reg_user(){
$this->form_validation->set_rules('userFName', 'userFName', 'trim|required',
array('required' => 'Error Message on First name ')
);
$this->form_validation->set_rules('userMName', 'userMName', 'trim|required',
array('required' => 'Error Message on Middle Name')
);
if ($this->form_validation->run() == TRUE) {
$result['status'] = true;
$result['message'] = "Data inserted successfully.";
}else {
$result['status'] = false;
$result['message'] = $this->form_validation->error_array();
}
echo json_encode($result);
}
Now the Ajax Part
In Ajax i am using the FormData function instead of using serialize function. In case if you are going to upload files it will be helpful.
<script type="text/javascript">
$(document).ready(function() {
$("#form_data").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_data"));
$.ajax({
url : $("#form_data").attr('action'),
dataType : 'json',
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
$('.error').html('');
if(resp.status == false) {
$.each(resp.message,function(i,m){
$('.'+i).text(m);
});
}
}
});
});
return false;
});
View Part
<a data-toggle="modal" href='#admin_create_acct' class="list_sort">Select<a>
<div class="modal fade large" id="admin_create_acct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header btn-success">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Create Account</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" action="<?php echo base_url('Practice/test_user')?>" method="post" id="form_data">
<div class="form-group">
username : <input type="text" class="form-control" name="name">
<span class="error userFName"></span>
</div>
<div class="form-group">
password : <input type="text" class="form-control" name="userMName">
<span class="error userMName"></span>
</div>
<input type="submit" name="submit" value="submit">
</form>
</div>
</div>
</div>
</div>
This my where I submit my form to vue resource
<meta id="token" name="token" value="{{ csrf_token() }}">
<div class="modal fade" id="editroom" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Edit Blog Post</h4>
</div>
<div class="modal-body">
<form method="post" enctype="multipart/form-data" v-on:submit.prevent="updateRoom(fillRoom.id)">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Room Number:</label>
<input type="text" name="title" class="form-control" v-model="fillRoom.rn" />
</div>
<div class="form-group">
<label for="title">Status:</label>
<input type="text" name="title" class="form-control" v-model="fillRoom.status" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
This is my vue-resource/ajax. that calls the routes
Vue.http.headers.common['X-CSRF-TOKEN'] = $("#token").attr("value");
new Vue({
el: "#app",
data:{
newRoom: {'rt': ''},
rooms: [],
dT: '',
fillRoom : {'rn':'','status':'', 'id': ''}
},
mounted: function() {
this.getRooms();
},
methods:{
editRoom: function(room){
this.fillRoom.rn = room.room_no;
this.fillRoom.status = room.status;
this.fillRoom.id = room.room_id;
$("#editroom").modal('show');
},
updateRoom: function(id) {
var input = this.fillRoom;
this.$http.patch('/admin_page/rooms/'+id,input).then(response => {
this.newRoom = {'rt': ''};
$("#edit-item").modal('hide');
toastr.success('Item Updated Successfully.', 'Success Alert', {timeOut: 5000});
}, response => {
console.log(response.date);
});
},
}
});
And this my route resource that calls the controller
Route::group(['middleware' => ['web']], function() {
Route::get('/admin_page/rooms_page', 'RoomController#rooms_page');
Route::resource('admin_page/rooms', 'RoomController');
});
finally, this is my controller. it return json data after update
public function update(Request $request, $id)
{
$query = DB::table('rooms')
->where('id', $id)
->update(['room_no' => $request->input('rn')]);
return response()->json($query);
}
I want to make a simple CRUD using modal bootstrap and Jquery submit button and framework that i use is laravel 5.2, below is my controller, modal, jquery and routes, the problem is when i click save changes nothing happen, is there anything im doing wrong?
MODAL
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Add Barang</h3>
</div>
<div class="modal-body" id="addModal">
<form id="tambahform" class="form-horizontal" role="form">
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Name</label>
<div class="col-md-9">
<input type="text" id="client-nama" name="clientName" class="form-control" placeholder="Your Name">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn-add btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
JQuery
$(document).ready(function(){
var check1=0;
$('#tambahform').submit(function(e){
if (check1==0){
$("#addModal").animate({scrollTop:0}, 'slow');
}else{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url:'form/insert',
data:formData,
type:'POST',
contentType: false,
processData: false,
success:function(data){
$("#addModal").hide();
window.location.reload(true);
}
});
}
return false;
});
Controller
public function insert(){
$nama = Input::get('nama');
$this->nama = Input::get('clientName');
$query = DB::table('profile')->insert(array('nama'=>$nama));
}
ROUTES
Route::get('form/insert', 'FormController#insert');
You need to define the method you will be using to submit the form as. There is no method mentioned so it is submitting its default, GET.
so you form tag should look like this:
<form method="POST" id="tambahform" class="form-horizontal" role="form">
In the url, you need to give it a full path or else it will give a 404 not found error. Take a look at this code:
e.preventDefault();
var formData = $(tambahform).serialize(); //<--use Serialize
$.ajax({
url:'form/insert.php', //<--add full path including the files extension here
data:formData,
type:'POST',
contentType: false,
processData: false,
success:function(data){
$("#addModal").hide();
window.location.reload(true);
}
Instead of this
Route::get('form/insert', 'FormController#insert');
use this
Route::post('form/insert', 'FormController#insert');