How to send some data and image from AJAX to Controller in Laravel? - ajax

I'm a freshmen in the office and I was assigned by my boss to fix the code of the website that the developer is not in the company anymore. He used mostly AJAX to do things which I'm not used to it. I rarely use AJAX in my project, so I'm very very new about this.
From the old code, I'm trying to send an image with some data from an input form. I can console.log(form_data) to see its values, but I don't know why the content of image cannot be sent to Controller. It's getting 'null' and I can't store it.
Here is the code in input form
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">{{$head}}</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="input-form" class="needs-validation" novalidate method="POST" enctype="multipart/form-data" name="input-form">
{{ csrf_field() }}
<div class="form-horizontal">
<div class="form-group required">
<label class="col-sm-12 control-label" for="thai_name">{{trans('home.thai_name')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="thai_name" name="thai_name" value="{{isset($user) ? $user->thai_name : ''}}" required/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="eng_name">{{trans('home.eng_name')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="eng_name" name="eng_name" value="{{isset($user) ? $user->eng_name : ''}}" required/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="email">{{trans('home.email')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="email" name="email" value="{{isset($user) ? $user->email : ''}}" required/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="password">{{trans('home.password')}}</label>
<div class="col-sm-12">
<input type="password" id="password" class="form-control" required/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="password_confirmation">{{trans('home.password_confirmation')}}</label>
<div class="col-sm-12">
<input type="password" id="password_confirmation" class="form-control" required/>
</div>
</div>
<div class="form-group col-sm-12">
<a class="btn-link" id="message" style="text-align: center;"></a>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label" for="phone">{{trans('home.phone')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="phone" name="phone" value="{{isset($user) ? $user->telephone : ''}}" required/>
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label" for="fax">{{trans('home.fax')}}</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="fax" name="fax" value="{{isset($user) ? $user->fax : ''}}"/>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label">{{trans('home.system_role')}}</label>
<div class="col-sm-12">
<div class="form-check form-check-inline">
<input class="form-check-input role" type="radio" id="admin" name="role" value="1"
{{isset($user) && $user->system_role_id == 1 ? 'checked' : ''}} required>
<label class="form-check-label" for="admin">ผู้ดูแลระบบ</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input role" type="radio" id="content_admin" name="role" value="2"
{{isset($user) && $user->system_role_id == 2 ? 'checked' : ''}} required>
<label class="form-check-label" for="content_admin">ผู้ดูแลข้อมูล</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input role" type="radio" id="user" name="role" value="3"
{{isset($user) && $user->system_role_id == 3 ? 'checked' : ''}} required>
<label class="form-check-label" for="user">ผู้ใช้งาน</label>
</div>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label">{{trans('home.faction')}}</label>
<div class="col-sm-12">
<select id="faction" class="form-control">
#foreach($factions as $faction)
<option value="{{$faction->id}}" {{isset($user) && $user->faction_id == $faction->id ? 'selected' : ''}}>
{{trans('home.'.$faction->name)}}
</option>>
#endforeach
</select>
</div>
</div>
<div class="form-group required">
<label class="col-sm-12 control-label">{{trans('home.position')}}</label>
<div class="col-sm-12">
<select id="position" class="form-control">
#foreach($positions as $position)
<option value="{{$position->id}}" {{isset($user) && $user->position_id == $position->id ? 'selected' : ''}}>
{{trans('home.'.$position->name)}}
</option>>
#endforeach
</select>
</div>
</div>
<div class="form-group required">
<div class="col-sm-12">
<label class="control-label" for="photo">รูปถ่าย</label>
<input type="file" class="form-control-file" id="photo" name="photo" accept="image/*" required/>
</div>
</div>
<div class="form-group">
<label class="col-sm-12 control-label">{{trans('home.acting')}} / {{trans('home.past')}}</label>
<div class="col-sm-12">
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="acting" name="acting" {{isset($user) && $user->is_acting ? 'checked' : ''}}>
<label class="form-check-label" for="acting">{{trans('home.acting')}}</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="past" name="past" {{isset($user) && $user->is_past ? 'checked' : ''}}>
<label class="form-check-label" for="past">{{trans('home.past')}}</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-12" for="start">{{trans('home.start')}}</label>
<div class="col-sm-12">
<div class="input-group" id="start" name="start">
<input type="text" class="form-control" readonly="readonly"/>
<div class="input-group-append">
<span class="input-group-text input-group-addon">
<span class="fa fa-calendar"></span>
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-12" for="end">{{trans('home.end')}}</label>
<div class="col-sm-12">
<div class="input-group" id="end" name="end">
<input type="text" class="form-control" readonly="readonly"/>
<div class="input-group-append">
<span class="input-group-text input-group-addon">
<span class="fa fa-calendar"></span>
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row col-sm-12 text-center">
<input type="button" class="btn btn-default" value="{{trans('home.save')}}"
onclick="{{$func}}"
/>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#start').datetimepicker({
sideBySide: true,
locale: 'th',
format: 'YYYY-MM-DD',
ignoreReadonly: true,
defaultDate: "{{isset($user) ? $user->start : ''}}"
});
$('#end').datetimepicker({
sideBySide: true,
locale: 'th',
format: 'YYYY-MM-DD',
ignoreReadonly: true,
defaultDate: "{{isset($user) ? $user->end : ''}}"
});
$('#password, #password_confirmation').on('keyup', function () {
if ( $('#password').val() == $('#password_confirmation').val() ) {
if ( $('#password').val() != '') {
$('#message').html('{{trans("home.password_match")}}').css('color', 'green');
} else {
$('#message').html('{{trans("home.password_null")}}').css('color', 'red');
$('#password').removeClass('valid').addClass('invalid');
$('#password_confirmation').removeClass('valid').addClass('invalid');
}
} else {
$('#message').html('{{trans("home.password_mismatch")}}').css('color', 'red');
$('#password').removeClass('valid').addClass('invalid');
$('#password_confirmation').removeClass('valid').addClass('invalid');
}
});
});
</script>
Here is the code in user.js where I'm using AJAX to send form_data contains image and some data
function addUser() {
var validate = validateUser("add");
if (validate.error == '') {
$('#modal1').modal({backdrop: "static"});
var form_data = {
thai_name: validate.thai_name,
eng_name: validate.eng_name,
email: validate.email,
password: validate.password,
password_confirmation: validate.password_confirmation,
telephone: $('#phone').val(),
fax: $('#fax').val(),
system_role_id: $('input[name=role]:checked').val(),
faction_id: $('#faction').val(),
position_id: $('#position').val(),
photo: $('#photo').val(),
photo_file: $('#photo').prop("files")[0],
is_acting: 0,
is_past: 0,
start: $('#start').data('date'),
end: $('#end').data('date'),
};
if ($('#acting').is(':checked')) {
form_data.is_acting = 1;
}
if ($('#past').is(':checked')) {
form_data.is_past = 1;
}
console.log(form_data);
$.ajax({
type: "post",
enctype: "multipart/form-data",
url: baseurl + "/admin/user/add",
data: form_data,
processData: false,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function () {
$('#input-area').modal('hide');
listUser();
}
});
}
}
Here is some code in my controller
public function addUser(Request $request) {
$user = new User();
$user->thai_name = request()->thai_name;
$user->eng_name = request()->eng_name;
$user->email = request()->email;
$user->password = Hash::make(request()->password);
$user->telephone = request()->telephone;
$user->fax = request()->fax;
$user->system_role_id = request()->system_role_id;
$user->faction_id = request()->faction_id;
$user->position_id = request()->position_id;
// Store Profile Photo
$filename = "profile-photo-" . time() . "-name-" . basename(request()->photo);
request()->file('photo_file')->storeAs('', $filename, 'images');
$user->photo = $filename;
$user->is_acting = request()->is_acting;
$user->is_past = request()->is_past;
$user->start = request()->start;
$user->end = request()->end;
$user->save();
}
Which part I did wrong? Any ideas?
Please help me figure this out.
Thank you in advanced.

Related

Undefined array key "school_name" using flatMap

i am using flatMap to get the keys and the value related together
but it gives me an error Undefined array key "school_name" i dont know why
although i do return $setting it gives me like this
{
setting: {
current_session: "2021-2022",
school_title: "MS",
school_name: "Mora Soft International Schools",
end_first_term: "01-12-2021",
end_second_term: "01-03-2022",
phone: "0123456789",
address: "القاهرة",
school_email: "info#morasoft.com",
logo: "1.jpg"
}
}
this is my table settings table
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->string('key');
$table->string('value');
$table->timestamps();
});
and this is my web.php route
Route::resource('settings', 'SettingController');
and here is my settingcontroller
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$collection = setting::all();
$setting['setting'] = $collection->flatMap(function ($collection){
return [$collection->key => $collection->value];
});
// return $setting;
return view('pages.settings.index',compact('setting'));
}
and here is my blade that views the form
<form enctype="multipart/form-data" method="post" action="{{route('settings.update','test')}}">
#csrf #method('PUT')
<div class="row">
<div class="col-md-6 border-right-2 border-right-blue-400">
<div class="form-group row">
<label class="col-lg-2 col-form-label font-weight-semibold">اسم المدرسة<span class="text-danger">*</span></label>
<div class="col-lg-9">
<input name="school_name" value="{{ $setting['school_name'] }}" required type="text" class="form-control" placeholder="Name of School">
</div>
</div>
<div class="form-group row">
<label for="current_session" class="col-lg-2 col-form-label font-weight-semibold">العام الحالي<span class="text-danger">*</span></label>
<div class="col-lg-9">
<select data-placeholder="Choose..." required name="current_session" id="current_session" class="select-search form-control">
<option value=""></option>
#for($y=date('Y', strtotime('- 3 years')); $y<=date('Y', strtotime('+ 1 years')); $y++)
<option {{ ($setting['current_session'] == (($y-=1).'-'.($y+=1))) ? 'selected' : '' }}>{{ ($y-=1).'-'.($y+=1) }}</option>
#endfor
</select>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label font-weight-semibold">اسم المدرسة المختصر</label>
<div class="col-lg-9">
<input name="school_title" value="{{ $setting['school_title'] }}" type="text" class="form-control" placeholder="School Acronym">
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label font-weight-semibold">الهاتف</label>
<div class="col-lg-9">
<input name="phone" value="{{ $setting['phone'] }}" type="text" class="form-control" placeholder="Phone">
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label font-weight-semibold">البريد الالكتروني</label>
<div class="col-lg-9">
<input name="school_email" value="{{ $setting['school_email'] }}" type="email" class="form-control" placeholder="School Email">
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label font-weight-semibold">عنوان المدرسة<span class="text-danger">*</span></label>
<div class="col-lg-9">
<input required name="address" value="{{ $setting['address'] }}" type="text" class="form-control" placeholder="School Address">
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label font-weight-semibold">نهاية الترم الاول </label>
<div class="col-lg-9">
<input name="end_first_term" value="{{ $setting['end_first_term'] }}" type="text" class="form-control date-pick" placeholder="Date Term Ends">
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label font-weight-semibold">نهاية الترم الثاني</label>
<div class="col-lg-9">
<input name="end_second_term" value="{{ $setting['end_second_term'] }}" type="text" class="form-control date-pick" placeholder="Date Term Ends">
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label font-weight-semibold">شعار المدرسة</label>
<div class="col-lg-9">
<div class="mb-3">
<img style="width: 100px" height="100px" src="{{ URL::asset('attachments/logo/'.$setting['logo']) }}" alt="">
</div>
<input name="logo" accept="image/*" type="file" class="file-input" data-show-caption="false" data-show-upload="false" data-fouc>
</div>
</div>
</div>
</div>
<hr>
<button class="btn btn-success btn-sm nextBtn btn-lg pull-right" type="submit">{{trans('Students_trans.submit')}}</button>
</form>

