Laravel AJAX getting all records in one JSON request - ajax

i am trying to edit record in my database using ajax, my code is working fine, but i have to mention each column by name, how i can get same result without typing all columns name.
Edit Controller: i am using columns name [efirst,esecond etc] i want to pass everything from database without mentioning name
public function edit($id)
{
$teacher = Teacher::find($id);
return response()->json([
'status' => 'success',
'id' => $teacher->id,
'efirst' => $teacher->efirst,
'esecond' => $teacher->esecond,
]);
}
Edit.js:
jQuery(document).ready(function($) {
$(".table-container").on("click touchstart", ".edit-btn", function () {
$.ajax({
type: "GET",
url: "lists/" + $(this).attr("value") + "/edit",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
beforeSend: function() {
$('#esecond-not-found').remove();
},
success: function (data) {
$("#update-id").val(data['id']);
$("#update-efirst").val(data['efirst']);
$("#update-esecond").val(data['esecond']);
$('#update-form').show();
},
});
});
});
View:
<form method="post" id="update-form">
{{ method_field('PATCH') }}
<input type="hidden" name="id" id="update-id">
<div class="">
<label for="efirst">efirst</label>
<input type="text" class="form-control" name="efirst" id="update-efirst">
<label for="esecond">esecond body</label>
<textarea name="esecond" class="form-control" id="update-esecond" rows="6"></textarea>
</div>
<div class="">
<button type="submit" class="btn btn-success" id="update-submit">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>

A teacher object can be passed instead of writing every table field
return response()->json([ 'status' => 'success', 'teacher' => $teacher ]);
So in order for this code to work the id of the form needs to match the name of the column
let teacher = Object.entries(data.teacher);
teacher.forEach(item => { $("#"+item[0]).val(item[1]); });
Let's say we have four inputs
<input id="data1" type="text" class="form-control">
<input id="data2" type="text" class="form-control">
<input id="data3" type="text" class="form-control">
<input id="data4" type="text" class="form-control">
and you do this
success: function (data) {
let teacher = Object.entries(data.teacher);
teacher.forEach(item => {
console.log(item)
$("#"+item[0]).val(item[1]);
});
}
the console log gives the following
(2) ["data1", "test1"]
(2) ["data2", "test2"]
(2) ["data3", "test3"]
(2) ["data4", "test4"]
you get an array of arrays that you can loop where the index position 0 is your input id and the index position 1 is your value.

Related

422 Unprocessable Entity Error. I tried upload Excel file to import data but it is not working

This is my code, i use vuejs and laravel. The function I am doing is both saving the Course and also importing the Excel file to get the data in the file. But when saving the Course is normal, but when it comes to running the validate excel file line, the error is not received. Even though I gave it a name and console.log came out. Can you help me fix it? Thank you so much.
Component - template tag
<form #submit.prevent="store()" #keydown="form.onKeydown($event)">
<div class="form-group">
<label class="form-label">Courses</label>
<select class="form-control" name="education_program_course" v-model="form.education_program_course">
<option value="" disabled selected="">Select option</option>
<option value="" disabled>-------</option>
<option v-for="course in courses" :key="course.course_code" :value="course.course_code">{{ course.course_name }}</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Excel File</label>
<input type="file" class="form-control" id="file_data" name="file_data" ref="fileupload" #change="onFileChange">
</div>
<div class="card-footer text-right">
<button :disabled="form.busy" class="btn btn-success btn-lg mt-1" type="submit">Save</button>
</div>
</form>
Component - script tag
export default: {
data() {
return {
file_data: "",
form: new Form({
education_program_course
}),
},
methods: {
onFileChange(e) {
this.file_data = e.target.files[0];
},
store() {
this.form.busy = true;
let formData = new FormData();
formData.append('file_data', this.file_data);
this.form.post('../../api/admin/program/education', formData, {
headers: { 'content-type': 'multipart/form-data' }
})
.then(res => {
if(this.form.successful){
this.$snotify.success('Sucessful!');
this.form.clear();
this.form.reset();
}
})
.catch(err => {
this.$snotify.error(err.response.data.errors.file_data[0]);
});
},
}
}
}
Controller
$data = $request->validate([
'education_program_course' => ['required'],
'file_data' => ['required', 'file', 'mimes:xls,xlsx']
]);
$program = new EducationProgram();
$program->education_program_course = $data['education_program_course'];
$path = $request->file($data['file_data'])->getRealPath();
Excel::import(new ProgramDetailImport, $path);
You should append 'education_program_course' on your formdata.
formData.append('education_program_course', this.form.education_program_course);
I have solved this problem. Change change at script tag -> store()
from:
let formData = new FormData();
formData.append('file_data', this.file_data);
to:
if(document.getElementById("file_data").files[0]){
this.form.file_data = document.getElementById("file_data").files[0];
}
Adding file_date in form: new Form and remove formData in this.form.post.

How to store logged In user_id in vuejs

