Laravel Error Page After Create data using ajax and boostrap - php

So I'm trying create data using ajax and modal box from boostrap, but my pagination not using ajax, after created data Paginate and Table Has change by using render() in laravel.. after that I click Another page.. it making error Like This.. Click Me for Look the Error
web.php
Route::prefix('ajaxCrud')->group(function () {
Route::get('', 'ajaxCrudController#index')->name('crud.index');
Route::post('add', 'ajaxCrudController#masuk')->name('crud.add');
});
Javascript / crudCustom.js
$('#form-tambah').submit(function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: "json",
success: function (results) {
$('#tbody-row').html(results.template.table);
$('#paginate').html(results.template.paginate);
// ajaxLoad(results.url);
history.pushState(null, null, results.url);
}
});
});
AjaxCrudController.php
siswa::create([
'name' => $req->name,
'nomor' => $req->phone,
'alamat'=> $req->address
]);
$template = [
'table' => view('ajaxCrud.ajax.table')->with(['data' => $siswa])->render(),
'paginate' => view('ajaxCrud.ajax.paginate')->with(['data' => $siswa])->render()
];
$response = [
'status' => true,
'template' => $template,
'url' => route('crud.index')
];
return response()->json($response);
index.blade.php
#foreach ($data as $item)
<tr>
<td>{{$loop->iteration}}</td>
<td>{{$item->name}}</td>
<td>{{$item->nomor}}</td>
<td>{{$item->alamat}}</td>
<td>
<a class="btn btn-success" href="#">Edit</a>
<a class="btn btn-danger" href="#">Delete</a>
</td>
</tr>
#endforeach
Paginate
<div id="paginate">
{{ $data->links() }}
</div>
Modal
<form method="post" action="{{route('crud.add')}}" id="form-tambah">
#csrf
<span id="form_output"></span>
<div class="modal-body">
<div class="form-group">
<label for="nama">Name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="number" name="phone" class="form-control">
</div>
<div class="form-group">
<label for="address">Address</label>
<textarea name="address" class="form-control"></textarea>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-success">Add</button>
</div>
</form>

Related

how to send data from ajax to controller in lalravel? the keys form doesn't send from ajax 422 (Unprocessable Content)?

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 }}
},

A non-numeric value encountered ajax laravel

