Laravel 5.2 Method Not Allowed Exception on Production Server - php

I've build a simple from in laravel which takes some data and stores it in the DataBase.
Problem occurred when i uploaded my code on production server.
In development and local it's working perfectly, but when i try to submit the same form on production server it throws following exception:
MethodNotAllowedHttpException in RouteCollection.php line 218:
I've already checked my form and route methods both are post. I'm lost in it.
routes Code
Route::get('/', function () {
return view('welcome');
});
Route::group(['middleware' => ['web']], function () {
Route::get('auth/register', 'Auth\AuthController#register');
Route::post('/ajax-registration','RegistrationController#registration');
Route::post("/signup", "Api\ApplicantRegistrationController#registration");
Route::auth();
Route::get('/home', 'HomeController#index');
Route::get('/roles/{id}',"HomeController#roles");
Route::post('/complete-profile', 'HomeController#completeProfile');
});
Controller Code (the function which i am calling from route)
public function completeProfile(Request $request){
If(Input::hasFile('file')){
$file = Input::file('file');
$cDate = date("d-m-Y_H:i:s");
$destinationPath = public_path(). '/uploads/';
$filename = $cDate."_".$file->getClientOriginalName();
$file->move($destinationPath, $filename);
}
$insert = DB::table('Applicant')->insert(
[
'name' => Auth::user()->name,
'email' => Auth::user()->email,
'total_experience' => $request->input('int_exp'),
'functional_area' => $request->input('txtFunctionalArea'),
'current_role' => $request->input('txtRole'),
'current_company' => $request->input('company'),
'desired_role' => $request->input('txtRole2'),
'file' => $filename
]);
\DB::table('users')->where('email', Auth::user()->email)->update(['allInformationReceived' => 1]);
if($insert){
return redirect('/home');
}
else{
return 'Some Error';
}
}
form
<form id="signupform" method="POST" action="complete-profile" class="mob-pad0" enctype="multipart/form-data" style="padding: 20px 250px;">
<div class="col-md-6 col-xs-12 mob-pad0 padd-right60">
<div class="form-horizontal">
<div class="form-group">
<label for="int_exp">Total Experience</label>
<select class="form-control border-radius0" name="int_exp" id="int_exp" tabindex="2" required="required">
<option value="">Select</option>
Dropdown Using Ajax
<option value="15+">15+</option>
</select>
</div>
<div class="form-group">
<label for="txtFunctionalArea">Functional Area</label>
<select class="form-control border-radius0" name="txtFunctionalArea" id="txtFunctionalArea" tabindex="3" required="required">
<option value="">Select</option>
<option value="32">IT Software- Application Programming / Maintenance </option>
<option value="37">IT Software- Network Administration / Security </option>
</select>
</div>
<div class="form-group">
<label for="txtRole2">Desired Role</label>
<select class="form-control border-radius0" name="txtRole2" id="txtRole2" tabindex="6" required="required">
<option value="">Select</option>
Dropdown Using Ajax
</select>
</div>
</div>
</div>
<div class="col-md-6 col-xs-12 mob-pad0 padd-right60">
<div class="form-horizontal">
<div class="form-group">
<label for="company">Current Company</label>
<input name="company" id="company" type="text" placeholder="Current Company" class="form-control border-radius0" required="required" tabindex="5"/>
</div>
<div class="form-group">
<label for="txtRole">Current Role</label>
<select class="form-control border-radius0" name="txtRole" id="txtRole" tabindex="4" required="required">
<option value="">Select</option>
Dropdown Using Ajax
</select>
</div>
<div class="form-group">
<label for="resume">Resume (PDF/DOC)</label>
<input type="file" name="file" id="resume" class="form-control border-radius0" required="required" accept=".pdf,.doc, .docx" onchange="validate_fileupload(this);">
</div>
</div>
</div>
<input type="hidden" id="csrfToken" name="_token" value="{{ csrf_token() }}">
<div class="col-sm-12 col-xs-12 mob-pad0 text-center padd30">
<input type="submit" id="submitbtn_2" value="Get Started" class="inputButton btn btn-success"/>
</div>
</form>
Any help will be appreciated, thanks.

Thanks Guys for your inputs, i got the solution on the following URL:
MethodNotAllowedException
And made two changes in my code:
one in route, changed method to any
and one in form, changed post method to PUT.

Related

Not getting error but data was not stored in database in laravel 8