I am totally new in vew js and I am trying to store data in db and I am storing successfully when I entered the values manually but I want to store the user_id of logged in user.
Here is my vue
<form #submit.prevent>
<div class="form-group">
<label for="event_name">Name</label>
<input type="text" id="event_name" class="form-control" v-model="newEvent.event_name">
</div>
<div class="form-group">
<label for="user_id">Use Id</label>
<input type="text" id="user_id" class="form-control" v-model="newEvent.user_id">
</div>
<div class="col-md-6 mb-4" v-if="addingMode">
<button class="btn btn-sm btn-primary" #click="addNewEvent">Save Event</button>
</div>
</form>
export default {
components: {
Fullcalendar
},
data() {
return {
calendarPlugins: [dayGridPlugin, interactionPlugin],
events: "",
newEvent: {
event_name: "",
user_id: ""
},
addingMode: true,
indexToUpdate: ""
};
},
created() {
this.getEvents();
},
methods: {
addNewEvent() {
axios
.post("/fullcalendar/api/calendar", {
...this.newEvent
})
.then(data => {
this.getEvents(); // update our list of events
this.resetForm(); // clear newEvent properties (e.g. title and user_id)
})
.catch(err =>
console.log("Unable to add new event!", err.response.data)
);
},
Here, when I enter values in Name and User Id manually then it stores in db but in user id I want to get the logged in user_id.
I have tried something like this but it didn't work,
<input type="text" id="user_id" class="form-control" v-model="newEvent.{{ Auth::user()->id; }}">
Please help me out, Thanks in advance.
EventResource.php
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->event_name,
'user' => $this->user_id,
];
}
you can send data with your axios request like this:
axios.post('/url', {
user_id: {{ Auth::user()->id }}
}, {
headers: headers
})
and in your controller you can access it with:$request->user_id;

Laravel 5.5 Multilanguage validation

Please tell me, I ran into a problem. There is a site based on Laravel 5.5. The site has a multilanguage (two languages en/ru). For multilanguage I'm using:
dimsav/laravel-translatable
mcamara/laravel-localization
Added language files to the directory resources/lang/ru. The problem is the validation of the form. The site has a feedback form in the modal window, working with ajax (sending and validating), error messages are displayed only in the default language, the default language is en. I tried to send data from the form without the help of ajax, everything works well, messages are displayed in both Russian and English.
reoutes/web.php
Route::group(['prefix' => LaravelLocalization::setLocale()], function(){
Route::get('/', 'PagesController#getProfile')->name('profile');
Route::get('/skills', 'PagesController#getSkills')->name('skills');
Route::get('/portfolio', 'PagesController#getPortfolio')->name('portfolio');
Route::get('/resume', 'PagesController#getResume')->name('resume');
Route::post('/contact', 'PagesController#contact');
});
controller
public function contact(Request $request){
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'message' => 'required'
]);
if ($validator->passes()) {
Mail::to('mycontactform#mail.ru')->send(new Contact($request));
return response()->json(['success'=>'Message sent successfully!']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
js
$(document).ready(function() {
$(".btn-send-message").click(function(e){
e.preventDefault();
$.ajax({
url: "/contact",
type:'POST',
data: $('#contact-form').serialize(),
beforeSend: function() {
$("#loading").show();
$(".fa-paper-plane").hide();
},
complete: function() {
$("#loading").hide();
$(".fa-paper-plane").show();
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg();
}else{
printErrorMsg(data.error);
}
}
});
});
var $success_msg = $(".print-success-msg");
var $error_msg = $(".print-error-msg");
function printSuccessMsg() {
$success_msg.html('Message sent successfully!');
$success_msg.css('display','block');
$success_msg.delay(5000).fadeOut(350);
$('#contact-form')[0].reset();
}
function printErrorMsg (msg) {
$error_msg.find("ul").html('');
$error_msg.css('display','block');
$.each( msg, function( key, value ) {
$error_msg.find("ul").append('<li>'+value+'</li>');
});
$error_msg.delay(5000).fadeOut(350);
}
});
form
<div class="modal-body col-md-8 offset-md-2">
<div class="alert alert-danger print-error-msg" style="display:none">
<strong>Errors:</strong>
<ul></ul>
</div>
<div class="alert alert-success print-success-msg" style="display:none"></div>
{!! Form::open(['id'=>'contact-form']) !!}
<div class="form-group">
<input class="form-control" type="text" name="name" id="name" placeholder="Your Name">
</div>
<div class="form-group">
<input class="form-control" type="email" name="email" id="email" placeholder="Your Email">
</div>
<div class="form-group">
<textarea class="form-control" name="message" id="message" rows="3"></textarea>
</div>
<button type="button" class="btn btn-success btn-send-message"><i class="fas fa-paper-plane"></i>
Send Message <span id="loading" style="display: none;"><img class="loader"
src="{{ asset('images/loading.gif') }}"></span>
</button>
{!! Form::close() !!}
</div>
Use LaravelLocalization::getLocalizedURL() which returns an URL adapted to $locale.
So your ajax code will be.
$.ajax({
url: "{{ LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(),'/contact') }}",
type:'POST',
data: $('#contact-form').serialize(),
beforeSend: function() {
$("#loading").show();
$(".fa-paper-plane").hide();
},
complete: function() {
$("#loading").hide();
$(".fa-paper-plane").show();
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg();
}else{
printErrorMsg(data.error);
}
}
});
When you return your response try to use this helper __('translated_string')
To use this helper, you have to create some translate.php file in those folders resources/lang/en and resources/lang/en
For example:
File resources/lang/en/translate.php should contain this array
return [
'success_message' => 'Message sent successfully!',
];
File:
resources/lang/ru/translate.php should contain this array
return [
'success_message' => 'Сообщение успешно отправлено!',
];
For example:
return response()->json(['success'=> __('translate.success_message') ]);
To get some translated string, use dot notation for this helper;
Laravel localization helper

