Ajax not displaying error message itself, box only - ajax

For some reason AJAX is not passing the error message. Whatever I try to submit in my form, I get red line (error message style) but without error message init, which makes hard for me to debug. Any ideas what is causing error message not to be displayed?
My AJAX function, pointing to store method in TicketCategory controller:
$(document).ready(function() {
$("#btn-add").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/ticket-category/store',
data: {
name: $("#frmAddTicketCategory input[name=name]").val(),
},
dataType: 'json',
$('#frmAddTicketCategory').trigger("reset");
$("#frmAddTicketCategory .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#add-ticket-category-errors').html('');
$.each(errors.messages, function(key, value) {
$('#add-ticket-category-errors').append('<li>' + value + '</li>');
});
$("#add-error-bag").show();
}
});
});
My view:
<div class="modal fade" id="addTicketCategoryModal">
<div class="modal-dialog">
<div class="modal-content">
<form id="frmAddTicketCategory">
<div class="modal-header">
<h4 class="modal-title">
Add New Task
</h4>
<button aria-hidden="true" class="close" data-dismiss="modal" type="button">
×
</button>
</div>
<div class="modal-body">
<div class="alert alert-danger" id="add-error-bag">
<ul id="add-ticket-category-errors">
</ul>
</div>
<div class="form-group">
<label>
Name
</label>
<input class="form-control" id="name" name="name" type="text">
</input>
</div>
</div>
<div class="modal-footer">
<input class="btn btn-default" data-dismiss="modal" type="button" value="Cancel">
<button class="btn btn-info" id="btn-add" type="button" value="add">
Add New Task
</button>
</input>
</div>
</form>
</div>
</div>
</div>
Controller:
public function create()
{
return view('ticket_category/ticket_cat',[
'tickets' => TicketCategory::all()
]);
}
public function store(Request $request)
{
$validator = Validator::make($request->input(), array(
'name' => 'required'
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$ticket_category = TicketCategory::create([$request->name]);
return response()->json([
'error' => false,
'ticket_category' => $ticket_category,
], 200);
}
see the error issue

I think value is an array of errors for a field that is why you are not able to display the errors. Try this
$('#add-ticket-category-errors').append('<li>' + value[0] + '</li>')

Related

How to solve Laravel Post Error 403 with ajax?

I want to insert some record into database table which is using server side mode. Im using laravel 8, php version 8.0.13, database mysql.
This is my Route
use App\Http\Controllers\JabatanController;
Route::resource('jabatan', JabatanController::class, [
'names' => [
'index' => 'jabatan.list',
'store' => 'jabatan.store',
]]);
//dd($request->all());
My view
<button type="button" id="tambah-jabatan" class="btn btn-primary float-right" data-toggle="modal" data-target="#modal_tambah">
Tambah Jabatan
</button>
<!-- Modal -->
<div class="modal fade" id="modal_tambah" tabindex="-1" role="dialog" aria-labelledby="modalTambahLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalTambahLabel">Tambah Data Jabatan</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- mb -->
<div class=" mb-3">
<label for="jabatan">Jabatan</label>
<input type="text" name="jabatan" class="form-control" id="jabatan" placeholder="Masukkan Jabatan disini" value="" required>
</div>
<!-- /mb -->
</div>
<div class="modal-footer">
<button type="button" id="close" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="save-jabatan" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
My Controllers
public function store(StoreJabatanRequest $request)
{
$data = Jabatan::updateOrCreate([
'jabatan' => $request->jabatan,
]);
return response()->json($data);
}
My Model
class Jabatan extends Model
{
use HasFactory;
protected $table = "jabatans";
protected $fillable = [
'jabatan'
];
}
some ajax script in my main view
<script>
$('#save-jabatan').on('click', function() {
$.ajax({
url: "{{route('jabatan.store')}}",
type: "post",
data: {
jabatan: $('#jabatan').val(),
"_token": "{{csrf_token()}}"
},
success: function(res) {
console.log(res.data);
alert(res.text)
$('#close').click()
$('#tb_jabatan').DataTable().ajax.reload()
},
error: function(xhr) {
alert(xhr.responseJSON.text)
}
})
})
</script>
and when im check on inspect i got this error
POST http://localhost:8000/jabatan 403 (Forbidden)
there's any suggestion?
Ok, so in my case the problem is on my App\Http\Request\StoreJabatanRequest.php
class StoreJabatanRequest extends FormRequest;
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'jabatan' => 'required'
];
}