I keep getting an Integrity constraint violation when I'm trying to submit data to db

I have this problem and I have no idea why it's not working. I have tried so many code changes but I still get the same error when I try to submit a form. It's a simple form to insert data to tomany tables in db. All tables accept data with no error but payment_agrement table gives me this error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (kassemschool.payment_agrements, CONSTRAINT payment_agrements_responisbleid_foreign FOREIGN KEY (responsible_id) REFERENCES payment_agrements (id)) (SQL: insert into payment_agrements (frais_inscription, payment_mois, Assurance, Garde, Transport, responsible_id, updated_at, created_at) values (450, 550, 400, 200, 300, 154, 2019-11-16 19:47:39, 2019-11-16 19:47:39))
This is my controller:
if(request()->has('rName')) {
$responsible = Responsible::create([
'ResponsibleName'=> $request->rName,
'ResponsibleCNI'=>$request->cni,
'responsible_number'=>$request->tele
]);
}
//Student::create($data);
if(request()->has('MontantP')) {
$payment=Payment::create([
'PaymentPaid'=>$request->MontantP,
'PaymentRemaining'=>$request->RestP,
'responsible_id'=>$responsible->id,
]);
}
if($request->hasFile('file')){
$student->images = $request->file->store('file');
}
if(request()->has('TransportR')) {
$transport=Transport::create([
'TransportPaid'=> $request->TransportP,
'TransportRemainning'=>$request->TransportR,
'TransportDateStart'=>$request->TdateStart,
'TransportDateEnd'=>$request->TdateEnd,
]);
}
if(request()->has('edateStart')) {
$payment_date = Payment_Date::create([
'PaymentDateStart'=>$request->edateStart,
'PaymentDateEnd'=>$request->edateEnd,
'payment_id'=>$payment->id,
]);
$letter = 'KassN';
$number =$request->env . 'G';
$number2 = $request->group;
$id='_'.rand();
$random = $letter.$number.$number2.$id;
if(request()->has('fName')) {
$student = Student::create([
'StudentFName'=> $request->fName,
'StudentLName'=> $request->lName,
'StudentDateStart'=>$request->edateStart,
'StudentDateEnd'=>$request->edateEnd,
'level_id'=> $request->env,
'group_id'=>$request->group,
'responsible_id'=> $responsible->id,
'payment_date_id'=>$payment_date->id,
'Payment_dure_id'=>$request->paymentD,
'payment_id'=>$payment->id,
'transport_id'=>$transport->id,
'student_code'=>$random
]);
}
if(request()->has('inscription')){
$agrement= Payment_agrement::create([
'frais_inscription'=>$request->inscription,
'payment_mois'=>$request->payment,
'Assurance'=>$request->assaurance,
'Garde'=>$request->garde,
'Transport'=>$request->fraiTransport,
'responsible_id'=>$responsible->id
]);
}
my create view
#extends('layouts.app')
#section('content')
#if (Route::has('login'))
#auth
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
back to <strong>Home</strong>
back to <strong>list</strong>
</div>
#endif
<div class="mr-auto offset-md-1" style="width: 200px;">
<input type="button" class="btn btn-danger btn-sm" name="" value="<- Reteur">
</div>
<div class="card-body">
<div class="container" style="width: 80%;">
<form action="{{url('student')}}" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label for="firstName">First Name </label>
<input type="text" class="form-control" name="fName" id="elastName">
</div>
<div class="form-group">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" name="lName" id="efirstName">
</div>
<div class="form-group">
<label for="responsable">Responsable Name:</label>
<input type="text" class="form-control" name="rName" id="responsable">
</div>
<div class="form-group">
<label for="cni">Responsable CNI:</label>
<input type="text" class="form-control" name="cni" id="cni">
</div>
<div class="form-group">
<label for="nuveau">Niveau:</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="nuveau">Options</label>
</div>
<select class="custom-select" id="nuveau" name="env">
<option selected>Choose...</option>
#foreach($levels as $level)
<option value="{{$level->id}}">{{$level->LevelName}} </option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<fieldset>
<legend>Aggrement:<hr></legend>
<div class="form-group">
<label for="cni">Frais de inscription:</label>
<input type="text" class="form-control" name="inscription" id="cni">
</div>
<div class="form-group">
<label for="cni">paiement mensuel:</label>
<input type="text" class="form-control" name="payment" id="cni">
</div>
<div class="form-group">
<label for="cni">Frais de Assurance:</label>
<input type="text" class="form-control" name="assaurance" id="cni">
</div>
<div class="form-group">
<label for="cni">Frais de Garde:</label>
<input type="text" class="form-control" name="garde" id="cni">
</div>
<div class="form-group">
<label for="cni">Frais de transport:</label>
<input type="text" class="form-control" name="fraiTransport" id="cni">
</div>
</fieldset>
</div>
<div class="form-group">
<label for="nuveau">Group:</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="group">Options</label>
</div>
<select class="custom-select" id="nuveau" name="group">
<option selected>Choose...</option>
#foreach($groups as $group)
<option value="{{$group->id}}">{{$group->group_name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="payment">Payment:</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="payment">Options</label>
</div>
<select class="custom-select" id="payment" name="paymentD">
<option selected>Choose...</option>
#foreach($payment_dures as $payment_dure)
<option value="{{$payment_dure->id}}">{{$payment_dure->payment_dure_name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="dateStart"></label>
<input type="date" class="#" id="dateStart" style="width: 49%;" name="edateStart">
<label for="dateEnd">au:</label>
<input type="date" class="#" id="dateEnd" style="width: 44%;" name="edateEnd">
</div>
<div class="form-group">
<label for="MontantP">Montant paye:</label>
<div class="input-group mb-3">
<input type="text" class="form-control" name="MontantP" placeholder="" id="MontantP">
<div class="input-group-append">
<span class="input-group-text">DH</span>
</div>
</div>
</div>
<div class="form-group">
<label for="RestP">Rest a paye paye:</label>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="" id="MontantR" name="RestP">
<div class="input-group-append">
<span class="input-group-text">DH</span>
</div>
</div>
</div>
<p>
<a class="btn btn-primary" data-toggle="collapse" href="#multiCollapseExample1" role="button" aria-expanded="false" aria-controls="multiCollapseExample1" style="width: 100%">Bus subscribtion</a>
<div class="row">
<div class="col">
<div class="collapse multi-collapse" id="multiCollapseExample1">
<div class="card card-body">
<div class="form-group">
<div class="form-group">
<label for="TMontantP">Montant paye:</label>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="" id="TMontantP" name="TransportP">
<div class="input-group-append">
<span class="input-group-text">DH</span>
</div>
</div>
</div>
<div class="form-group">
<label for="TRestP">Rest a paye paye:</label>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="" id="TRestP" name="TransportR">
<div class="input-group-append">
<span class="input-group-text">DH</span>
</div>
</div>
</div>
<div class="form-group">
<label for="TdateStart"></label>
<input type="date" class="#" id="TdateStart" style="width: 48%;" name="TdateStart">
<label for="dTateEnd">au:</label>
<input type="date" class="#" id="TdateEnd" style="width: 44%;" name="TdateEnd">
</div>
</div>
</div>
</div>
</div>
</div>
</p>
<br>
<button type="submit" class="btn btn-secondary">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
#else
<div class="d-flex justify-content-center text-center">
<div class="alert alert-danger" role="alert" style="width: 70%">
identifié vous d'abord
</div>
</div>
#endauth
#endif
#endsection
Looks like your foreign key constraint isn't setup correctly. From the look of the error you have setup payment_agrements.responsible_id to point to payment_agrements.id instead of responsibles.id.
In the migration for that table, that field probably looks like this:
$table->foreign('responsible_id')->references('id')->on('payment_agrements');
When it should be:
$table->foreign('responsible_id')->references('id')->on('responsibles');

including the appended variable to the data with other variable in ajax

Hello and good day everyone, I am having a problem in ajax. I have a variable named fd that contains object. But i cant find a way to put it together with other variable in "data:". I just want to pass the data of fd and also the other variables from other inputs of my form. Thank you very much.
$('#register_btn').click(function(e) {
var fd = new FormData();
var files = $('#image')[0].files[0];
fd.append('image',files);
var val1 = $('#email').val();
var val2 = $('#firstname').val();
var val3 = $('#middlename').val();
var val4 = $('#lastname').val();
var val5 = $('#emp_status').val();
var val6 = $('input[name=date_hired]').val();
var val7 = $('#account_type').val();
var val8 = $('#notes').val();
var val9 = $('#position').val();
var val10 = $('#cp_number').val();
var val11 = $('#tel_number').val();
var val12 = $('#address').val();
$.ajax({
type: 'POST',
url: 'process/add_employee_process.php',
contentType: false,
cache: false,
processData:false,
data: {email: val1, firstname: val2, middlename: val3, lastname: val4, emp_status: val5, date_hired: val6, account_type: val7, notes: val8, position: val9, cp_number: val10, tel_number: val11, address: val12,fd},
success:function(html) {
if(html=="Failed"){
$("#gifcheckmark").attr('src','../campfire.gif');
$("#gifcheckmark").css('display','inline');
$("#gifcheckmark").css('width','inline');
$("#notif_message").text("Failed");
$("#register_btn").css('display','none');
$("#decline_btn").css('display','none');
}
else{
$("#notif_message").text("Success");
$("#gifcheckmark").css('display','inline');
$("#gifcheckmark").css('width','inline');
$("#register_btn").css('display','none');
$("#decline_btn").css('display','none');
setInterval(successGif, 1600);
$('#qr').load('../phpqrcode/index.php');
$('#qr').show();
}
}
});
});
This is the form
<form role="form" style="width: 100%;">
<div class="box-body">
<div class="box-header with-border col-xs-12">
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-remove"></i></button>
</div>
</div>
<div class="form-group col-md-3">
<label for="">Email </label>
<input type="email" id="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div>
<div class="form-group col-md-3">
<label for="">Firstname </label>
<input type="text" id="firstname" class="form-control" id="" placeholder="Firstname">
</div>
<div class="form-group col-md-3">
<label for="">Middlename </label>
<input type="text" id="middlename" class="form-control" id="" placeholder="Middlename">
</div>
<div class="form-group col-md-3">
<label for="">Lastname </label>
<input type="text" id="lastname" class="form-control" id="" placeholder="Lastname">
</div>
<div class="form-group col-md-3">
<label for="">Employee Status </label>
<input type="text" id="emp_status" class="form-control" id="" placeholder="Employee Status">
</div>
<div class="form-group col-md-3">
<label for="">Date Hired </label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" name="date_hired" class="form-control pull-right" id="datepicker">
</div>
</div>
<div class="form-group col-md-3">
<label for="">Account Type </label>
<input type="text" id="account_type" class="form-control" id="" placeholder="Account Type">
</div>
<div class="form-group col-md-3">
<label for="">Notes </label>
<input type="text" id="notes" class="form-control" id="" placeholder="Notes">
</div>
<div class="form-group col-md-3">
<label for="">Positions </label>
<input type="text" id="position" class="form-control" id="" placeholder="Positions">
</div>
<div class="form-group col-md-3">
<label for="">Cellphone Number </label>
<input type="text" id="cp_number" class="form-control" id="" placeholder="Cellphone Number">
</div>
<div class="form-group col-md-3">
<label for="">Telephone Number </label>
<input type="text" id="tel_number" class="form-control" id="" placeholder="Telephone Number">
</div>
<div class="form-group col-md-3">
<label for="">Address </label>
<input type="text" id="address" class="form-control" id="" placeholder="Address">
</div>
<div class="form-group col-xs-12">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" id="image" name="image">
</div>
</div>
<!-- /.box-body -->
<div class="col-xs-2">
<center><button type="button" id="confirm_btn" class="btn btn-primary" data-toggle="modal" data-target="#modal-default">
Submit
</button></center>
</div>
</form>
This is the add_employee_process.php
$db = mysqli_connect('localhost', 'root','','cjwebsolutions');
$image = $_FILES['image']['name'];
$target = "image/".basename($image);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
$emp_id = make_emp_id($_POST['date_hired']);
$_POST['emp_id'] = $emp_id;
// Required field names
$required_fields = array('email','firstname','middlename','lastname', 'emp_status', 'date_hired','account_type','notes','position','cp_number','tel_number','address','emp_id');
$data_insert_fields = array('email','firstname','middlename','lastname', 'emp_status', 'date_hired','account_type','notes','position','cp_number','tel_number','address','emp_id');
if (check_empty_fields($required_fields)) {
echo "Failed";
}
else
{
data_insert($data_insert_fields,"cj_accounts");
}

When Pass pdf file in ajax call then file_get_content() gives error

When i try to pass pdf at controller side through ajax at that time file_get_content() gives error like this
file_get_contents(): Filename cannot be empty
My output is like below:-
Illuminate\Http\UploadedFile Object(
[test:Symfony\Component\HttpFoundation\File\UploadedFile:private] =>
[originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 2017-playing-rules.pdf
[mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => application/octet-stream
[size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
[error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 1
[hashName:protected] =>
[pathName:SplFileInfo:private] =>
[fileName:SplFileInfo:private] =>
)
Here "[pathName:SplFileInfo:private]=>" gives null response which should have temp path of my uploaded file.
Here is my ajax call:-
$('#formAddLeague').on('success.form.bv', function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url:'{{ url('restoreleague') }}',
data:formData,
type:'post',
dataType:'json',
cache: false,
contentType: false,
processData: false,
success: function(data)
{
$('#loader').hide();
if(data.key == 1)
{
notify('League has been updated Successfully.','blackgloss');
}
}
});
});
In controller i used following:-
$import_rule = $request->file('importRule');
Here is my controller:-
public function restore(Request $request)
{
$league_id = $request->get('hiddenLeagueId');
$import_rule = $request->file('importRule');
$league_rule_url = $request->get('txtLeagueRule');
$objLeague = League::find($league_id);
if (!empty($import_rule)) {
$originalName = $import_rule->getClientOriginalName();
$ruleFileName = pathinfo($originalName, PATHINFO_FILENAME) . '.' . pathinfo($originalName, PATHINFO_EXTENSION);
$s3 = Storage::disk('s3');
$filePath = 'league_rules/' . $ruleFileName;
if ($s3->put($filePath, file_get_contents($import_rule) , 'public'))
{
$ruleURL = $s3->url($filePath);
$objLeague->league_rules = $ruleURL;
$objLeague->rules_filename = $ruleFileName;
}
}
else
if (!empty($league_rule_url))
{
$checkExtension = pathinfo($league_rule_url, PATHINFO_EXTENSION);
if ($checkExtension != 'pdf')
{
$msg = "The selected url extension is not valid.";
return $msg;
}
else
{
$objLeague->league_rules = $league_rule_url;
}
}
$objLeague->league_name = $request->get('txtLeagueName');
$objLeague->league_email = $request->get('txtLeagueEmail');
$objLeague->league_phone = $this->replacePhoneNumber($request->get('leagueContactNo'));
$objLeague->league_info = $request->get('txtLeagueInfo');
$objLeague->level_id = $request->get('txtLevel');
$objLeague->age_required = $request->get('txtMinRequiredAge');
$objLeague->league_website = $request->get('leagueWebsite');
$objLeague->save();
$response['key'] = 1;
return $response;
}
Here is my form:-
<div id="tab2" class="tab-pane">
<form id="formAddLeague" method="post">
{{ csrf_field() }}
<input id="hiddenLeagueId" type="hidden" name="hiddenLeagueId" value="{{$leagueDetail->league_id or ''}}">
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label class="control-label"><b>LEAGUE NAME</b></label>
<input type="text" id="txtLeagueName" name="txtLeagueName" value="{{$leagueDetail->league_name or ''}}" class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><b>LEAGUE ID</b></label><br>
<span class="disabled-color" id="leagueId">{{$leagueDetail->league_id or ''}}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><b>TYPE OF LEAGUE</b></label>
<select id="txtLevel" name="txtLevel" class="form-control">
<option value="">-- Select Type of League --</option>
#foreach($levelList as $level)
<option value="{{ $level->level_id }}" #if($leagueDetail->level_id == $level->level_id) {{"selected='selected'"}} #endif>{{ $level->level_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><b>MIN AGE REQUIREMENT</b></label>
<select id="txtMinRequiredAge" name="txtMinRequiredAge" class="form-control">
<option value="ALL AGES" #if($leagueDetail->age_required == 'ALL AGES') {{ "selected='selected'" }} #endif>All AGES</option>
<option value="18 AND OVER" #if($leagueDetail->age_required == '18 AND OVER') {{ "selected='selected'" }} #endif>18 AND OVER</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group" style="overflow: visible!important;">
<label class="control-label"><b>SPORTS OFFERED</b></label>
<select id="txtLevel" name="txtLevel" class="form-control selectpicker" multiple data-style="form-control">
#foreach($levelList as $level)
<option value="{{ $level->level_id }}" #if($leagueDetail->level_id == $level->level_id) {{"selected='selected'"}} #endif>{{ $level->level_name }}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><b>LEAGUE EMAIL</b></label>
<input style="text-transform: lowercase;" type="email" id="txtLeagueEmail" name="txtLeagueEmail" value="{{$leagueDetail->league_email or ''}}" class="form-control" placeholder="Enter Your Email">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><b>LEAGUE PHONE</b></label>
<input placeholder="(xxx) xxx-xxxx" type="text" name="leagueContactNo" id="leagueContactNo" value="{{$leagueDetail->league_phone or ''}}" class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><b>LEAGUE WEBSITE</b></label>
<input id="leagueWebsite" type="text" name="leagueWebsite" value="{{$leagueDetail->league_website or ''}}" class="form-control" placeholder=" League website">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label"><b>LEAGUE RULES</b></label>
<div class="row">
<div class="col-md-1">
<div class="radio radio-info">
<input type="radio" name="user_radio" id="file_radio" onclick="leagueRule(1)" checked>
<label> Use File </label>
</div>
</div>
<div class="col-md-11">
<div class="col-sm-12">
<div class="fileinput fileinput-new input-group" data-provides="fileinput">
<div class="form-control" data-trigger="fileinput">
<i class="glyphicon glyphicon-file fileinput-exists"></i>
<span class="fileinput-filename"></span>
</div>
<span class="input-group-addon btn btn-default btn-file">
<span class="fileinput-new"><i class="fa fa-upload"></i></span>
<span class="fileinput-exists">Change</span>
<input type="file" name="importRule" id="importRule">
</span>
Remove
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-1">
<div class="radio radio-info">
<input type="radio" name="user_radio" id="url_radio" onclick="leagueRule(2)">
<label> Use URL </label>
</div>
</div>
<div class="col-md-11">
<input disabled type="text" id="txtLeagueRule" name="txtLeagueRule" value="{{$leagueDetail->league_rules or '' }}" class="form-control" placeholder="Enter Link">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<label class="control-label"><b>ABOUT</b></label>
<textarea id="txtLeagueInfo" style="resize: none;" class="form-control" rows="3" data-minwords="3" maxlength="238" name="txtLeagueInfo" placeholder="Type your message">{{$leagueDetail->league_info or ''}}</textarea>
<div id="textarea_feedback" style="text-align:right; color: red"></div>
{{-- <div id="textarea_feedback" class="text-left disabled-color"></div> --}}
</div>
</div>
</div>
<div class="form-group text-left p-t-md">
<button type="submit" class="btn btn-info">UPDATE</button>
</div>
</form>
</div>

How can I return a html view from an ajax call in Laravel 5.1?

I am trying to render an html view via ajax call and in success callback i will add this html to DOM.But i am not getting any response in the success callback.
public function create()
{
$format = new ProductFormat();
//return response()->view('cms.formats.create_modal', compact('format'));
return (String) view('cms.formats.create_modal', compact('format'));
}
$.ajax({
dataType: 'json',
method: 'GET',
type: 'html',
url: '{{ url("admin/formats/create") }}',
success: function (data) {
alert(data);
console.log(data);
$('#format_modal').html(data);
$('#add_edit_format_modal').modal('show');
}
}).error(function(e){
console.log(e);
});
error callback is getting the html response but why not in success call back?
my response is:
<div class="modal fade" id="add_edit_format_modal" tabIndex="-1">
<div class="modal-dialog">
<div class="modal-content"> <!--start modal content-->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">Product Format</h4>
</div>
<!--start modal body-->
<div class="modal-body">
<div class="form-horizontal" role="form" id="add_format">
<div class="form-group">
<label for="format_title_en" class="col-md-3 control-label">Title (en)</label
>
<div class="col-md-6">
<input id="format_title_en" value="" name="format_title_en" class="form-control"
type="text" required="required">
</div>
</div>
<div class="form-group">
<label for="format_title_fr" class="col-md-3 control-label">Title (fr)</label
>
<div class="col-md-6">
<input id="format_title_fr" value="" name="format_title_fr" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label for="barcode" class="col-md-3 control-label">Barcode</label>
<div class="col-md-6">
<input id="barcode" value="" name="barcode" class="form-control" type="number"
>
</div>
</div>
<div class="form-group">
<label for="packaging_type" class="col-md-3 control-label">Packaging Type</label
>
<div class="col-md-6">
<select class="form-control" id="format_packaging_type" name="packaging_type"
>
<option value="">Other</option>
<option value="bottled">Bottled</option>
<option value="canned">Canned</option>
</select>
</div>
</div>
<div class="form-group">
<label for="amount_g" class="col-md-3 control-label">Size (g)</label>
<div class="col-md-6">
<input id="amount_g" value="" name="amount_g" class="form-control" type="number"
onkeydown="validateNumberAllowDecimal(event, true)">
</div>
</div>
<div class="form-group">
<label for="amount_ml" class="col-md-3 control-label">Size (ml)</label>
<div class="col-md-6">
<input id="amount_ml" value="" name="amount_ml" class="form-control" type
="number" onkeydown="validateNumberAllowDecimal(event, true)">
</div>
</div>
<div class="form-group">
<label for="size_indicated_amount" class="col-md-3 control-label">Size Indicated
Amount</label>
<div class="col-md-6">
<input id="size_indicated_amount" value="" name="size_indicated_amount" class
="form-control" type="number" onkeydown="validateNumberAllowDecimal(event, true)">
</div>
</div>
<div class="form-group">
<label for="size_indicated_unit" class="col-md-3 control-label">Size Indicated
Unit</label>
<div class="col-md-6">
<input id="size_indicated_unit" value="" name="size_indicated_unit" class
="form-control" type="text">
</div>
</div>
<div class="form-group">
<label for="store_code" class="col-md-3 control-label">Store Code</label>
<div class="col-md-6">
<input id="store_code" value="" name="store_code" class="form-control" type
="number">
</div>
</div>
<div class="form-group">
<label for="price" class="col-md-3 control-label">Price</label>
<div class="col-md-6">
<input id="price" value="" name="price" class="form-control" type="number"
>
</div>
</div>
</div>
</div> <!--end modal body-->
<div class="modal-footer">
<button type="button" class="btn btn-success" id="save_product_format">
Save
</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div> <!--end modal content-->
</div>
</div>

Resources