it's been a while since I stuck in this problem. So I want to make a dynamic selection, when I select a nis (student_id) then the column nama (name) is filled with the student name.
Input form
Output i want
method create
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all()
]);
}
create_blade.php
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="name" required />
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
I have watched and read some questions with similar problems, and yet I still didn't get it
UPDATE
My method in my controller
public function find_nis(Request $request)
{
$data = Student::find($request->id); //Counseling::with('student', 'student.student_class')->where('student_id', $request->id)->first();
return response()->json(['view' => view('admin.counseling.create', ['data' => $data])->render()]);
}
My Ajax in create.blade.php
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change','.student_nis',function () {
var student_id = $(this).val();
var a = $(this).parent();
console.log(student_id);
var op="";
$.ajax({
type : 'GET',
url : '{!! URL::to('find_nis') !!}',
data : 'id=' + student_id,
success:function(data){
console.log(data);
a.find('.student_name').val(data.name);
},
error:function(){
}
});
});
});
</script>
My Route
Route::get('/admin/counseling/find_nis', [CounselingController::class, 'find_nis'])->name('find_nis');
this is output in my browser console when i select nis 1212
i think for getting response from DB without refresh page you should use ajax,
post student_id with ajax to Controller get username from DB and return your view like this:
in your blade:
first you must set this meta tag inside of :
<meta name="csrf-token" content="{{ csrf_token() }}">
then config and post your data with ajax like this:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var studentId = $("input[name=student]").val();
$.ajax({
xhrFields: {withCredentials: true},
type:'POST',
url:"{{ route('getStudentInfo') }}",
data:{studentId:studentId},
success:function(data){
$('html').html(data.view);
}
});
</script>
in your Controller inside of getStudentInfo():
$student = DB::table('user')->find($studen_id);
$username = $student->username;
return response()->json(['view' => view('admin.counseling.create', compact('username'))->render()]);
Here the working solutions
*Route
Route::get('/admin/counseling/find_student', [CounselingController::class, 'find_nis'])->name('find_student');
*Controller
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all(),
'problems' => Problem::all()
]);
}
public function find_nis(Request $request)
{
$student = Student::with('student_class')->findOrFail($request->id);
return response()->json($student);
}
*blade
<div class="container-fluid mt--7">
<div class="mt-8">
<div class="dashboard-content">
<div class="row">
<div class="col-12">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="student_name" id="student_name" disabled required/>
</div>
<div class="form-group">
<label>Kelas</label>
<input type="text" class="form-control" name="student_class_name" id="student_class" disabled required/>
</div>
<div class="form-group">
<label>Permasalahan</label>
<div class="row">
<div class="col">
#foreach ($problems as $problem)
<div class="form-check">
<input type="checkbox" id="" name="problem_name[]" value="{{ $problem->name }}">
<label class="fs-6 fw-light">{{ $problem->name }}</label>
</div>
#endforeach
</div>
</div>
</div>
<div class="form-group">
<label>Bobot Permasalahan</label>
<select name="priority" required class="form-control" id="nis">
<option value="null" disabled="true" selected="true">-Pilih-</option>
<option value="1">Normal</option>
<option value="3">Penting</option>
<option value="5">Sangat Penting</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
*ajax
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_name').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_name').val(data.name);
},
error:function(){
}
});
});
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_class').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_class').val(data.student_class.name);
},
error:function(){
}
});
});
});
</script>
I'm new to laravel, I'm trying to achieve a functionality when selecting a year for a specific ID or number that year will be removed from the dropdown list or it will not be listed.
Below I added screenshots and my code so far. I'm actually struggling to figure this out. :(
Please let me know if you need to check my controller.php and others.
Here's my code:
JS:
$(document).ready(function () {
// input fields
$("#tax-dec-form").on('submit', function (e) {
e.preventDefault()
$('#tax-dec-form').find('span.error').remove() //resets error messages
let _url = null;
let data = $('#tax-dec-form').serialize();
if ($('#tax-dec-form').hasClass('new')) {
_url = 'add-tax-info'
data = $('#tax-dec-form').serialize() + "&pin_id=" + pin_id
} else {
_url = 'update-tax-info'
}
$.ajax({
url: _url,
type: "POST",
data: data,
success: function (response) {
if (response.code == 200) {
//console.log(response)
$('#tax-dec-form').removeClass('new');
swal({ title: "Success!", text: response.message, type: "success", buttonsStyling: false, confirmButtonClass: "btn btn-success" })
}
},
error: function (response) {
console.warn(response.responseJSON.errors)
$.each(response.responseJSON.errors, function (field_name, error) {
if ($(document).find('#tax-dec-form [name=' + field_name + ']').next().is('span')) {
$(document).find('#tax-dec-form [name=' + field_name + ']').next('span').remove()
}
$(document).find('#tax-dec-form [name=' + field_name + ']').after('<span class="error text-danger">' + error + '</span>')
})
}
})
})
$('[data-toggle="tooltip"]').tooltip()
})
//for dynamic year list
$(document).ready(function () {
var d = new Date();
for (var i = 0; i <= 40; i++) {
var option = "<option value=" + parseInt(d.getFullYear() + i) + ">" + parseInt(d.getFullYear() + i) + "</option>"
$('[id*=DropDownList1]').append(option);
}
});
Blade.php:
<div class="content menu-css">
<div class="container-fluid">
{{-- upper form here --}}
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header card-header-primary">
<h4 class="card-title">Tax Information</h4>
<p class="card-category">Please complete all fields</p>
</div>
<div class="form-group"> </div>
<div class="card-body">
#if (session('status'))
<div class="row">
<div class="col-sm-12">
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<i class="material-icons">close</i>
</button>
<span>{{ session('status') }}</span>
</div>
</div>
</div>
#endif
<div class="form_container">
<form action="/action_page.php" id="tax-dec-form" {{$taxesInfo !== null ? '' : 'class=new'}}>
#csrf
<div class="form-group">
<label for="taxdeclarationnumber">Tax Declaration No:</label>
<input value="{{ $taxesInfo->tax_declaration_number ?? ''}}" type="text" class="form-control" name="tax_declaration_number" placeholder="Input Tax Declaration No..">
</div>
<div class="form-group"> </div>
<div class="form-group">
<label for="current">Current RPT: </label>
<input type="text" value="{{ $taxesInfo->current_rpt ?? ''}}" class="form-control" name="current_rpt" placeholder="Input Current RPT..">
</div>
<div class="form-group">
<label for="years" class="bmd-label-static">Select Tax Declaration Year</label>
<select id="DropDownList1" class="custom-select mr-sm-2" data-style="btn btn-secondary" name="year">
</select>
</div>
</form>
</div>
<div class="clearfix"> </div>
<div id="form-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" id="btn-save1">Save</button>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
</div>
I have a few application, when I am sending formdata using axios post data is successfully sent to API. but when i am using put request its not working with formData.
<template>
<div class="container">
<div class="container-fluid" style="background:#fff">
<div class="page-header">
<h4 class="page-title">
<i class="flaticon-users"></i> Leads
</h4>
<ul class="breadcrumbs">
<li class="nav-home">
<a href="/">
<i class="flaticon-home"></i>
</a>
</li>
<li class="separator">
<i class="flaticon-right-arrow"></i>
</li>
<li class="nav-item">
<router-link to="/leads">Leads</router-link>
</li>
<li class="separator">
<i class="flaticon-right-arrow"></i>
</li>
</ul>
</div>
<template>
<div class="btn-wrapper">
<button v-on:click="seen = !seen" class="btn btn-primary btn-md">
<i class="flaticon-interface-1"></i>Add New Lead
</button>
</div>
<p></p>
</template>
<div class="row">
<div class="col-md-12" v-if="!seen">
<div class="card">
<div class="card-header">
<h4 class="card-title">
<i class="flaticon-interface-1"></i> New Leads
</h4>
</div>
<div class="card-body">
<form
#submit.prevent="addLeads"
id="leadform"
class="mb-3"
enctype="multipart/form-data"
>
<div class="col-md-12">
<div class="row">
<div class="col-md-6">
<label>Lead</label>
<div class="form-group">
<input
type="text"
id="name"
name="lead_name"
class="form-control"
placeholder="Lead Name"
v-model="form.name"
>
<template v-if="errors">
<span v-for="(fieldsError, fieldName) in errors" :key="fieldName">
<template v-if="fieldName == 'name'">
<p class="errors">
<strong>{{ fieldsError.join('\n') }}</strong>
</p>
</template>
</span>
</template>
</div>
</div>
<div class="col-md-6">
<label>Source</label>
<div class="form-group">
<textarea
type="text"
id="source"
name="source"
class="form-control"
placeholder="lead Souve"
v-model="form.source"
></textarea>
<template v-if="errors">
<span v-for="(fieldsError, fieldName) in errors" :key="fieldName">
<template v-if="fieldName == 'source'">
<p class="errors">
<strong>{{ fieldsError.join('\n') }}</strong>
</p>
</template>
</span>
</template>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label>Value</label>
<div class="form-group">
<input
type="text"
id="value"
name="value"
class="form-control"
placeholder="lead Value"
v-model="form.value"
>
<template v-if="errors">
<span v-for="(fieldsError, fieldName) in errors" :key="fieldName">
<template v-if="fieldName == 'value'">
<p class="errors">
<strong>{{ fieldsError.join('\n') }}</strong>
</p>
</template>
</span>
</template>
</div>
</div>
<div class="col-md-6">
<label>Notes</label>
<div class="form-group">
<textarea
type="text"
id="notes"
name="notes"
class="form-control"
placeholder="lead Notes"
v-model="form.notes"
></textarea>
<template v-if="errors">
<span v-for="(fieldsError, fieldName) in errors" :key="fieldName">
<template v-if="fieldName == 'notes'">
<p class="errors">
<strong>{{ fieldsError.join('\n') }}</strong>
</p>
</template>
</span>
</template>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="exampleFormControlSelect1">Assigned To</label>
<template v-if="!userlist">
<select class="form-control" id="assigned_to">
<option value>No User Found</option>
</select>
</template>
<template v-else>
<select
v-model="form.assigned_to"
name="assigned_to"
class="form-control"
id="assigned_to"
>
<option value>Please Select</option>
<option v-for="user in userlist" :key="user.id" :value="user.id">
<template v-if="user.id == currentUser.id">Me</template>
<template v-else>{{ user.name }}</template>
</option>
</select>
</template>
<template v-if="errors">
<span v-for="(fieldsError, fieldName) in errors" :key="fieldName">
<template v-if="fieldName == 'assigned_to'">
<p class="errors">
<strong>{{ fieldsError.join('\n') }}</strong>
</p>
</template>
</span>
</template>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Close Date</label>
<div class="clearfix"></div>
<date-picker v-model="form.date" name="close_date"></date-picker>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label>Email</label>
<div class="form-group">
<input
type="text"
id="email"
name="email"
class="form-control"
placeholder="User Email"
v-model="form.email"
>
<template v-if="errors">
<span v-for="(fieldsError, fieldName) in errors" :key="fieldName">
<template v-if="fieldName == 'email'">
<p class="errors">
<strong>{{ fieldsError.join('\n') }}</strong>
</p>
</template>
</span>
</template>
</div>
</div>
<div class="col-md-6">
<label>Phone</label>
<div class="form-group">
<input
type="text"
id="phone"
name="phone"
class="form-control"
placeholder="User Phone Number"
v-model="form.phone"
>
<template v-if="errors">
<span v-for="(fieldsError, fieldName) in errors" :key="fieldName">
<template v-if="fieldName == 'phone'">
<p class="errors">
<strong>{{ fieldsError.join('\n') }}</strong>
</p>
</template>
</span>
</template>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input
type="file"
multiple="multiple"
id="attachments"
#change="uploadFieldChange"
>
<hr>
<div class="col-md-12">
<div
class="attachment-holder animated fadeIn"
v-cloak
v-for="(attachment, index) in attachments"
>
<template v-if="attachment.file_name">
<span class="label label-primary">{{ attachment.file_name}}</span>
</template>
<template v-else>
<span
class="label label-primary"
>{{ attachment.name + ' (' + Number((attachment.size / 1024 / 1024).toFixed(1)) + 'MB)'}}</span>
</template>
<span
class
style="background: red; cursor: pointer;"
#click="removeAttachment(attachment)"
>
<button class="btn btn-xs btn-danger">Remove</button>
</span>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-check">
<label>Status</label>
<br>
<label class="form-radio-label">
<input
class="form-radio-input"
v-model="form.status"
type="radio"
name="status"
value="open"
checked
>
<span class="form-radio-sign">Open</span>
</label>
<label class="form-radio-label ml-3">
<input
class="form-radio-input"
v-model="form.status"
type="radio"
name="status"
value="sent"
>
<span class="form-radio-sign">Proposal Sent</span>
</label>
<label class="form-radio-label ml-3">
<input
class="form-radio-input"
v-model="form.status"
type="radio"
name="status"
value="won"
>
<span class="form-radio-sign">Won</span>
</label>
<label class="form-radio-label ml-3">
<input
class="form-radio-input"
v-model="form.status"
type="radio"
name="status"
value="lost"
>
<span class="form-radio-sign">lost</span>
</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<button type="submit" class="btn btn-success">Save</button>
<button #click="clearForm()" class="btn btn-danger">Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid" style="background:#fff;">
<kanban-board :stages="stages" :blocks="blocks" #update-block="updateBlock">
<div v-for="stage in stages" :slot="stage">
<h2>{{ stage }}</h2>
</div>
<div v-for="block in blocks" :slot="block.id">
<div>
<strong>{{ block.name }}</strong>
</div>
<p></p>
<button class="btn btn-danger">UKDH</button>
<button class="btn btn-warning">£ {{ block.value }}</button>
<router-link :to="`/account/${block.id}/convert`" class="btn btn-primary">create account</router-link>
<div class="text-right">
<router-link :to="`/leads/${block.id}`" class="btn btn-link btn-info">
<i class="la la-street-view"></i>
</router-link>
<a href="#" #click="deleteLead(block.id)" class="btn btn-link btn-danger">
<i class="la la-times"></i>
</a>
<a href="#" #click="editLead(block)" class="btn btn-link btn-primary">
<i class="la la-edit"></i>
</a>
</div>
</div>
</kanban-board>
</div>
</div>
</template>
<script>
import { addLeadsAPI } from "../../helpers/api";
import { updateStatus } from "../../helpers/api";
import { getCommonAPI } from "../../helpers/api";
import { deleteAPI } from "../../helpers/api";
import validate from "validate.js";
import DatePicker from "vue2-datepicker";
export default {
name: "leads",
components: {
DatePicker
},
data() {
return {
leads: [],
userlist: [],
attachments: [],
percentCompleted: 0,
upload_size: 0,
result: {},
stages: ["open", "sent", "lost", "won"],
blocks: [],
form: {
id: "",
name: "",
source: "",
value: 0,
notes: "",
user_id: "",
assigned_to: 1,
date: new Date(),
email: "",
phone: "",
status: ""
},
lead_id: "",
pagination: {},
edit: false,
isOpen: 0,
seen: true,
errors: null
};
},
created() {
this.fetchLeads();
this.getusers();
},
mounted() {
this.$store.dispatch("leads");
},
methods: {
getusers(page_url) {
let vm = this;
getCommonAPI("/users", "get", {
headers: {
Authorization: `Bearer ${this.currentUser.token}`,
Accept: "application/json"
}
}).then(res => {
vm.userlist = res.data;
});
},
fetchLeads(page_url) {
let vm = this;
page_url = page_url || "/leads/lead";
getCommonAPI(page_url, "get", {
headers: {
Authorization: `Bearer ${this.currentUser.token}`,
Accept: "application/json"
}
}).then(res => {
vm.blocks = res.data.data;
//vm.makePagination(res.meta, res.links);
});
},
makePagination(meta, links) {
let pagination = {
current_page: meta.current_page,
last_page: meta.last_page,
next_page_url: links.next,
prev_page_url: links.prev
};
this.pagination = pagination;
},
editLead(form) {
console.log(form);
this.edit = true;
this.seen = false;
this.form.id = form.id;
this.form.name = form.name;
this.form.lead_sid = form.lead_sid;
this.form.status = form.status;
this.form.type = form.type;
this.form.source = form.source;
this.form.value = form.value;
this.form.notes = form.notes;
this.form.email = form.email;
this.form.phone = form.phone;
this.form.assigned_to = form.assigned_to;
this.form.date = form.close_date;
this.attachments = form.uploads;
},
clearForm() {
this.edit = false;
this.form.id = null;
this.form.user_id = null;
this.form.assigned_to = "";
this.form.type = "";
this.form.status = true;
this.form.name = "";
this.form.source = "";
this.form.value = "";
this.form.notes = "";
this.form.email = "";
this.form.phone = "";
this.attachments = [];
},
addLeads() {
if (this.edit === false) {
// add new leads
this.errors = null;
const constraints = this.getConstraints();
const errors = validate(this.$data.form, constraints);
if (errors) {
this.errors = errors;
return;
}
// multiple file uploading
this.lead = document.getElementById("leadform");
const formData = new FormData(this.lead);
if (this.attachments.length > 0) {
for (var i = 0; i < this.attachments.length; i++) {
let attachment = this.attachments[i];
formData.append("attachments[]", attachment);
}
}
var config = {
headers: { "Content-Type": "multipart/form-data" },
onUploadProgress: function(progressEvent) {
this.percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
this.$forceUpdate();
}.bind(this)
};
//end
this.$store.dispatch("lead");
addLeadsAPI(formData, "post").then(res => {
swal("Good job!", "You clicked the button!", "success");
this.clearForm();
this.fetchLeads();
//this.attachments = [];
});
} else {
this.errors = null;
const constraints = this.getConstraints();
const errors = validate(this.$data.form, constraints);
if (errors) {
this.errors = errors;
return;
}
console.log("i am in edit");
// multiple file uploading
this.lead = document.getElementById("leadform");
let formData = new FormData(this.lead);
if (this.attachments.length > 0) {
for (var i = 0; i < this.attachments.length; i++) {
let attachment = this.attachments[i];
formData.append("attachments[]", attachment);
}
}
console.log(formData);
var config = {
headers: { "Content-Type": "multipart/form-data" },
onUploadProgress: function(progressEvent) {
this.percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
this.$forceUpdate();
}.bind(this)
};
//end
console.log(formData);
this.$store.dispatch("lead");
//update
addLeadsAPI(formData, "put").then(res => {
swal("Good job!", "You clicked the button!", "success");
this.clearForm();
this.fetchLeads();
//this.attachments = [];
});
}
},
getConstraints() {
return {
name: {
presence: true,
length: {
minimum: 6,
message: "Must be at least 6 characters long"
}
},
source: {
presence: true,
length: {
minimum: 6,
message: "Must be at least 6 characters long"
}
},
value: {
presence: true,
length: {
minimum: 1,
message: "Must be at least 1 characters long"
}
},
notes: {
presence: true,
length: {
minimum: 6,
message: "Must be at least 6 characters long"
}
}
};
},
updateBlock(id, status) {
//api call axios
updateStatus(id, status, "get").then(res => {
this.clearForm();
this.fetchLeads();
});
this.blocks.find(b => b.id === Number(id)).status = status;
},
deleteLead(id) {
swal({
title: "Are you sure?",
text: "Do you really want to delete Lead!",
type: "warning",
buttons: {
confirm: {
text: "Yes, delete it!",
className: "btn btn-success"
},
cancel: {
visible: true,
className: "btn btn-danger"
}
}
}).then(Delete => {
if (Delete) {
deleteAPI(`/lead/${id}`, "delete", {
headers: {
Authorization: `Bearer ${this.currentUser.token}`,
Accept: "application/json"
}
}).then(res => {
swal({
title: "Deleted!",
text: "Your lead has been deleted.",
type: "success",
buttons: {
confirm: {
className: "btn btn-success"
}
}
});
this.fetchLeads();
});
} else {
this.fetchLeads();
swal.close();
}
});
},
getAttachmentSize() {
this.upload_size = 0; // Reset to beginningƒ
this.attachments.map(item => {
this.upload_size += parseInt(item.size);
});
this.upload_size = Number(this.upload_size.toFixed(1));
this.$forceUpdate();
},
removeAttachment(attachment) {
this.attachments.splice(this.attachments.indexOf(attachment), 1);
this.getAttachmentSize();
},
// This function will be called every time you add a file
uploadFieldChange(e) {
console.log(this.attachments);
var files = e.target.files || e.dataTransfer.files;
if (!files.length) return;
for (var i = files.length - 1; i >= 0; i--) {
this.attachments.push(files[i]);
}
console.log("out");
// Reset the form to avoid copying these files multiple times into this.attachments
document.getElementById("attachments").value = [];
}
},
computed: {
users() {
return this.$store.getters.users;
},
currentUser() {
return this.$store.getters.currentUser;
}
}
};
</script>
<style lang="scss">
#import "../assets/board.scss";
</style>
<style scoped>
.vue-js-switch#changed-font {
font-size: 30px;
}
.hide {
display: none;
}
.errors {
color: lightcoral;
border-radius: 5px;
padding: 21px 0 2px 0;
}
</style>
when edit option true. I am calling method addLeadsAPI for posting data with axios put but Formdata is empty $request->all().
Anyone can help me with this?seems axios put is not working for editing data. through formdata.
Laravel can not handle multipart-formdata well with PUT method. See Input from PUT requests sent as multipart/form-data is unavailable #13457.
If your code actually uses the PUT method, it seems to be affected by this problem.
There are several workarounds.
Dealing with the client side:
Instead of PUT method, use POST method with _method parameter value set to PUT (called 'method spoofing')
Dealing with the server side:
Add a package that performs multipart processing to Laravel. (ex. illuminatech/multipart-middleware)
Use pecl/apfd extension which provides ability to parse 'multipart/form-data' HTTP requests for any request method.
I have changed the axioscall into post and set the value _method:put
addLeads() {
if (this.edit === false) {
// add new leads
this.errors = null;
const constraints = this.getConstraints();
const errors = validate(this.$data.form, constraints);
if (errors) {
this.errors = errors;
return;
}
// multiple file uploading
this.lead = document.getElementById("leadform");
const formData = new FormData(this.lead);
if (this.attachments.length > 0) {
for (var i = 0; i < this.attachments.length; i++) {
let attachment = this.attachments[i];
formData.append("attachments[]", attachment);
}
}
var config = {
headers: { "Content-Type": "multipart/form-data" },
onUploadProgress: function(progressEvent) {
this.percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
this.$forceUpdate();
}.bind(this)
};
//end
this.$store.dispatch("lead");
formData.append("_method", "post");
addLeadsAPI(formData, "post", config).then(res => {
swal("Good job!", "You clicked the button!", "success");
this.clearForm();
this.fetchLeads();
//this.attachments = [];
});
} else {
this.errors = null;
const constraints = this.getConstraints();
const errors = validate(this.$data.form, constraints);
if (errors) {
this.errors = errors;
return;
}
console.log("i am in edit");
// multiple file uploading
this.lead = document.getElementById("leadform");
let formData = new FormData(this.lead);
if (this.attachments.length > 0) {
for (var i = 0; i < this.attachments.length; i++) {
let attachment = this.attachments[i];
formData.append("attachments[]", attachment);
}
}
formData.append("_method", "put");
formData.append("id", this.form.id);
console.log(formData);
var config = {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
onUploadProgress: function(progressEvent) {
this.percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
this.$forceUpdate();
}.bind(this)
};
//end
console.log(formData);
this.$store.dispatch("lead");
//update
addLeadsAPI(formData, "put", config).then(res => {
swal("Good job!", "You clicked the button!", "success");
this.clearForm();
this.fetchLeads();
//this.attachments = [];
});
}
},
Well, I had an issue trying to update records using axios & vue.js.
The solution is to set the method value on the formData to putand send the request using the post method. Something like this:
console.log("i am in edit");
// multiple file uploading
this.lead = document.getElementById("leadform");
let formData = new FormData(this.lead);
if (this.attachments.length > 0) {
for (var i = 0; i < this.attachments.length; i++) {
let attachment = this.attachments[i];
formData.append("attachments[]", attachment);
}
}
formData.append("_method", "put");
console.log(formData);
In your axios request:
axios({
method: "POST", // this is important
url: {$your_destination_url},
data: formData,
headers: { "Content-Type": "multipart/form-data" }
})
.then(r => console.log(r.data))
.catch(e => console.log(e));
It may be related to this, https://laravel.com/docs/5.0/routing#method-spoofing.
when using PUT, PATCH or DELETE, you may need to also let laravel know the form method you are using. Try adding "_method" property with the value "PUT", and let me know if that works for you
My previous wrong code -
let data = new FormData()
data.append('message', 'AnyMessage')
Instead of FormData use the following String that works fine -
let data = "message=AnyMessage"
I'm trying to make autocomplete in appended field.
My codeigniter view file:
<div class="right_col" role="main">
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<span class="section">Search Product's Info</span>
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Product Name <span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="prosearch" class="form-control col-md-7 col-xs-12" name="prosearch" type="text" placeholder="Search">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
My script:
<script type="text/javascript">
var $ = jQuery.noConflict();
$(function() {
// alert('hello');
$( "#prosearch" ).autocomplete({
source: function( request, response ) {
var t = $('#prosearch').val();
$.ajax({
type: "POST",
url: "<?php echo site_url('sale/search') ?>",
data: { term: request.term },
dataType: 'json',
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.data,
value: item.product_name,
id: item.id
}
}));
}
});
}
})
});
</script>
My Controller method:
public function search(){
$q=$_POST["term"];
#print_r($q); exit;
$query = $this->db->query("SELECT * FROM product WHERE product_name LIKE '".strtoupper($q)."%';");
$data= $query->result_array();
$json = json_encode($data);
echo $json;
}
My output is:
Well i am trying to my search result is under own input like any other autosuggestion.
Any kind of help.
Now this may sound complicated but I have a page called activation.php where after the user has registered using my reg.php page, they get sent an email with their activation link - activation.php then a get method of k to make activation.php?k=activation-code-here
I made it so it returns the status of the activation, e.g - success of error.
On my reg.php page, I want to make it so it uses ajax to open a sweetAlert popup saying 'Activation Success'. It will get the popup depending on if the users 'activ_status' changed from 0 to 1 in the database when they access the activation.php page with a correct activation key.
Here is my code :
Activation.php
<?php
include('inc/conf/db_.php');
$result = '';
if(empty($_GET['k']) || (!$_GET['k']))
{
header('Location: login.php');
exit();
$result = 'Hacker Tried Accessing Auth Page';
}
$key = mysqli_real_escape_string($con,$_GET["k"]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php
if (!empty($key))
{
$query = "SELECT * FROM users WHERE activ_key = '$key'";
$result = mysqli_query($con,$query) or die('error');
if (mysqli_num_rows($result))
{
$row = mysqli_fetch_array($result);
if ($row['activ_status']!='1')
{
$query = "update users set activ_status='1' where activ_key='$key'";
$result = mysqli_query($con,$query) or die('error');
$result = 'Successfuly Activated, Return To Your Other Page.';
}
else
{
$result = "Account Already Activated";
}
}
else
{
$result = 'Invalid Access Token';
}
}
else
{
$result = 'Error';
}
?>
<?php include('inc/login_header.php'); ?>
<div class="accountbg"></div>
<div class="wrapper-page">
<div class="panel panel-color panel-primary panel-pages">
<div class="panel-body">
<br>
<center><div id="result"></center>
<br>
<h3 class="text-center m-t-0 m-b-30"> <span class=""><?php echo site_settings('site_name'); ?></h3>
<h4 class="text-muted text-center m-t-0"><b>Activation Status</b></h4>
<br>
<center><img src="assets/images/loading.gif"></center>
<br>
<center><div class="alert alert-info"><button type="button" class="close"></button><?php echo $result; ?></div></center>
<?php return $result; ?>
</body>
</html>
My reg.php page
<?php
include('inc/conf/db_.php');
if (session_status() == PHP_SESSION_ACTIVE) {
session_start();
}
if(isset($_SESSION['user_i']) || isset($_SESSION['login'])) {
header('Location: index.php');
exit();
}
else if (session_status() == PHP_SESSION_NONE) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link href="assets/plugins/bootstrap-sweetalert/sweet-alert.css" rel="stylesheet" type="text/css">
<?php include('inc/login_header.php'); ?>
<div class="accountbg"></div>
<div class="wrapper-page">
<div class="panel panel-color panel-primary panel-pages">
<div class="panel-body">
<center><img src="assets/images/loading.gif" id="loading-image" style="display:none"/></center>
<h3 class="text-center m-t-0 m-b-30"> <span class=""><?php echo site_settings('site_name'); ?></h3>
<h4 class="text-muted text-center m-t-0"><b>Sign Up</b></h4>
<form id="registered_form" class="form-horizontal m-t-20">
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="email" type="email" required="" placeholder="Email"></div>
<span class="fa fa-envelope form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="username" type="text" required="" placeholder="Username"></div>
<span class="fa fa-user form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="password" type="password" required="" placeholder="Password"></div>
<span class="fa fa-lock form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LeGFxYUAAAAAOqjyovTS3H0D1HS4IBgoHMvG4y_"></div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="checkbox checkbox-primary" style="text-align: center;"> <input type="checkbox" name="checkbox" value="agree"> <label for="checkbox-signup"> I accept Terms and Conditions </label></div>
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12"> <button class="btn btn-primary w-md waves-effect waves-light" type="submit" id="reg_button" style="width: 100%;" >Register</button></div>
</div>
<div class="form-group m-t-30 m-b-0">
<div class="col-sm-12 text-center"> Already have an account?</div>
</div>
</form>
</div>
</div>
</div>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/js/jquery.validate.js"></script>
<script src="assets/plugins/bootstrap-sweetalert/sweet-alert.min.js"></script>
<script>
$(document).ready(function()
{
jQuery.validator.addMethod("noSpace", function(value, element)
{
return value.indexOf(" ") < 0 && value != "";
}, "Spaces are not allowed");
$("#registered_form").submit(function()
{
if ($("#registered_form").valid())
{
$('#loading-image').show();
var data1 = $('#registered_form').serialize();
$.ajax({
type: "POST",
url: "inc/pgs/register.php",
data: data1,
success: function(msg)
{
$('#loading-image').hide();
console.log(msg);
if(msg == '')
{
swal({
title: "Registration Success!",
text: "Your registration was successful! Check your email and click on your activation link to be able to access your account. NOTE: Keep this page open",
type: "success",
timer: 15000,
showConfirmButton: false
});
}
else
{
swal("Registration Error!", msg, "error");
}
}
});
$.ajax({
type: "GET",
url: "activation.php",
data: data1,
success: function(msg)
{
if(msg == 'Successfuly Activated, Return To Your Other Page.')
{
swal({
title: "Activation Success",
text: "You can now login!",
type: "success",
timer: 15000,
showConfirmButton: false
});
}
}
});
}
return false;
});
});
</script>
</body>
</html>
<?php } ?>
I found a piece of code that might help me. It doesn't seem to be loading the modal up though:
$.ajax({
url: 'activation.php',
type: 'GET',
dataType: 'jsonp',
cache: 'false',
timeout: 32000,
success: function(data) {
if(data == 'Successfuly Activated, Return To Your Other Page.')
{
swal("Activation Completed!", "You can now login using the link at the bottom of the page - Already have an account?", "success")
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[refresh]: " + textStatus);
console.log(jqXHR);
ajaxCall();
},
});
Please clearly explain the problem you are having that is preventing the code from working as you intend.
If my interpretation is correct, you want to update the registration page that user keeps open while activating in another window, and then reflect the change on the registration page using AJAX. In fact, in this case you want to send data from the server to your client (you want something to change when a change happens on the server in the database). In this case, a simple solution is to repeatedly request the status (for instance every 2 seconds) using setTimeout. Other solutions exist but are probably overkill, such as long polling or web sockets.