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

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() }}"

Related

Cant send data ajax in laravel

I m trying to login this from with ajax but ajax dont work :( can you help me
My Controller
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'password' => 'required',
'email' => 'required|email',
]);
if ($validator->passes()) {
if (auth()->attempt(array('email' => $request->input('email'),
'password' => $request->input('password')),true))
{
return response()->json(["status" => true]);
}
return response()->json(['error'=>false]);
}
return response()->json(['error'=>$validator->errors()]);
}
my View
<div id="giris-yap" class="ekran" x-show="tab === 'giris-yap'">
<form action="javascript:void(0)" id="loginform" action="{{ route('giris') }}" method="post">
#csrf
<div class="form-group">
<input type="email" name="email" id="email" placeholder="E-Posta"
#error('email') style="border-color:red" #enderror>
<label class="lab" for="email">E-Posta</label>
<small style="color: red;" id="email" class="text-danger error-text email_err hata"></small>
</div>
<div class="password-input form-group">
<input type="password" name="password" id="password" placeholder="Şifre"
#error('password') style="border-color:red" #enderror>
<label class="lab" for="password">Şifre</label>
<span toggle="#password" class="fa fa-fw fa-eye field-icon toggle-password"></span>
<small style="color: red;" id="password" class="text-danger error-text password_err hata"></small>
</div>
<div class="remember col-2 gap-10">
<div class="form-check">
<label><input type="checkbox" name="remember"> Beni Hatırla</label>
</div>
<span class="password-request">
Şifremi Unuttum
</span>
</div>
<small id="mydiv" style="color: red; margin-top: 5px; margin-bottom: 10px; display: none " class="text-danger password_err">Lütfen Eposta ve Şifrenizi Kontrol edin.</small>
<button type="submit" class="btn loginBtn">Giriş Yap</button>
</form>
my ajax
<script>
//login ajax
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
url: "{{ route('giris') }}",
type:'POST',
data:{'_token' : '{{ csrf_token() }}', email:email, password:password},
success: function(data) {
printMsg(data)
if(data.status === true)
{
console.log(data.status)
window.location.href = '/';
}
if(data.error === true){
console.log(data.error)
$('#mydiv').show()
}
},
});
});
function printMsg (msg) {
if($.isEmptyObject(msg.error)){
}else{
$.each( msg.error, function( key, value ) {
$('.'+key+'_err').text(value);
});
}
}
});
</script>
do not pass route just pass in form open tag #csrf and on button Sign In and then
in js script like this. function login(){ $.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
$.ajax({ type : 'POST', url: '{{route('login.check')}}', data : data,success : function(response) {console.log(response); if(response == 1) {
window.location.replace('{{route('test.index')}}'); }else if(response == 3)
{ $("#err").hide().html("Username or Password Incorrect. PleaseCheck").fadeIn('slow'); } } });}

Is there is a way to keep my modal open in Laravel after submit and save the values to db?