variable is not found inside ajax

<div class="modal-body">
<form>
<div class="form-group">
<label for="email" class="col-form-label">Email address:</label>
<input type="email" class="form-control" id="signUpEmail" name="email">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Password:</label>
<input type="password" class="form-control" id="signUpPassword" name="password" onchange="check_pass()">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Confirm Password:</label>
<input type="password" class="form-control" id="signUpConPassword" name="password" onchange="check_pass()">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="signUpSubmit" disabled="true" >Sign Up</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function check_pass()
{
//alert(document.getElementById('signUpPassword').value);
if (document.getElementById('signUpPassword').value ==
document.getElementById('signUpConPassword').value) {
document.getElementById('signUpSubmit').disabled = false;
}
else
{
document.getElementById('signUpSubmit').disabled = true;
}
}
$('#signUpSubmit').click(function()
{
//alert("signup completed");
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: $email,
password: $password
},
success: function() {
alert('Email Sent');
}
});
});
</script>
This code snippet shows ReferenceError: $email is not defined when I click on the signupSubmit button although I defined the variable inside the function.
I also try
var email=document.getElementById('signUpEmail').value;
var password = document.getElementById('signUpPassword').value;
but, same error. I guess there is a problem in variable declaration. What is the correct form of variable declaration inside the function?
You have to change the $email and $password to email ,password
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: email,
password: password
},
success: function() {
alert('Email Sent');
}
});
Remove the $
data: {
email: $email,
password: $password
},
The data being passed has two properties - "email" and "password", the values of the properties are stored in the variables email and password.
Your code should look like this:
/* Remove these two lines */
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
...
data: {
"email": $("#signUpEmail").val(),
"password": $("#signUpPassword").val()
}
The $ is the jQuery function call, and the "#signUpEmail" is the selector for the element with an id of "signUpEmail". The val() method will return the value of the input.
document.getElementById("something").value
is the same as
$("#something").val()
If you're using jQuery for the Ajax, you might as well use it to get the values.

Laravel AJAX Form 405 Error

I'm receiving this error when attempting to submit via AJAX. When not using AJAX, the form submits just fine to it's specified url. I've read this error can happen because the form is trying to submit in the browser along with the AJAX request. I've tried using onsubmit="event.preventDefault()".
ROUTE:
Route::post('/post/{id}', [
'uses' => '\App\Http\Controllers\PostController#postMessage',
'as' => 'post.message',
'middleware' => ['auth'],
]);
FORM:
<form id="post" role="form" action="{{ route('post.message', ['id' => $user->id]) }}" onsubmit="event.preventDefault()">
<div class="feed-post form-group{{ $errors->has('post') ? ' has-error' : ''}}">
<textarea class="form-control feed-post-input" rows="2" id="postbody" name="post" placeholder="What's up?"></textarea>
<div class="btn-bar">
<!-- <button type="button" class="btn btn-default btn-img btn-post" title="Attach an image"><span class="glyphicon glyphicon-picture"></span></button> -->
<!-- <input type="file" id="img-upload" style="display:none"/> -->
<button class="btn btn-default btn-post" title="Post your message"><span class="glyphicon glyphicon-ok"></span></button>
</div>
#if ($errors->has('post'))
<span class="help-block">{{ $errors->first('post') }}</span>
#endif
</div>
<input type="hidden" name="_token" value="{{ CSRF_token() }}">
</form>
CONTROLLER:
public function postMessage(Request $request, $id)
{
$this->validate($request, [
'post' => 'required|max:1000',
]);
if(Request::ajax()){
Auth::user()->posts()->create([
'body' => $request->input('post'),
'profile_id' => $id
]);
}
}
JS:
$('#post').submit(function(){
var body = $('#postbody').val();
var profileId = $('#user_id').text();
var postRoute = '/post/'+profileId;
var dataString = "body="+body+"&profile_Id="+profileId;
$.ajax({
type: "POST",
url: postRoute,
data: dataString,
success: function(data){
console.log(data);
}
});
});
try this, remove
onsubmit="....." attribute from form
and update your submit method like this
$('#post').submit(function(event){
var body = $('#postbody').val();
var profileId = $('#user_id').text();
var postRoute = '/post/'+profileId;
var dataString = "body="+body+"&profile_Id="+profileId;
$.ajax({
type: "POST",
url: postRoute,
data: dataString,
success: function(data){
console.log(data);
}
});
//this will prevent your default form submit
event.preventDefault();
});
I hope this will work for you

Resources