My form is like this
I'm working on a project and I would like to know which is the best way to showing the data after having to insert a record on the database having a complex structure HTML between using the structure in Laravel or jQuery.
I'm building a system of jobs. When the user writes the post and publishes it a call ajax triggers the function Laravel and it inserts the information on the database. until here all OK, but then I have to display the message insert on the wall of the user, so did not work.
<form id="job-store" method="post">
<input type="hidden" value="{{ route('job.store') }}" name="url" />
#csrf
<div class="row">
<div class="col-md-6 mb-3">
<label for="employment_type">نوع استخدام</label>
<select class="form-control selectpicker" title="چیزی انتخاب نشده است" id="employment_type" name="employment_type">
<option value="حق التدریس">حق التدریس</option>
<option value="رسمی">رسمی</option>
<option value="پیمانی">پیمانی</option>
<option value="قراردادی">قراردادی</option>
</select>
</div>
<div class="col-md-6 mb-3">
<label for="job_type">عنوان شغلی</label>
<select class="form-control selectpicker" title="چیزی انتخاب نشده است" id="job_type" name="job_type">
<option value="مربی درون سازمانی">مربی درون سازمانی</option>
<option value="مربی حق التدریس">مربی حق التدریس</option>
<option value="صنعتکار">صنعتکار</option>
<option value="مدرس دانشگاه">مدرس دانشگاه</option>
<option value="استادکار مهارتی">استادکار مهارتی</option>
<option value="سایر">سایر</option>
</select>
</div>
<div class="col-md-6 mb-3">
<label for="history">سابقه (سال)</label>
<input type="text" class="form-control" id="history" name="history">
</div>
<div class="col-md-6 mb-3">
<label for="post_title">عنوان پست</label>
<input type="text" class="form-control" id="post_title" name="post_title">
</div>
<div class="col-md-6 mb-3">
<label for="state">استان محل خدمت</label>
<input type="text" class="form-control" id="state" name="state">
</div>
<div class="col-md-6 mb-3">
<label for="city">شهر محل خدمت</label>
<input type="text" class="form-control" id="city" name="city">
</div>
<div class="col-md-6 mb-3">
<label for="start_date">تاریخ شروع به كار</label>
<date-picker type="date" id="start_date" name="start_date"></date-picker>
</div>
<div class="col-md-6 mb-3">
<label for="end_date">تاریخ خاتمه كار</label>
<date-picker type="date" id="end_date" name="end_date"></date-picker>
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<button type="submit" class="btn btn-success job-store"><i class="fas fa-plus fa-xs"></i> افزودن</button>
</div>
</div>
</form>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>ردیف</th>
<th>نوع استخدام</th>
<th>تاریخ شروع کار</th>
<th>تاریخ خاتمه کار</th>
<th>استان محل خدمت</th>
<th>شهر محل خدمت</th>
<th>اکشن</th>
</tr>
</thead>
<tbody id="showJobs">
</tbody>
</table>
</div>
#section('script')
<script>
$(document).ready(function (e) {
$('.job-store').on('click',(function(e) {
e.preventDefault();
var formData = new FormData($('#job-store')[0]);
let url = $('#job-store :input')[0].getAttribute('value');
$.ajax({
type:'POST',
url,
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
showJobs(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
function showJobs(data) {
let html = '';
$.each(data, function (key, val) {
$('#data').append("<tr>"+
"<td>"+val.id+"</td>"+
"<td>"+val.employment_type+"</td>"+
"<td>"+val.start_date+"</td>"+
"<td>"+val.end_date+"</td>"+
"<td>"+val.state+"</td>"+
"<td>"+val.city+"</td>"+
"<td>"+
'<form action="{{ route('job.destroy',+'val.id') }}" method="post">'+
'#csrf'+
'#method('DELETE')'+
'<div class="btn-group">'+
'Edit'+
'<button type="submit" class="btn btn-danger btn-sm">Delete</button>'+
'</div>'+
'</form>'+
"</td>"+
"</tr>"
)});
$('#showJobs').append(html);
}
});
</script>
#endsection
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests\JobRequest;
use App\Job;
use Illuminate\Http\Request;
class JobController extends Controller
{
public function store(Request $request)
{
Job::create([
'user_id' => auth()->id(),
'employment_type' => $request->employment_type,
'job_type' => $request->job_type,
'post_title' => $request->post_title,
'history' => $request->history,
'state' => $request->state,
'city' => $request->city,
'start_date' => $request->start_date,
'end_date' => $request->end_date,
]);
return redirect()->back();
}
public function edit(Job $job)
{
return view('Home.edits.job', compact('job'));
}
public function update(Request $request, Job $job)
{
$data = [
'employment_type' => $request->employment_type,
'job_type' => $request->job_type,
'post_title' => $request->post_title,
'history' => $request->history,
'state' => $request->state,
'city' => $request->city,
'start_date' => $request->start_date,
'end_date' => $request->end_date,
];
$job->update($data);
return redirect()->route('home');
}
public function destroy(Job $job)
{
$job->delete();
return redirect()->back();
}
}
It is my console
I get this error
Instead of appending in javascript better create view for that file and return view from controller
First controller must return view or json but it returning redirect back.
public function store(Request $request)
{
Job::create([
'user_id' => auth()->id(),
'employment_type' => $request->employment_type,
'job_type' => $request->job_type,
'post_title' => $request->post_title,
'history' => $request->history,
'state' => $request->state,
'city' => $request->city,
'start_date' => $request->start_date,
'end_date' => $request->end_date,
]);
$jobs= Job::get();
return view('jobdetail',compact('jobs'));
}
and jobdetail blade
#foreach($jobsas $key=>$value)
<tr>
<td>{{$value->id}}</td>
<td>{{$value->employment_type}}</td>
<td>{{$value->start_date}}</td>
<td>{{$value->end_date}}</td>
<td>{{$value->state}}</td>
<td>{{$value->city}}</td>
<td>
<form action={{ route('job.destroy',$value->id) }} method=post>
#csrf
#method('DELETE')
<div class=btn-group>
<a href={{ route('job.edit',$value->id) }} class=btn btn-info btn-sm>Edit</a>
<button type=submit class=btn btn-danger btn-sm>Delete</button>
</div>
</form>
</td>
</tr>
#endforeach
and in JavaScript
$.ajax({
type:'POST',
url,
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
$('#showJobs').html(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
Also if you want to append last created job detail then
public function store(Request $request)
{
$job=Job::create([
'user_id' => auth()->id(),
'employment_type' => $request->employment_type,
'job_type' => $request->job_type,
'post_title' => $request->post_title,
'history' => $request->history,
'state' => $request->state,
'city' => $request->city,
'start_date' => $request->start_date,
'end_date' => $request->end_date,
]);
return view('jobdetail',compact('job'));
}
then in view jobdetail
<tr>
<td>{{$job->id}}</td>
<td>{{$job->employment_type}}</td>
<td>{{$job->start_date}}</td>
<td>{{$job->end_date}}</td>
<td>{{$job->state}}</td>
<td>{{$job->city}}</td>
<td>
<form action={{ route('job.destroy',$job->id) }} method=post>
#csrf
#method('DELETE')
<div class=btn-group>
<a href={{ route('job.edit',$job->id) }} class=btn btn-info btn-sm>Edit</a>
<button type=submit class=btn btn-danger btn-sm>Delete</button>
</div>
</form>
</td>
</tr>
and in JavaScript
$.ajax({
type:'POST',
url,
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
$('#showJobs').append(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});

Ajax response in not working properly in laravel 7

I am doing a simple insert in laravel 7 using ajax, here the validation is working properly but the success result is not working or showing propoerly.
The routes are
// Product Poutes
Route::get('create/product', 'Product\ProductController#create')->name('createProduct');
Route::post('store/product', 'Product\ProductController#store')->name('storeProduct');
The Model is
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
//
protected $fillable = [
'name', 'category_id','sell_price','purchase_price',
];
}
The Controller code
public function store(Request $request)
{
$validation = Validator::make(
$request->all(),
[
'name' => 'required|unique:products|max:120|min:4',
'category_id' => 'required',
'sell_price' => 'required',
'purchase_price' => 'required'
]
);
if ($validation) {
return response()->json(['error' => $validation->errors()->all()]);
}
$product = new Product;
$product->name = $request->name;
$product->category_id = $request->category_id;
$product->sell_price = $request->sell_price;
$product->purchase_price = $request->purchase_price;
$product->save();
return response()->json(['success' => "New Product Added!"]);
}
The Blade form
#extends('layouts.newApp')
<!-- Product create -->
#section('content')
<!-- Begin Page Content -->
<div class="container">
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">Create Product</h1>
<div class="row">
<form method="POST">
#csrf
<div class="row justify-content-center">
<div class="form-group col-md-10">
<div id="div-error" class="col-md-10 justify-content-center">
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
</div>
</div>
<div class="form-group col-md-10">
<label for="category">Category</label>
<select id="category_id" class="form-control custom-select" name='category_id'>
<option selected>Choose...</option>
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-10">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Product Name" name='name'>
</div>
<div class="form-group col-md-5">
<label for="sell_price">Notes</label>
<input type="number" class="form-control" id="sell_price" placeholder="sell_price"
name='sell_price'>
</div>
<div class="form-group col-md-5">
<label for="purchase_price">Notes</label>
<input type="number" class="form-control" id="purchase_price" placeholder="purchase_price"
name='purchase_price'>
</div>
<div class="form-group col-md-10">
<button class="btn btn-primary btn-submit" type="submit">Submit</button>
</div>
</div>
</form>
</div>
</div>
<script>
$(document).ready(function() {
$(".btn-submit").click(function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content')
}
});
var category_id = document.getElementById("category_id").value;
var name = $("input[name=name]").val();
var sell_price = $("input[name=sell_price]").val();
var purchase_price = $("input[name=purchase_price]").val();
$.ajax({
type: 'POST',
url: "{{ route('storeProduct') }}",
dataType: 'json',
data: {
category_id: category_id,
name: name,
sell_price: sell_price,
purchase_price: purchase_price
},
success: function(data) {
if ($.isEmptyObject(data.error)) {
alert(data.success);
} else {
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>
#endsection
The validation is working fine:
But after I add data and press submit it returns undefined type:
I tried all sort of possible method found non.
Hope to sort out the problem very soon.
may be you are getting some error in your response.why dont you check your ajax hit in inspect element to see what its returning i think its returning some php error or something else or you data in json maybe

Laravel post form without refresh problem

I wrote a code to submit a form without page refresh in laravel and here's my codes :
my view :
<form action="{{ url('/admin/products/new') }}" method="post">
{{ csrf_field() }}
<div class="form-group row">
<label for="example-text-input" class="col-sm-2 col-form-label">pid</label>
<div class="col-sm-10">
<input type="text" id="pid" name="pid" class="form-control" placeholder="مثال : Oil distillation machine" id="name">
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-sm-2 col-form-label">name</label>
<div class="col-sm-10">
<input type="text" id="name" name="name" class="form-control" placeholder="مثال : Oil distillation machine" id="name">
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-sm-2 col-form-label">value</label>
<div class="col-sm-10">
<input type="text" id="value" name="value" class="form-control" placeholder="مثال : Oil distillation machine" id="name">
</div>
</div>
<div class="form-group">
<button type="submit" id="submit" class="btn btn-primary btn-lg text-center waves-effect waves-light">ارسال</button> </div>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#submit').click(function(e){
e.preventDefault();
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/admin/products/new') }}",
method: 'post',
data: {
name: jQuery('#pid').val(),
email: jQuery('#name').val(),
subject: jQuery('#value').val(),
},
success: function(data){
jQuery.each(data.errors, function(key, value){
jQuery('.alert-danger').show();
jQuery('.alert-danger').append('<p>'+value+'</p>');
});
}
});
});
});
</script>
</form>
my controller :
public function add_product_post(Request $request)
{
$pid = $request->pid;
$name = $request->name;
$value = $request->value;
DB::table('product_features')->insert([
'pid' => $pid,
'name' => $name,
'value' => $value
]);
return ['message' => 'success'];
}
my problem is that when i click on submit button i just get a response in blank page {"message":"success"}
I want to submit my form without any page refreshing.
What is wrong with my code?
Thanks
In your controller action, you just return an array, plz change it to response:
public function add_product_post(Request $request)
{
$pid = $request->pid;
$name = $request->name;
$value = $request->value;
DB::table('product_features')->insert([
'pid' => $pid,
'name' => $name,
'value' => $value
]);
return response()->json(['message' => 'success']);
}
Another thing is in jquery ajax,you need to display the success message instead of the error message.
I'm not sure but try to change the button type into "button"
<button type="button" id="submit" class="btn btn-primary btn-lg text-center waves-effect waves-light">ارسال</button>

Display return message for Ajax response from Laravel

I've got a working form that submits to a database from an HTML form using Laravel Collective that submits to my Controller, and it works fine.
I want to submit it without a page reload, so I'm submitting the data with AJAX.
I've got it working, and it's writing to the db, but I can't get the controller to return the response to the page on success.
The following is my script:
SCRIPT:
$(document).ready(function(){
$("#msg").hide();
$("#submit").click(function() {
$("#msg").show();
var name = $("#recipeName").val();
var description = $("#recipeDescription").val();
var token = $("#token").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
data: "name="+name+"&description="+description,
dataType:'json',
url: "{{ route('recipes.store') }}",
success:function(data){
$("#msg").html("Recipe Saved");
$("#msg").fadeOut(2000);
}
});
})
})
HTML:
<div class="row">
<div class="col">
<p class="alert alert-success" id="msg"></p>
</div>
</div>
<div class="row">
<div class="col">
<!-- Start Form -->
<input type="hidden" name="csrf" value="{{csrf_token()}}" id="token">
<div class="form-group">
<label for="recipeName">Recipe name:</label>
<input type="text" class="form-control" id="recipeName" aria-describedby="emailHelp" placeholder="Enter recipe name">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="recipeDescription">Recipe Description:</label>
<textarea class="form-control" id="recipeDescription" rows="3" placeholder="Enter a recipe description"></textarea>
</div>
<button type="submit" class="btn btn-primary btn-block btn-lg" id="submit">Submit</button>
<!-- End Form -->
</div>
</div>
CONTROLLER:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'description' => 'required'
]);
$recipe = new Recipe;
$recipe->name = $request->name;
$recipe->description = $request->description;
$recipe->user_id = auth()->user()->id;
$recipe->save();
return Response::json(array(
'success' => true,
'data' => $data
));
}
I can't workout what it is that I'm missing.
I'm learning AJAX on the fly (I'm learning all of it on the fly if I'm honest!), but as I say, it's writing to the db successfully, just need to notify the user of it.
SCRIPT
$("#submit").click(function() {
$("#msg").show();
var name = $("#recipeName").val();
var description = $("#recipeDescription").val();
$.ajax({
type: "post",
data: {name:name,description:description,'_token':'{{csrf_token()}}'},
dataType:'json',
url: "{{ route('recipes.store') }}",
success:function(data){
$("#msg").html("Recipe Saved");
$("#msg").fadeOut(2000);
}
});
});
HTML
change the the type of submit button from submit to button
<div class="row">
<div class="col">
<p class="alert alert-success" id="msg"></p>
</div>
</div>
<div class="row">
<div class="col">
<!-- Start Form -->
<input type="hidden" name="csrf" value="{{csrf_token()}}" id="token">
<div class="form-group">
<label for="recipeName">Recipe name:</label>
<input type="text" class="form-control" id="recipeName" aria-describedby="emailHelp" placeholder="Enter recipe name">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="recipeDescription">Recipe Description:</label>
<textarea class="form-control" id="recipeDescription" rows="3" placeholder="Enter a recipe description"></textarea>
</div>
<button type="button" class="btn btn-primary btn-block btn-lg" id="submit">Submit</button>
<!-- End Form -->
Controller
you must identify $data variable
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'description' => 'required'
]);
$data = 'some data';
$recipe = new Recipe;
$recipe->name = $request->name;
$recipe->description = $request->description;
$recipe->user_id = auth()->user()->id;
$recipe->save();
return Response::json(array(
'success' => true,
'data' => $data
));
}
Changing the following in the controller works correctly!
...
$recipe->save();
$data = [
'success' => true,
'message'=> 'Your AJAX processed correctly'
] ;
return response()->json($data);

Categories