Ajax script to update record does not work, Laravel - ajax

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>

Related

Laravel - search submit is not redirecting to the next blade

In my Laravel-5.8, I am using the index as the search page:
public function index()
{
$search = '';
if (request('search'))
{
$search = request('search');
return redirect()->route('client', [$search]);
}
return view('index', ['search' => $search]);
}
public function client($clientid)
{
$myparam = $clientid;
$client = new Client();
$res = $client->request('GET','https://example/{$myparam}', [
'query' => ['key' => 'jkkffd091']
])->getBody();
$geoLocation = json_decode($res->getContents(), true);
return view('client', [
'geoLocation' => $geoLocation
]);
}
Here is my index blade:
<form method="GET" action="{{ route('index', ['search' => $search]) }}">
<div class="field">
<label class="label blog-sidebar-label" for="search">
<input class="search-field" type="search" name="search" id="search" placeholder="client id..." value="{{ $search }}">
</label>
</div>
</form>
I have this route:
Route::get('/', [HomeController::class, 'index'])->name('index');
Route::get('client/{search}', [HomeController::class, 'client'])->name('client');
What I want to achieve is that when the search button for index is submitted with the clientid in the text input field, it should take the clientid as parameter and pass it to client controller. Also redirect to client blade.Then when nothing is in the text input field, it should indicate.
But it is not redirecting. How do I achieve this?
Thanks
Probably you want to submit without a submit button. Then you can submit with JS :
<form id="submitForm" method="GET" action="{{ route('index', ['search' => $search]) }}">
<div class="field">
<label class="label blog-sidebar-label" for="search">
<input class="search-field" type="search" name="search" id="search" placeholder="client id..." value="{{ $search }}">
</label>
</div>
</form>
<!-- JS code below -->
<script>
document.getElementById("search").onchange = function() {myFunction()};
function myFunction() {
document.getElementById("submitForm").submit();
}
</script>

Laravel 8 prevent logout after user password change?

I have an admin panel and I am currently working on the change password module. I have done the code for change password but for some reason the session is destroyed and user is logged out after changing the password. How to prevent the auto logout from happening. Please help me.
HTML
<form id="changepasswordform">
<input type="hidden" name='_token' value="{{ csrf_token() }}">
<div class="form-group">
<div class="row">
<div class="col-md-2">
<label>Password</label>
</div>
<div class="col-md-10">
<div class="custom_error_msg password_error"></div>
<input type="password" name="password" class="form-control password">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2">
<label>Confirm Password</label>
</div>
<div class="col-md-10">
<div class="custom_error_msg confirm_password_error"></div>
<input type="password" name="confirm_password" class="form-control confirm_password">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<button class="btn btn-success float-right"><i class="far fa-save"></i> Save</button>
</div>
</div>
</div>
</form>
Controller
public function ChangePasswordProcess(Request $request){
/*User::find(auth()->user()->id)
->update([
'password'=> Hash::make($request->password)
]);*/
$userId = Auth::User()->id;
$user = User::find($userId);
$user->password = Hash::make($request->password);
$user->save();
return response()->json(['status' => 'success']);
}
Javascript
<script>
$(document).ready(function(){
$(".dropify").dropify();
$("#changepasswordform").submit(function(e){
e.preventDefault();
var status=false;
if($(".password").val()==""){
$(".password_error").html("Field is mandatory");
$(".password_error").show();
status=false;
} else {
$(".password_error").hide();
status=true;
}
if($(".confirm_password").val()==""){
$(".confirm_password_error").html("Field is mandatory");
$(".confirm_password_error").show();
status=false;
} else {
$(".confirm_password_error").hide();
status=true;
}
if($(".password").val()!=="" && $(".confirm_password").val()!==""){
if($(".password").val() !== $(".confirm_password").val()){
$(".confirm_password_error").html("Passwords don't match");
$(".confirm_password_error").show();
status=false;
} else {
$(".confirm_password_error").hide();
status=true;
}
}
if(status==true){
var formdata = new FormData(document.getElementById('changepasswordform'));
$.ajax({
url: "{{ route('admin.change_password_process') }}",
type: "post",
async: false,
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function (res) {
if (res.status == 'success') {
Swal.fire({
icon: 'success',
title: 'Success',
text: 'Password updated successfully',
confirmButtonClass: 'btn btn-primary',
buttonsStyling: false,
}).then(function (result) {
window.location.reload();
});
}
}
});
}
});
});
</script>
On the method ChangePasswordProcess in the controller, you have to re-authenticate the user which his password changed
public function ChangePasswordProcess(Request $request){
/*User::find(auth()->user()->id)
->update([
'password'=> Hash::make($request->password)
]);*/
$userId = Auth::User()->id;
$user = User::find($userId);
$user->password = Hash::make($request->password);
$user->save();
Auth::login($user);
return response()->json(['status' => 'success']);
}
When the password_hash of the session is different from the current auth()->user() the laravel will automatically logout the user. This is done on this middleware:
vendor/laravel/framework/src/Illuminate/Session/Middleware/AuthenticateSession.php
If you update the password_hash on the session with the new hash password the user will be not logout.
session()->put([
'password_hash_' . auth()->getDefaultDriver() => $user->getAuthPassword()
]);
Example:
session()->put([
'password_hash_web' => "$2y$10$...hashpasswordstoredondatabase"
]);

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