I am uploading a file in Laravel 8 with having one bootstrap modal which works dynamically . everything is working fine but I want to improve my output more:
1) Update one of my forms through a modal without refreshing the page?
2) keep the modal open if the validation fails and print the errors to modal instead of my redirect page?
I will appreciate your time helping me.
my form for updating the file
<form action="{{ route('storefile' , $requisition->id) }}" method="POST"
enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="form-group row">
<div class="col-sm-12">
<label for="title"> Account Status: </label>
<select class="form-control" name="acc_status">
<option value="0" {{ $requisition->acc_status == 0 ? 'selected' : '' }}> Inactive
</option>
<option value="1" {{ $requisition->acc_status == 1 ? 'selected' : '' }}> Active
</option>
</select>
</div>
<div class="col-sm-12 pt-4">
<label for="title"> Account document File: </label>
<div>
#if (!empty($requisition->acc_document))
<label class="badge-success">
{{ $requisition->acc_document }}
</label>
#else
<label class="badge-danger">
Nothing uploaded </label>
#endif
</div>
<input type="file" name="acc_document" class="form-control" id="acc_document" />
</div>
</div>
<div class="card-footer">
<div class="row">
<div class="col-md-6 text-left">
<input type="submit" value="Upload document" class="btn btn-primary">
</div>
</div>
</div>
</div>
</form>
my controller and route
public function uploadFile($id) {
$requisition = Requisition::find($id);
return view('requisition.createFile' , compact('requisition'));
}
public function storeFile(Request $request , $id) {
$request->validate([
'acc_status' => 'required',
'acc_document' => 'required|mimes:doc,docx,pdf,txt,zip|max:2000',
]);
$requisition = Requisition::find($id);
$requisition->acc_status = $request->get('acc_status');
$FileName = uniqid() .$request->file('acc_document')->getClientOriginalName();
$path = $request->file('acc_document')->storeAs('uploads', $FileName , 'public');
$requisition->acc_document = '/storage/' . $path;
}
$requisition->save();
//$requisition->update($request->all());
return back()
->with('success', 'Your file has been uploaded successfully.');
}
Route::get('upload/{id}', [RequisitionController::class, 'uploadFile'])->name('upload');
Route::put('requisition/{id}/files', [RequisitionController::class, 'storeFile'])->name('storefile');
and last part my modal and ajax in my index page to upload the file and popup will open
<div class="col-md-6">
<a style="display:inline-block; text-decoration:none; margin-right:10px;"
class="text-secondary" data-toggle="modal" id="mediumButton"
data-target="#mediumModal" title="upload"
data-attr="{{ route('upload' , $requisition->id) }}">
<i class="fas fa-upload"></i>
</a>
</div>
<script>
// display a modal (medium modal)
$(document).on('click', '#mediumButton', function(event) {
event.preventDefault();
let href = $(this).attr('data-attr');
$.ajax({
url: href,
beforeSend: function() {
$('#loader').show();
},
// return the result
success: function(result) {
// #if (count($errors) > 0) #endif
$('#mediumModal').modal("show");
$('#mediumBody').html(result).show();
$("#date-picker").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd'
});
} ,
complete: function() {
$('#loader').hide();
},
error: function(jqXHR, testStatus, error) {
console.log(error);
alert("Page " + href + " cannot open. Error:" + error);
$('#loader').hide();
},
timeout: 8000
});
});
</script>
<!-- medium modal -->
<div class="modal fade" id="mediumModal" tabindex="-1" role="dialog" aria-labelledby="mediumModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-body" id="mediumBody">
<form id="modal-form" method="get">
<div>
<!-- the result of displayed apply here -->
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
what I want to implement looks like enter image description here
There are several ways to do this kind of thing. One way to do it, is to do something like this:
Html:
<div class="modal" id="the-modal">
<form action="{{ $theAction }}" method="POST" id="the-form">
<input type="text" name="input-name" id="the-input">
<button type="submit">
</form>
<p id="the-text"></p>
</div>
In your Controller you will return an error or an 200 response, if everything is ok.
public function theAction(Request $request , $id) {
//Do stuff
if (!$error) {
return response("OK"); //This will return a 200 response
} else {
return response("An error happened", 500); //This will return a 500 error
}
}
Then, in your JS, you'll intercept form submission and then, you're going to be able to separate errors from ok messages:
<script>
$("#the-form").on('submit', function(event) {
event.preventDefault();
let theInput = $("#the-input");
$.ajax({
url: theUrl,
data: {
the-input: theInput
}
// 200 response
success: function(result) {
$("#the-text").empty();
$("#the-text").append(result.repsonse);
} ,
error: function(jqXHR, testStatus, error) {
$("#the-text").empty();
$("#the-text").append(error.response);
}
});
});
</script>
If you want to do all this stuff inside a modal, the concept is just the same: You intercept form submission, send to controller, return separate responses for errors and 200 responses, and then update manually the inputs/texts.
I did't test the code, but the concept should work.

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

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

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