Hello everyone i'm actually stuck for hours because of this, im new to laravel and idk whats wrong with my code and there is no actual message error, please help me
This my store function
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'jenis_id' => 'required',
'detjenis_id' => 'required',
'email' => 'required',
'message' => 'required',
]);
$asep = $request->name;
dd($asep);
$order = new DataOrder();
$order->name = $request->name;
$order->jenis_id = $request->jenis_id;
$order->detjenis_id = $request->detjenis_id;
$order->email = $request->number;
$order->message = $request->message;
$order->save();
//return back()->with('alert-success', '<script> window.onload = swal("Sukses!", "Data telah terkirim!", "success")</script>');
// if ($order->save()) {
// return redirect(route('home'))->with('alert-success', '<script> window.onload = swal("Sukses!", "Data telah terkirim!", "success")</script>');
// } else {
// return redirect(route('home'))->with('alert-success', '<script> window.onload = swal("Oops !" , "Data gagal terkirim!!" , "error")</script>');
// }
}
This my blade code
<form action="{{route('order.store')}}" method="POST">
{{csrf_field()}}
<div class="tm-section-wrap bg-white">
<section id="talk" class="row tm-section">
<div class="col-xl-6 mb-5">
<div class="tm-contact-form-wrap">
<div class="tm-contact-form">
<div class="form-group">
<input type="text" id="name" name="name"
class="form-control rounded-0 border-top-0 border-right-0 border-left-0"
placeholder="Nama anda..." required="" />
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Kebutuhan</label>
<select name="jenis_id" class="form-control" id="jenis_id">
<option value="" disabled selected>Pilih dibawah ini:</option>
#foreach ($jenis as $j)
<option value="{{$j->id}}">{{$j->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Detail</label>
<select name="detjenis_id" class="form-control" id="detjenis_id">
</select>
</div>
<div class="form-group">
<input type="number" id="number" name="number"
class="form-control rounded-0 border-top-0 border-right-0 border-left-0"
placeholder="Nomor HP" required="" />
</div>
<div class="form-group">
<textarea rows="4" id="message" name="message"
class="form-control rounded-0 border-top-0 border-right-0 border-left-0"
placeholder="Message..." required=""></textarea>
</div>
<div class="form-group mb-0">
<button type="submit" class="btn rounded-0 d-block ml-auto tm-btn-primary">
SEND
</button>
</div>
</div>
</div>
</div>
</section>
</div>
and my route setup
Route::get('/testcrud', 'HomeController#testcrud')->name('testcrud');
Route::resource('SAS/order', 'DataOrderController');
Thank you if there anyone can help me with this problem, i'm really appreciate that.
As I can see, There is email field is missing in your form and you are using :
'email' => 'required'
Thats why data is not saving in database. For displaying validation error you can check here
are you sure that you already put all the field name,jenis_id,detjenis_id,email,message
in the fillable array in the model?
or if you don't want to bother doing that? you can just create a empty
protected $guarded variable on model.
And are you sure about the field? because i see you put number on email field.

ErrorException Trying to get property of non-object laravel

umm hello.
Im new in laravel and i want to create a program for list of workers.
I'm trying to access this route:
http://127.0.0.1:8000/posts/create
and there's error message.
ErrorException
Trying to get property '{"role":"pegawai","name":"asdasdasdasd1","email":"1asdad#ifocaproject.com","updated_at":"2020-05-11T18:26:31.000000Z","created_at":"2020-05-11T18:26:31.000000Z","id":7}' of non-object
this is my controller.
public function create(Request $request)
{
$user = new \App\User;
$user->role = 'pegawai';
$user->name = $request['nama_pegawai'];
$user->email = $request['email'];
$user->password = bcrypt('rahasia');
$user->remember_token = Str::random(60);
$user->save();
$request ->request->add(['user_id'-> $user->id]);
$pegawai = \App\Pegawai::create($request->all());
return redirect('/pegawai')->with('sukses','Data Berhasil Di-input');
}
and this is my blade.
<div class="modal-body">
<form action="/pegawai/create" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label for="exampleFormControlInput1">Nama Pegawai</label>
<input name="nama_pegawai" type="text" class="form-control"
id="exampleFormControlInput1" placeholder="Joni">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Email</label>
<input name="email" type="text" class="form-control"
id="exampleFormControlInput1" placeholder="eve#ifocaprojec.com">
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Jenis Kelamin</label>
<select name="jenis_kelamin" class="form-control" id="exampleFormControlSelect1">
<option value="Laki-Laki">Laki-laki</option>
<option value="Perempuan">Perempuan</option>
<option value="-none-">-none-</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Umur</label>
<input name="umur" type="text" class="form-control" placeholder="Cth:21">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Agama</label>
<input name="agama" type="text" class="form-control" placeholder="Cth:Islam">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Alamat</label>
<textarea name="alamat" class="form-control" rows="3"></textarea>
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Divisi</label>
<select name="divisi" class="form-control">
<option value="Inbound">Inbound</option>
<option value="Outbound">Outbound</option>
</select>
</div>
</div>
table user:
table pegawai:
What Am I missing? Any help would be greatly appreciated, Thanks.
And I'm sorry, I'm not very good at English.
You may have typo in code.
Here it must be => instead of ->:
$request->request->add(['user_id' => $user->id]);
I believe you need to reload data from DB after ->save():
.......
$user->save();
$request ->request->add(['user_id'-> $user->fresh()->id]);

One page CRUD form operation (Laravel6)

I have a table in my database with contact details. On my form, I have a Dropdown which displays the names of people, and which, once I click on the name, fills in the fields with the data (ajax).
The problem happens when I want to perform operations on the form data.
For example, I click on "M Bram Manu" (id = 1) in the Dropdown. My Ajax will fill out my form with the details of this contact.
But when I want to update, delete or add a new contact, it doesn't work properly.
So, if I click on "delete", it not delete the contact I choose but the last contact of the dropdown list. Why???
So I think my link retrieves the last ID from my dropdown, so I decided to put an hidden Input with the value of the contact ID that appears in the form. But I don't know how to retrieve this value to define it as the ID to send to the controller.
Dropdown bar and link button :
<form class="col-md-9">
<label class="col-md-2">Rechercher : </label>
<select class="form-control select2 col-md-7" id="selInscrit" name="selInscrit" onchange="selectID()">
<option value="0" selected="selected"></option>
#foreach($inscrit as $inscrits)
<option value="{{$inscrits->INS_ID}}">{{$inscrits->INS_CIVILITE}} {{$inscrits->INS_NOM}} {{$inscrits->INS_PREN}} {{$inscrits->INS_NUM_RUE}} {{$inscrits->INS_Rue}} </option>
#endforeach
</select>
</form>
<div class="btn-group btn-group-sm col-md-3" role="group">
<form action="" method="GET">
<button type="submit" class="btn btn-secondary btn-sm">Edit</button>
</form>
<button type="submit" form="registerForm" formmethod="POST" formaction="{{ route('inscrits.store') }}" class="btn btn-secondary btn-sm">Save</button>
<button type="submit" form="registerForm" formmethod="POST" formaction="{{ route('inscrits.update') }}" class="btn btn-secondary btn-sm">Update</button>
<form action="{{ route('inscrits.destroy') }}" method="POST">
<input id="INS_ID" name="INS_ID" value="" type="hidden">
#method('DELETE')
#csrf
<button type="submit" class="btn btn-secondary btn-sm">Delete </button>
</form>
</div>
Ajax for dropdown :
<script>
$('#selInscrit').change(function() {
var id = $(this).val();
var url = '{{ route("inscrits.show", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (response != null) {
$('#INS_ID').val(response.INS_ID);
$('#INS_CIVILITE').val(response.INS_CIVILITE);
$('#INS_NOM').val(response.INS_NOM);
$('#INS_PREN').val(response.INS_PREN);
$('#INS_NAISS').val(response.INS_NAISS);
$('#INS_AGE').val(response.INS_AGE);
$('#INS_NUM_RUE').val(response.INS_NUM_RUE);
$('#INS_Rue').val(response.INS_Rue);
$('#INS_TEL1').val(response.INS_TEL1);
$('#INS_OBS').val(response.INS_OBS);
$('#INS_DATE').val(response.INS_DATE);
$('#INS_TEL2').val(response.INS_TEL2);
}
}
});
});
Route :
// INSCRITS
/ route for index
Route::get('/inscrits', 'InscritController#index')->name('inscrits.index');
// route for dropdown bar
Route::get('/inscrits/show/{id}', 'InscritController#show')->name('inscrits.show');
// route for update
// Route::match(['put', 'patch'], '/inscrits/update','InscritController#update')->name('inscrits.update');
Route::post('/inscrits/update','InscritController#update')->name('inscrits.update');
// route for store
Route::post('/inscrits/store', 'InscritController#store')->name('inscrits.store');
//route for delete
Route::delete('/inscrits/destroy', 'InscritController#destroy')->name('inscrits.destroy');
Form :
<form id="registerForm">
#csrf
<div class="form-group row">
<div class="col-lg-1">
<label for="INS_CIVILITE">Civilité</label>
<select class="form-control form-control-sm" id="INS_CIVILITE" name="INS_CIVILITE">
<option value="" selected="selected"></option>
<option value="Mme">Mme</option>
<option value="Mlle">Mlle</option>
<option value="M.">M.</option>
</select>
</div>
<div class="col-lg-4">
<label for="INS_NOM">Nom</label>
<input class="form-control form-control-sm" id="INS_NOM" name="INS_NOM" value="" type="text">
</div>
<div class="col-lg-3">
<label for="INS_PREN">Prénom</label>
<input class="form-control form-control-sm" id="INS_PREN" name="INS_PREN" value="" type="text">
</div>
<div class="col-lg-2">
<label for="INS_NAISS">Année Naiss</label>
<input class="form-control form-control-sm" id="INS_NAISS" name="INS_NAISS" value="" type="text">
</div>
<div class="col-lg-2">
<label for="INS_AGE">Age</label>
<input class="form-control form-control-sm" id="INS_AGE" name="INS_AGE" value="" type="text">
</div>
</div>
<div class="form-group row">
<div class="col-lg-1">
<label for="INS_NUM_RUE"># Rue</label>
<input class="form-control form-control-sm" id="INS_NUM_RUE" name="INS_NUM_RUE" value="">
</div>
<div class="col-lg-9">
<label for="INS_Rue">Libellé voie</label>
<select class="form-control form-control-sm" id="INS_Rue" name="INS_Rue">
#foreach($rue as $rues)
<option value="{{$rues->RUE_NUM}}">{{$rues->RUE_NOM}} ({{$rues->RUE_Type}})</option>
#endforeach
</select>
</div>
<div class="col-lg-2">
<label for="INS_TEL1">Téléphone 1</label>
<input class="form-control form-control-sm" id="INS_TEL1" name="INS_TEL1" value="" type="text">
</div>
</div>
<div class="form-group row">
<div class="col-lg-8">
<label for="INS_OBS">Observation</label>
<input class="form-control form-control-sm" id="INS_OBS" name="INS_OBS" value="" type="text">
</div>
<div class="col-lg-2">
<label for="INS_DATE">Date d'inscription</label>
<input class="form-control form-control-sm" id="INS_DATE" name="INS_DATE" value="" type="text">
</div>
<div class="col-lg-2">
<label for="INS_TEL2">Téléphone 2</label>
<input class="form-control form-control-sm" id="INS_TEL2" name="INS_TEL2" value="" type="text">
</div>
</div>
<input id="INS_LIEU" name="INS_LIEU" value="WEB" type="hidden">
<input id="INS_EID" name="INS_EID" value="" type="hidden">
</form>
The controller :
public function index()
{
$inscrit = Inscrit::all();
return view('index', compact('inscrit'));
}
public function store(Request $request)
{
$storeData = $request->validate([
'INS_CIVILITE' => 'max:15',
'INS_NOM' => 'max:50',
'INS_PREN' => 'max:50',
'INS_NUM_RUE' => 'max:8',
'INS_TEL1' => 'max:10',
'INS_TEL2' => 'max:10',
'INS_AGE' => 'numeric',
'INS_OBS' => 'max:255',
'INS_Rue' => 'max:255',
'INS_DATE' => 'max:255',
'INS_NAISS' => 'max:255',
]);
$inscrit = Inscrit::create($storeData);
return redirect('/inscrits')->with('completed', 'Nouvel inscrit !');
}
public function show($id = 0)
{
$data = Inscrit::where('INS_ID', $id)->first();
return response()->json($data);
}
public function edit($id)
{
$inscrit = Inscrit::findOrFail($id);
return view('index', compact('inscrit'));
}
public function update(Request $request, $id)
{
$updateData = $request->validate([
'INS_CIVILITE' => 'max:15',
'INS_NOM' => 'max:50',
'INS_PREN' => 'max:50',
'INS_NUM_RUE' => 'max:8',
'INS_TEL1' => 'max:10',
'INS_TEL2' => 'max:10',
'INS_AGE' => 'numeric',
'INS_OBS' => 'max:255',
'INS_Rue' => 'max:255',
'INS_DATE' => 'max:255',
'INS_NAISS' => 'max:255',
]);
$id = request()->input('INS_EID');
Inscrit::where('INS_ID', $id)->update($updateData);
return redirect('/inscrits')->with('completed', 'inscrit mis à jour');
}
public function destroy($id)
{
$id = request()->input('INS_ID');
$inscrit = Inscrit::where('INS_ID', $id)->delete();
return redirect('/inscrits')->with('completed', 'inscrit supprimé');
}
The form
Database
Something like :
public function edit ($id) {
$inscritContent = Inscrit::where('id', $id)->firstOrFail();
return view('admin.inscrit.edit.form', [
'content' => $iscritContent
]);
}
public function update($id, Request $req) {
$inscrit = Inscrit::findOrFail($id);
$inscrit->update($req->all());
return redirect(route('admin.inscrit.index'));
}
admin.inscrit.edit.form and admin.inscrit.index are blade template

