Ajax post request- Unresolvable dependency resolving and error 500 - laravel

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
);
}
}
}

Related

Ajax script to update record does not work, Laravel

I wrote a small script that updates the information on the page when editing. Everything basically works as it should, but I just can’t update the image. I don’t understand what the matter is. Without a script, with a page reload, everything works as it should.
Ajax script
<script type="text/javascript">
$("document").ready(function() {
$("#editPostButton{{$post->id}}").click(function() {
var formData = $("#EditPostForm{{$post->id}}").serialize();
$.ajax({
url: "{{route('editPost', ['id' => $user->id, 'postId' => $post->id])}}",
type: "POST",
data: formData,
success: function(data) {
$("#textpostdata{{$post->id}}").html($(data).find("#textpostdata{{$post->id}}").html());
$("#closeButton{{$post->id}}").click();
}
});
});
});
</script>
My Controller
public function editPost(Request $request, $id, $postId) {
$validator = $this->validate($request,[
'title' => 'max:100',
'message' => 'max:5000',
'img' => 'mimes:jpeg,png,gif,jpg|max:5000',
'videoPost' => 'max:100'
]);
if($validator) {
$user = User::find($id);
if(!$user && $user != Auth::user()->id) {
return abort(404);
}
$post = Profile::find($postId);
if(!$post) {
return abort(404);
}
$post->user_id = Auth::user()->id;
$post->title = $request->title;
$post->message = $request->message;
$post->videoPost = str_replace('watch?v=', 'embed/', $request->videoPost);
if($request->file('img')) {
$path = Storage::putFile('public/'.Auth::user()->id.'/post', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;
}
$post->update();
return redirect()->back();
}
}
And update form
<form action="{{route('editPost', ['id' => $user->id, 'postId' => $post->id])}}" method="post" enctype="multipart/form-data" id="EditPostForm{{$post->id}}" name="postForm">
#csrf #method('PATCH')
<div class="form-group">
<textarea maxlength="100" name="title" class="form-control" rows="1">{{$post->title}}</textarea>
</div>
<div class="form-group">
<textarea id="message" maxlength="5000" name="message" class="form-control" rows="10">{{$post->message}}</textarea>
</div>
<div class="form-group">
<textarea maxlength="100" class="form-control mt-1" id="videoPost" name="videoPost" cols="100" rows="1">{{$post->videoPost}}</textarea>
</div>
<h6>Current image</h6>
<img src="{{$post->img}}" class="img-fluid mb-2" width="230">
<div class="form-group">
<input type="file" id="img" name="img" accept="image/*">
</div>
<button type="button" class="btn btn-sm btn-primary" id="editPostButton{{$post->id}}">Edit</button>
</form>

Ajax not displaying error message itself, box only

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>')

Laravel get a empty variable from axios.post from vuie.js module

partners from stackOverflow im making a module using laravel like backend, and vue.js by frontend, i have a form to create a new entity, but the controller dont get the values¡, plz help me to find the error. I'm going to share the code.
the routes.web
//new event from API
Route::resource('/api/events', 'EventsController', ['except' => 'show','create']);
The function in the controller EventsController.php
<?php
namespace soColfecar\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use soColfecar\Http\Requests\CreateEventRequest;
use soColfecar\Http\Requests\UpdateEventRequest;
use soColfecar\User;
use soColfecar\Change;
use soColfecar\Event;
use soColfecar\Event_type;
use Auth;
public function store(Request $request)
{
$exploded = explode(',', $request->banner);
$decoded = base64_decode($exploded[1]);
if(str_contains($exploded[0],'jpeg'))
$extension = 'jpg';
else
$extension = 'png';
$fileName = str_random().'.'.$extension;
$path = public_path().'/storage/banner/'.$fileName;
file_put_contents($path, $decoded);
Event::create([
'event' => strtoupper($request['event']),
'id_event_type' => $request['id_event_type'],
'date_init' => $request['date_init'],
'date_end' => $request['date_end'],
//'banner' => $fileName,
]);
Change::create([
'description' => 'Creo el de evento:'.$request['event'].' correctamente.',
'id_item' => 10,
'id_user' => Auth::user()->id,
]);
return redirect()->route('events.index')
->with('info', 'evento guardado con exito');
}
the method:
<form method="POST" v-on:submit.prevent="storeNewEvent">
<div class="form-group m-form__group">
<label for="eventTypeInput">Tipo de vento:</label>
<v-select :options="eventTypes" v-model="newEvent.id_event_type" id="eventTypeInput">
<template slot="option" slot-scope="option">
{{ option.label }}
</template>
</v-select>
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.city_id }}</span>
</div>
<div class="form-group m-form__group">
<label for="inputHotelName">Nombre del Evento</label>
<input type="text" class="form-control" name="inputHotelName" v-model="newEvent.event" placeholder="Nombre del Evento">
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.hotel_name }}</span>
</div>
<div class="form-group m-form__group">
<label for="date_init_imput">Fecha de inicio</label>
<input class="form-control" type="date" v-model="newEvent.date_init" value="" id="date_init_imput">
</div>
<div class="form-group m-form__group">
<label for="date_end_imput">Fecha de finalizacion</label>
<input class="form-control" type="date" v-model="newEvent.date_end" value="" id="date_end_imput">
</div>
<div class="form-group m-form__group">
<label for="customFile">Banner del Evento</label>
<div></div>
<div class="custom-file">
<input type="file" class="custom-file-input" #change="getLogo" id="customFile">
<label class="custom-file-label" for="customFile">Seleccione archivo</label>
<span v-for="error in errors" class="text-danger" :key="error.error">{{ error.logo }}</span>
</div>
</div>
<hr>
<button type="submit" class="btn btn-info waves-effect text-left">Guardar</button>
</form>
data() {
return {
changes: [],
eventTypes: [],
errors: [],
newEvent: {
event: '',
id_event_type: '',
date_init: '',
date_end: '',
banner: '',
}
}
},
storeNewEvent : function() {
var url = 'api/events';
var newEvent = this.newEvent
axios.post(url, {event: this.newEvent}).then(response => {
this.newEvent = {}
this.errors = [];
$('#new_event_modal').modal('hide');
$('.modal-backdrop').remove();
toastr.success('Se ha creado el evento con exito!')
}).catch(error => {
this.errors = error.response.data
});
},
And the error
"Too few arguments to function soColfecar\Http\Controllers\EventsController::store(), 0 passed and exactly 1 expected"
enter image description here
You need to type hint the $request so Laravel knows to fill it in ("dependency injection").
At the top of your file:
use Illuminate\Http\Request;
Then, for your function:
public function store(Request $request) {

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 jquery form submission codeigniter doesn't work

i want to create form submit by using ajax jquery,but everytime i press submit, the form is always executed directly to controller without passing ajax call.
is there anything wrong with my code?
controller:
public function simpanSaran(){
$this->form_validation->set_rules('nama', 'Nama', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('sub', 'Subjek', 'required');
$this->form_validation->set_rules('isi', 'Isi', 'required');
if ($this->form_validation->run() == FALSE) {
$this->content("user/hal_saran");
}
else {
$insert = array(
'nama' => $this->input->post('nama'),
'email' => $this->input->post('email'),
'subjek' => $this->input->post('sub'),
'komentar' => $this->input->post('isi'),
);
$this->db->insert('guest',$insert);
}
}
my view,with ajax jquery:
<script>
$(document).ready(function() {
$('#myForm').submit(function() {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function() {
$('#result').slideDown();
}
}
})
return false;
});
$('.close').click(function(){
$('#result').slideUp();
});
});
</script>
<div class=" span9">
<div class="span9" id="result" style="display:none;height:80px;">
<div class="notices" >
<div class="bg-color-green" style="height:60px;">
<div class="notice-header fg-color-white">Terima Kasih!</div>
<div class="notice-text">Anda telah Memberikan Kritik dan Saran pada Kami.</div>
</div>
</div>
</div>
<div id="hid" style="display:none;"></div>
<?php
$attr = array('id' => 'myForm');
echo (form_open('lowongan/simpanSaran',$attr)) ?>
<div class="input-control text span3" style="height:40px;">
<input type="text" placeholder="Nama" name="nama" required/>
<button class="btn-clear"></button>
</div>
<div class="input-control text span3" style="height:40px;">
<input type="text" placeholder="Email" name="email" required/>
<button class="btn-clear"></button>
</div>
<div class="input-control text span3" style="height:40px;">
<input type="text" placeholder="Subjek" name="sub" required/>
<button class="btn-clear"></button>
</div>
<div class="input-control textarea span9" >
<textarea placeholder="Komentar" name="isi" style="height:200px;" required></textarea>
<button type="submit" class="fg-color-white bg-color-purple" style="margin-top:20px;"><i class="icon-comments-5"></i> Kirim</button>
<p>*Saran atau kritik akan di-reply melalui email</p>
</div>
<?php echo(form_close())?>
</div>
Just a small change :
$('#myForm').submit(function(e) {
e.preventDefault();

Resources