Laravel & Vue.js Form Validation Errors

I am getting a continuous validation error despite the data being valid. I originally had this forming working, at the time I was only storing one email at a time. When I added the "addNewRow" function, I was unable to post the data. Each time I get a validation error, I am quite new to Vue, and I'm not sure where I am going wrong with either the post method or my validation.
Here is my controller:
public function notifyTeam(Request $request, Agency $id)
{
$request->validate([
'email' => 'unique:users|required|email|max:255|unique:agency_emails',
]);
$user = Auth::user();
$agency = Agency::where('id', $user->agency_id)->first();
$subdomain = $agency->subdomain;
$emails = json_decode($request->getContent('emailArray'), true);
foreach($emails as $email){
$authorizedEmails = new AgencyEmail;
$authorizedEmails->email = $request->email;
$authorizedEmails->agency_id = $agency->id;
$authorizedEmails->save();
}
// Generate Link
// /{subdomain}/register
// Email the link to specified users
// vue component
return redirect()->route('dashboard');
}
And here is my Vue Component:
<template>
<div class="row justify-content-center">
<div class="col-md-4">
<div class="row justify-content-center">
</div>
<h1 class="agency_h1 mt-5 mb-5">ASSEMBLE THE TROOPS</h1>
<form method="POST" #submit.prevent="submit">
<input type="hidden" name="_token" :value="csrf">
<label for="email">E-mail Address</label>
<div class="form-group row" v-for="(field, k) in fields" :key="k">
<div class="input-group">
<input id="email" type="email" class="form-control" name="email[]" v-model="field.email"
required placeholder="Add An Email Address">
</div>
<div class="col">
<div class="alert alert-success alert-dismissible fade show sticky-top mt-2" role="alert"
v-show="success">
Emails Have Been Seent
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="alert alert-danger alert-dismissible fade show sticky-top mt-2" role="alert"
v-if="errors && errors.email">
{{ errors.email[0] }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</div>
<button type="submit" class="btn btn-success mb-2" #click="addNewRow">Add Row +</button>
<button type="submit" class="btn btn-primary btn-block mb-5" >Create Your Agency</button>
</form>
</div>
</div>
</template>
<script>
export default {
data() {
return {
fields: [{
email: '',
}],
errors: {},
success: false,
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content')
}
},
methods: {
addNewRow() {
this.fields.push({
email: '',
});
},
submit() {
axios.post('/create-team', {
emailArray: this.fields
})
.then(response => {
this.fields = {};
this.success = true;
this.errors = {};
})
.catch(error => {
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
console.log('Still not saved');
});
},
},
}
</script>

Sharing data between all Vue.js components

I'm building a CRUD web app using Laravel/Vue.js for the first time. I'm using a MySQL database and I used many Vue.js components, and each one can access a table in the database. Now I need to make some components to get data from other components to use it in a drop down, but I can't figure it out.
I tried using props but always get errors.
This is in the child vue:
<div class="form-group">
<select v-model="form.fabnom" type="text" name="fabnom" id="fabnom" class="form-control" :class="{ 'is-invalid': form.errors.has('fabnom') }">
<option v-for="fabriquant in fabriquants" :key="fabriquant.id" :value="fabriquant.fabnom">
</option>
</select>
<has-error :form="form" field="fabnom"></has-error>
</div>
<script>
export default {
data(){
return{
editmode: false,
machines :{},
form: new Form({
id:'',
code:'',
nom: '',
type:'',
serie:'',
date:'',
fabnom:'',
section:'',
unite:''
})
}
} ,
This is the API:
Route::apiResources([
'user' => 'API\UserController',
'fabriquant' => 'API\FabriquantController',
'machine' => 'API\MachineController',]);
Child controller(Parent one is nearly the same):
public function index()
{
//$this->authorize('isAdmin');
if (\Gate::allows('isAdmin')) {
return Machine::latest()->paginate(5);
}
}
public function store(Request $request)
{
$this->validate($request,[
'code' => 'required|string|max:191|unique:machines',
'nom' => 'required|string|max:191',
'type' => 'max:191',
'serie' => 'max:191',
'date' => 'max:191',
'fabnom' => 'max:191',
'section' => 'max:191',
'unite' => 'max:191',
]);
return Machine::create([
'code'=> $request['code'],
'nom'=> $request ['nom'],
'type'=> $request['type'],
'serie'=> $request['serie'],
'date'=> $request['date'],
'fabnom'=> $request['fabnom'],
'section'=> $request['section'],
'unite'=> $request['unite'],
]);
}
public function show($id)
{
//
}
public function update(Request $request, $id)
{
$machine = Machine::findOrFail($id);
$this->validate($request,[
'code' => 'required|string|max:191|unique:machines,code,'.$machine->id,
'nom' => 'max:191',
'type' => 'max:191',
'serie' => 'max:191',
'date' => 'max:191',
'fabnom' => 'max:191',
'section' => 'max:191',
'unite' => 'max:191',
]);
$machine->update($request->all());
return ['message' => 'Updated'];
}
public function destroy($id)
{
$machine = Machine::findOrFail($id);
// delete
$machine->delete();
return ['message' => 'Deleted'];
}
}
EDIT: You can see in the child component there is a string called fabnom and in the parent there is one also: so lets just say now I'm in the parent component and I added 3 items to its database via a modal each item has 6 columns in the database, one of them is called fabnom, now I passed to the child component page I opened an 'addNew' model and there is a dropdown box labeled fabnom which should have the 3 options that I already added I choose one of them and this value is going to be stored in the fabnom column of the database of the child component (I hope you get the idea guys)
This the parent.vue(The child one looks pretty the same the only difference that it has also a dropdown box in its 'addNew' model as mentioned up which is causing the problem):
<template>
<div class="container">
<div class="row mt-5" v-if="$gate.isAdmin()">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Liste des Fabriquants</h3>
<div class="card-tools">
<button class="btn btn-success" #click="newModal">
Ajouter</button>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover">
<tbody>
<tr>
<th>Nom</th>
<th>Adresse</th>
<th>Téléphone</th>
<th>Fax</th>
<th>E-mail</th>
</tr>
<tr v-for="fabriquant in fabriquants.data" :key="fabriquant.id">
<td>{{fabriquant.fabnom}}</td>
<td>{{fabriquant.adresse}}</td>
<td>{{fabriquant.tel}}</td>
<td>{{fabriquant.fax}}</td>
<td>{{fabriquant.email}}</td>
<td>
<a href="#" #click="editModal(fabriquant)">
<i class="fa fa-edit"></i>
</a>
/
<a href="#" #click="deleteFabriquant(fabriquant.id)">
<i class="fa fa-trash"></i>
</a>
</td>
</tr>
</tbody></table>
</div>
<!-- /.card-body -->
<div class="card-footer">
<pagination :data="fabriquants" #pagination-change-page="getResults"></pagination>
</div>
</div>
<!-- /.card -->
</div>
</div>
<div v-if="!$gate.isAdmin()">
<not-found></not-found>
</div>
<!-- Modal -->
<div class="modal fade" id="Ajouter" tabindex="-1" role="dialog" aria-labelledby="AjouterLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-show="!editmode" id="AjouterLabel">Ajouter</h5>
<h5 class="modal-title" v-show="editmode" id="AjouterLabel">Modifier</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form #submit.prevent="editmode ? updateFabriquant() : createFabriquant()">
<div class="modal-body">
<div class="form-group">
<input v-model="form.fabnom" type="text" name="fabnom"
placeholder="Nom"
class="form-control" :class="{ 'is-invalid': form.errors.has('fabnom') }">
<has-error :form="form" field="fabnom"></has-error>
</div>
<div class="form-group">
<input v-model="form.adresse" type="text" name="adresse"
placeholder="Adresse"
class="form-control" :class="{ 'is-invalid': form.errors.has('adresse') }">
<has-error :form="form" field="adresse"></has-error>
</div>
<div class="form-group">
<input v-model="form.tel" type="text" name="tel"
placeholder="Téléphone"
class="form-control" :class="{ 'is-invalid': form.errors.has('tel') }">
<has-error :form="form" field="tel"></has-error>
</div>
<div class="form-group">
<input v-model="form.fax" type="text" name="fax"
placeholder="Fax"
class="form-control" :class="{ 'is-invalid': form.errors.has('fax') }">
<has-error :form="form" field="fax"></has-error>
</div>
<div class="form-group">
<input v-model="form.email" type="email" name="email"
placeholder="E-mail"
class="form-control" :class="{ 'is-invalid': form.errors.has('email') }">
<has-error :form="form" field="email"></has-error>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Fermer</button>
<button v-show="editmode" type="submit" class="btn btn-success">Modifier</button>
<button v-show="!editmode" type="submit" class="btn btn-primary">Ajouter</button>
</div>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
editmode: false,
fabriquants :{},
form: new Form({
id:'',
fabnom:'',
adresse: '',
tel:'',
fax:'',
email:''
})
}
},
methods: {
getResults(page = 1) {
axios.get('api/fabriquant?page=' + page)
.then(response => {
this.fabriquants = response.data;
});
},
updateFabriquant(){
this.$Progress.start();
// console.log('Editing data');
this.form.put('api/fabriquant/'+this.form.id)
.then(() => {
// success
$('#Ajouter').modal('hide');
Swal.fire(
'Modifié!',
'Informations modifiés!',
'success'
)
this.$Progress.finish();
Fire.$emit('AfterCreate');
})
.catch(() => {
this.$Progress.fail();
});
},
editModal(fabriquant){
this.editmode = true;
this.form.reset();
$('#Ajouter').modal('show');
this.form.fill(fabriquant);
},
newModal(){
this.editmode = false;
this.form.reset();
$('#Ajouter').modal('show');
},
deleteFabriquant(id){
Swal.fire({
title: 'Voulez vous vraiment supprimer cet fabriquant?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Oui, Supprimer!',
}).then((result) => {
// Send request to the server
if (result.value) {
this.form.delete('api/fabriquant/'+id).then(()=>{
Swal.fire(
'Supprimé!',
'Element supprimé.',
'success'
)
Fire.$emit('AfterCreate');
}).catch(()=> {
Swal.fire("Echec!", "Il y'a un problème.", "warning");
});
}
})
},
loadFabriquants(){
if(this.$gate.isAdmin()){
axios.get("api/fabriquant").then(({ data }) => (this.fabriquants = data));
}
},
createFabriquant(){
this.$Progress.start();
this.form.post('/api/fabriquant')
.then(()=>{
Fire.$emit('AfterCreate');
$('#Ajouter').modal('hide');
toast.fire({
type: 'success',
title: 'Fabriquant ajouté',
})
this.$Progress.finish();
})
.catch(()=>{
})
}
},
created() {
this.loadFabriquants();
Fire.$on('AfterCreate',()=>{
this.loadFabriquants();
});
}
}
</script>
If I understand your main issue, you could use something like an instance property or a javascript file to hold variables in client-side storage.
From what I understand, what you need is a way to first get data from your MySQL using one component, and then second, use that data in all the rest of your components. If so, I had this need with my current project about 2 months ago.
The only problem is that I'm not using Laravel/Vue but Vue.js, VueApollo, and GraphQL. Although, I'm pretty sure --and hope-- the way that I fixed my issue will only differ in syntax from the way you could solve yours.
I used a component to query some info from the user right after they log in.
Vue/Apollo Query
apollo: {
// Simple query that gets user info
me: {
query: gql` //GraphQL
{
me {
id
fullName
}
}
`,
loadingKey: "isLoading" //tracks results that are still loading.
}
}
Then I wanted to store the user's 'fullName' somewhere so that my navigation component could always use it. So I created a file:
src/config/credentialStore.js
In this file I created a displayName variable like this:
export const credentialStore = {
displayName: "",
userID: ""
};
Back in the component where I have the 'me' query, I destructured the data that was returned from the query with a function.
apollo: {
// Simple query that gets user info
me: {
query: gql`
{
me {
id
fullName
}
}
`,
loadingKey: "isLoading",
result({ data }) { //data is basically an object with the results of the query
this.$credentials.userId = data.me.id;
this.$credentials.displayName = data.me.fullName;
} //using this.$credentials.displayName will let me use that string from any component.
}
}
So you would do something like that and then maybe something like this:
<script>
export default {
data(){
return{
editmode: false,
fabriquants :{},
form: new Form({
id: this.$credentialStore.id,
fabnom:this.$credentialStore.fabnom, //what's a fabnom? 🤔
• • •
})
}
},
I hope this helps you or someone else.

Symfony\Component\HttpKernel\Exception\HttpException- Ajax post request

In the step 2 of a multi step form, if a radio button is selected and "go to step 3" is clicked or if no radio button is selected and "go to step 3" is clicked it appears always this error below:
{message: "", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}
exception"Symfony\Component\HttpKernel\Exception\HttpException"
file "/Users/johnw/projects/store/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php" line : 203 message: "" trace:[{,…},…]
Do you know where can be the issue?
Html for the step 2:
<form method="post" id="step2form" action="">
<h6>Payment method</h6>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="radio" name="payment_method" value="option1">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Payment method 1</span>
</label>
</div>
<br>
<div class="form-check">
<input class="form-check-input" type="radio" name="payment_method" value="option1">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Payment method 2</span>
</label>
</div>
</div>
<br>
<div class="text-right">
<button type="button" href="#step3" data-toggle="tab" role="tab"
class="btn btn-outline-primary prev-step">
Go back to step 2
</button>
<input type="submit" href="#step2" id="goToStep3"
class="btn btn-primary btn float-right next-step"
value="Go to step 3"/>
</div>
</form>
PaymentController method to handle ajax request for step 2:
public function storePaymentMethods(Request $request, $id, $slug = null, Validator $validator){
$validator = Validator::make($request->all(),[
'payment_method' => 'required',
]);
if($validator->passes())
{
return response()->json([
'success' => true,
'message' => 'success'
], 200);
}
$errors = $validator->errors();
$errors = json_decode($errors);
return response()->json([
'success' => false,
'errors' => $errors
], 422);
}
ajax:
$('#goToStep3').on('click', function (event) {
event.preventDefault();
var custom_form = $("#" + page_form_id);
$.ajax({
method: "POST",
url: '{{ route('products.storePaymentMethods', compact('id','slug') ) }}',
data: custom_form.serialize(),
datatype: 'json',
success: function (data, textStatus, jqXHR) {
},
error: function (data) {
var errors = data.responseJSON;
var errorsHtml = '';
$.each(errors['errors'], function (index, value) {
errorsHtml += '<ul class="alert alert-danger mt-3"><li class="text-danger">' + value + '</li></ul>';
console.log(errorsHtml);
});
$('#response').show().html(errorsHtml);
}
});
you have not added any csrf token with your form. There are several ways to do it like below mentioned ways -
Add {{ csrf_field() }} inside your form
or add token with your ajax request like _token:"{{ csrf_token() }}"

Ajax post request- Unresolvable dependency resolving and error 500

I'm trying to create a multi-step form using jQuery anad AJAX. But Im getting this error when "go to step 2" is clicked:
jquery.min.js:4 POST http://store.test/product/1/product-test/payment/storeUserInfo 500 (Internal Server Error)
Also when clicking in network tab and then click in "storeUserInfo" it appears:
exception
:
"Illuminate\Contracts\Container\BindingResolutionException"
file
:
"/Users/jakeB/projects/store/vendor/laravel/framework/src/Illuminate/Container/Container.php"
line
:
933
message
:
"Unresolvable dependency resolving [Parameter #1 [ <required> array $data ]] in class Illuminate\Validation\Validator"
Do you know where is the error?
In the PaymentController there is the storeUserInfo() Method that is the method for the step 1:
public function storeUserInfo(Request $request, $id, $slug = null, Validator $validator){
$validator = Validator::make($request->all(),[
'buyer_name' => 'required|max:255|string',
'buyer_surname' => 'required|max:255|string',
'buyer_email' => 'required|max:255|string',
'name_invoice' => 'required|max:255|string',
'country_invoice' => 'required|max:255|string',
]);
if ($validator->fails()) {
if($request->ajax())
{
return response('test');
}
$this->throwValidationException(
$request, $validator
);
}
}
Route:
Route::post('/product/{id}/{slug?}/payment/storeUserInfo', [
'uses' => 'PaymentController#storeUserInfo',
'as' =>'products.storeUserInfo'
]);
// step 1 and step 2 html
<div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab">
<h6>User Info</h6>
<form method="post" id="step1form" action="">
{{csrf_field()}}
<div class="form-group font-size-sm">
<label for="name" class="text-gray">Name</label>
<input name="name" type="text" required class="form-control" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
</div>
<!-- other form fields -->
<input type="submit" id="goToStep2" href="#step2"
class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
</div>
<div class="tab-pane fade clearfix tabs hide" id="step2" role="tabpanel" aria-labelledby="profile-tab">
<form method="post">
<h6>Payment method</h6>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="radio" name="paymentmethod1" value="option1" checked>
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">payment method 1</span>
</label>
</div>
<br>
<div class="form-check">
<input class="form-check-input" type="radio" name="credit_card" value="option1">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Stripe</span>
</label>
</div>
</div>
<div class="text-right">
<button type="button" href="#step3" data-toggle="tab" role="tab"
class="btn btn-outline-primary prev-step">
Go back to step 2
</button>
<button type="button" data-nexttab="#step3" href="#step3"
class="btn btn-primary btn ml-2 next-step">
Go to step 3
</button>
</div>
</form>
</div>
// ajax in payment.blade.php
$('#goToStep2').on('click', function (event) {
event.preventDefault();
var custom_form = $("#" + page_form_id);
$.ajax({
method: "POST",
url: '{{ route('products.storeUserInfo',compact('id','slug') ) }}',
data: custom_form.serialize(),
datatype: 'json',
success: function (data, textStatus, jqXHR) {
setTimeout(function () {
}, 3000);
},
error: function (data) {
console.log(data);
var errors = data.responseJSON;
var errorsHtml = '';
$.each(errors['errors'], function (index, value) {
errorsHtml += '<ul class="list-group"><li class="list-group-item alert alert-danger">' + value + '</li></ul>';
});
$('#response').show().html(errorsHtml);
}
});
});
});
Use Validator facade class in your PaymentController
use Validator;
class PaymentController extends Controller
{
public function storeUserInfo(Request $request, $id, $slug = null){
$validator = Validator::make($request->all(),[
'buyer_name' => 'required|max:255|string',
'buyer_surname' => 'required|max:255|string',
'buyer_email' => 'required|max:255|string',
'name_invoice' => 'required|max:255|string',
'country_invoice' => 'required|max:255|string',
]);
if ($validator->fails()) {
if($request->ajax())
{
return response('test');
}
$this->throwValidationException(
$request, $validator
);
}
}
}

Resources