(1/1) ErrorException Undefined index: id in ClientController.php (line 81)

I am not sure why I am getting this error. Here is the method in the ClientController.
protected function updateOneStudent($parameters)
{
$studentId = $parameters['id'];
return $this- >performPutRequest("https://lumenapi.juandmegon.com/students/{$studentId}", $parameters);
}
Basically I am trying to update a selected student. Below is the update form.
#extends('layouts.master')
#section('content')
<form action="{{url('/student/update')}}" method="POST" role="form">
{{ csrf_field() }}
{{method_field('PUT')}}
<legend>Create a Student</legend>
<div class="form-group">
<label for="">Name</label>
<input type="text" class="form-control" name="name" value="{{$student->name }}"required="required">
</div>
<div class="form-group">
<label for="">Address</label>
<input type="text" class="form-control" name="address" value="{{$student->address }}" required="required">
</div>
<div class="form-group">
<label for="">Phone</label>
<input type="text" class="form-control" name="phone" value="{{$student->phone }}" required="required">
</div>
<div class="form-group">
<label for="">Career</label>
<select name="career" class="form-control" required="required">
<option>Select a Career</option>
<option value="math"{{$student->career == 'math' ? 'selected' : ''}}>Math</option>
<option value="physics"{{$student->career == 'physics' ? 'selected' : ''}}>Physics</option>
<option value="engineering"{{$student->career == '' ? 'engineering' : ''}}>Engineering</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Update Student</button>
</form>
#endsection
The request I was sending was wrong. The error was in the StudentController.
I had
public function getUpdateStudent()
{
$students = $this->obtainAllStudents;
return view('students.select-student', ['students'=> $students]);
}
It it should have been
public function getUpdateStudent()
{
$students = $this->obtainAllStudents();
return view('students.select-student', ['students'=> $students]);
}
I missed the brackets to call the getUpdateStudent. Sorry guys I did not show this code earlier.