I want to send email for more than one user to Mailtrap

I tried to send an email to a user and arrived at Miltrap
Now I put all the users on my system (table users in database) and introduced them to checkboxs and I want to send one email to more than one user or to all users and I did not see the result on the mailtrap
This is the code
MailboxController.php
public function form(Request $request)
{
$users = User::where('id', '!=', auth()->user()->id)->get();
return view('MailBox.form',compact('users'));
}
public function contact(Request $request)
{
//$emails = [];
$this->validate($request, [
'email' => 'required|email',
'subject' => 'min:3',
'message' => 'min:10']);
$data = array(
'email' => $request->email,
'subject' => $request->subject,
'bodyMessage' => $request->message
);
Mail::send('MailBox.contact', $data, function($message) use ($data){
$message->from('info#dev-any.com');
$message->to($data['email']);
$message->subject($data['subject']);
});
Session::flash('success', 'Your Email was Sent!');
return redirect('/dashboard/mailbox');
}
Web.php
Route::get('/mailbox', 'MailboxController#form')->name('mailbox.form');
Route::post('/mailbox/contact', 'MailboxController#contact')->name('contact');
form.blade.php
<form action="{{ route('contact') }}" method="POST">
{{ csrf_field() }}
<div class='form-group col-md-6'><strong>Select User :</strong><br>
<input type="checkbox" id = "chckHead" name="chk_all" value="" onchange="checkall()" id='allcb' /><strong> Check All </strong> </br>
#foreach ($users as $user)
<tr>
<td><input type="checkbox" class = "chcktbl" onchange="check()" name="email" id="email" value={{ $user->id }}></td>
<td>{{ $user->name }}</td></br>
</tr>
#endforeach
</div>
<div class="form-group col-md-6">
<label name="subject">Subject:</label>
<input id="subject" name="subject" class="form-control">
</div>
<div class="form-group col-md-6">
<label name="message">Message:</label>
<textarea id="message" name="message" class="form-control">Type your message here...</textarea>
</div>
<input type="submit" value="Send Message" class="btn btn-success col-md-6">
</form>
</div>
</div>
<script type="text/javascript">
$('.chcktbl').click(function () {
var length = $('.chcktbl:checked').length;
if (length > 3) {
// alert(length);
$('.chcktbl:not(:checked)').attr('enable', true);
}
else {
$('.chcktbl:not(:checked)').attr('enable', false);
}
});
</script>
<script type="text/javascript">
$('#chckHead').click(function () {
if (this.checked == false) {
$('.chcktbl:checked').attr('checked', false);
}
else {
$('.chcktbl:not(:checked)').attr('checked', true);
}
});
$('#chckHead').click(function () {
});
Simply change the email checkbox, and modify the validation
<input type="checkbox" class="chcktbl" onchange="check()" name="email[]" id="email" value={{ $user->id }}>

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