post multiple fields with same name

I have a form by multiple field. In this form i can add multiple group field by prese a button via javascript. To understand exactly what I mean please see fiddle:
https://jsfiddle.net/alihesari/060ym890/2/
How to get all added fields by php and insert theme in mysql after submit?
<fomr action="">
<button type="button" id="add_hotel" class="btn btn-primary">
Add Hotel</button>
<button type="button" id="remove_hotel" class="btn btn-warning">Remove Hotel</button>
<ul class="hotels_ul">
<li class="hotel_li">
<div class="row">
<div class="col-md-10">
<div class="form-group">
<label for="hotel_name[]">Hotel Name:</label>
<input type="text" name="hotel_name[]" id="hotel_name[]" class="form-control" placeholder="Hotel Name">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="hotelRate[]">Hotel Rate: </label>
<select name="hotelRate[]" id="hotelRate[]" class="form-control">
<option value=""></option>
<option value="متل">متل</option>
<option value="یک ستاره">یک ستاره</option>
<option value="دو ستاره">دو ستاره</option>
<option value="سه ستاره">سه ستاره</option>
<option value="سه ستاره تاپ">سه ستاره تاپ</option>
<option value="چهار ستاره">چهار ستاره</option>
<option value="چهار ستاره تاپ">چهار ستاره تاپ</option>
<option value="پنج ستاره">پنج ستاره</option>
<option value="پنج ستاره تاپ">پنج ستاره تاپ</option>
<option value="هفت ستاره">هفت ستاره</option>
<option value="هتل آپارتمان">هتل آپارتمان</option>
</select>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room1[]">Room 1</label>
<input name="room1[]" id="room1[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room2[]">Room 2</label>
<input name="room2[]" id="room2[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room3[]">Room 3</label>
<input name="room3[]" id="room3[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room4[]">Room 4</label>
<input name="room4[]" id="room4[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-20">
<div class="form-group">
<label for="desc[]">Description</label>
<textarea class="form-control" name="desc[]" id="desc[]" placeholder="Description"></textarea>
</div>
</div>
</div>
</li>
</ul>
<input type="submit" value="submit">
</form>
Here's an example of how you can handle the forms with both JS and PHP.
(if the JS example here doesn't work, see https://jsfiddle.net/n6kzxj4m/)
$(function() {
$(".add").on('click', function(e) {
$($(".hotel").last().clone(true, true)).insertAfter($(".hotel").last());
// reset new items
$(".hotel").last().find(':input:not(select)').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$(".hotel").last().find('[select]').prop('selectedIndex', 0);
$(".hotel").last().find(':checkbox, :radio').prop('checked', false);
});
$(".remove").on('click', function(e) {
$(this).parents(".hotel").remove();
});
$("form").on('submit', function(e) {
e.preventDefault();
var $form = $(this);
$("#output").html($form.serializeJSON());
});
});
// plugin below only for debug on jsfiddle
/**
* jQuery serializeObject
* #copyright 2014, macek <paulmacek#gmail.com>
* #link https://github.com/macek/jquery-serialize-object
* #license BSD
* #version 2.4.5
*/
!function(e,r){if("function"==typeof define&&define.amd)define(["exports","jquery"],function(e,i){return r(e,i)});else if("undefined"!=typeof exports){var i=require("jquery");r(exports,i)}else r(e,e.jQuery||e.Zepto||e.ender||e.$)}(this,function(e,r){function i(e,i){function n(e,r,i){return e[r]=i,e}function a(e,r){for(var i,a=e.match(t.key);void 0!==(i=a.pop());)if(t.push.test(i)){var o=s(e.replace(/\[\]$/,""));r=n([],o,r)}else t.fixed.test(i)?r=n([],i,r):t.named.test(i)&&(r=n({},i,r));return r}function s(e){return void 0===h[e]&&(h[e]=0),h[e]++}function o(e){switch(r('[name="'+e.name+'"]',i).attr("type")){case"checkbox":return"on"===e.value?!0:e.value;default:return e.value}}function u(r){if(!t.validate.test(r.name))return this;var i=a(r.name,o(r));return c=e.extend(!0,c,i),this}function f(r){if(!e.isArray(r))throw new Error("formSerializer.addPairs expects an Array");for(var i=0,t=r.length;t>i;i++)this.addPair(r[i]);return this}function d(){return c}function l(){return JSON.stringify(d())}var c={},h={};this.addPair=u,this.addPairs=f,this.serialize=d,this.serializeJSON=l}var t={validate:/^[a-z_][a-z0-9_]*(?:\[(?:\d*|[a-z0-9_]+)\])*$/i,key:/[a-z0-9_]+|(?=\[\])/gi,push:/^$/,fixed:/^\d+$/,named:/^[a-z0-9_]+$/i};return i.patterns=t,i.serializeObject=function(){return this.length>1?new Error("jquery-serialize-object can only serialize one form at a time"):new i(r,this).addPairs(this.serializeArray()).serialize()},i.serializeJSON=function(){return this.length>1?new Error("jquery-serialize-object can only serialize one form at a time"):new i(r,this).addPairs(this.serializeArray()).serializeJSON()},"undefined"!=typeof r.fn&&(r.fn.serializeObject=i.serializeObject,r.fn.serializeJSON=i.serializeJSON),e.FormSerializer=i,i});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="#">
<fieldset class="hotel">
<legend>Add a hotel</legend>
<p><label>Hotel: <input type="text" name="hotel[name][]" /></label></p>
<p><label>Rate: <select name="hotel[rate][]"><option>123</option><option>456</option></select></label></p>
<p><input type="button" class="add" value="Add hotel" /> <input type="button" class="remove" value="Remove this hotel" /></p>
</fieldset>
<p><input type="submit" value="Search!" /></p>
</form>
<pre id="output"></pre>
Then, for the PHP handling, you can do:
<?php
if(!empty($_POST)) {
// handle items. $key is the index.
foreach($_POST['hotel']['name'] as $key => $hotel) {
$name = $hotel;
$rate = $_POST['hotel']['rate'][$key];
echo "Name: $name<br>Rate: $rate<hr>";
}
}
NOTE: You may want to check to ensure the number of items in $_POST['hotel']['name'] match the number of items in $_POST['hotel']['rate']. This method may not be ideal, and you may want to assign an ID per hotel row item via JS. But this is a basic approach to your question.

Categories