Making a PUT without refreshing the page - php

I have a blade form in Laravel
{!! Form::open(array('url' => '/'.$cpe_mac.'/device/'.$device_mac.'/update', 'class' => 'form-horizontal', 'role' =>'form','method' => 'PUT')) !!}
<span class="pull-left">
<div class="col-sm-6">
<p>Downlink </p>
<select type="text" class="form-control" name="max_down" >
#foreach ($rate_limit as $key => $value)
<option value="{{$value or ''}}">{{$value or ''}} Kbps</option>
#endforeach
</select>
</div>
<div class="col-sm-6">
<p>Uplink</p>
<select type="text" class="form-control" name="max_up" >
#foreach ($rate_limit as $key => $value)
<option value="{{$value or ''}}">{{$value or ''}} Kbps</option>
#endforeach
</select>
</div>
</span><br>
{!! Form::hidden('cpe_mac', $cpe_mac)!!}
{!! Form::hidden('device_mac', $device_mac)!!}
<span class="pull-right">
<button class="saveRateLimitBTN btn btn-xs btn-info pull-right">Save</button>
</span>
{!! Form::close();!!}
I want to be make a Ajax HTTP PUT without refresh my page.
How should my form look like ?
Right now, it keep redirecting me to url/update, and then redirecting it back.
How do I send all those data to my controller in the background ?
Any hints / suggestion on this will be a huge helps !

Usually I place my forms in a modal popup with a data-dismiss button that will simply close after you hit submit and run everything in the background.
For your case, after hitting submit without refreshing the page after hitting the submit button would seem a bit odd wouldn't it?
However here's a bit of jQuery to get you going either way:
$("#mySubmitButton").on('click', function(event){
var form = '#myForm';
$.post($(form).attr('action'),$(form).serialize());
});
Add an ID to your form:
{!! Form::open(array('url' => '/'.$cpe_mac.'/device/'.$device_mac.'/update', 'class' => 'form-horizontal', 'role' =>'form','method' => 'PUT', 'id' => 'myForm')) !!}
Add an ID to your button:
<button id="mySubmitButton" class="saveRateLimitBTN btn btn-xs btn-info pull-right">Save</button>
Add a TYPE to your button (to prevent it from submitting/refreshing);
<button type="button" id="mySubmitButton" class="saveRateLimitBTN btn btn-xs btn-info pull-right">Save</button>
If your routes are properly setup to lead to your controller then all your form input variables are now accessible via $request or Input:
public function processForm(Request $request)
{
$variable1 = $request->input('myforminputname1');
$variable2 = $request->input('myforminputname2');
// Or get it through Input
$variable1 = \Input::get('myforminputname1');
$variable2 = \Input::get('myforminputname2');
}

Related

Get the Old input of googleMap in update form

Am building a form that the user will be able to provide his information and also provide where he want the bus to pick him up , so am using google Map Api , so that he can provide coordinates , this is done .
but now in the update form i cant get the Coordinates values from User Object so that i can update them ,
this is the result of User::first() "dummy data btw"
{"id":1,"name":"Hady2","email":"Hady2#mtc.com","created_at":"2017-08-24 00:25:19","updated_at":"2017-08-24 00:25:19","MobileNo":"111111","Age":12,"Gender":2,"OrganizationId":1,"Location":"30.03914,31.081119","CheckInLocation":"30.4414,31.00019","CheckOutLocation":"30.02914,31.111119","BusId":1}
u will see up the coordinates variables , i want to use them so that they appear in their fields in the update form , and then i able to update them,
update form code :-
this is start form code :-
{!! Form::model($user,['route'=>['users.update',$user->id], 'method'=> 'PUT']) !!}
this a user name tag , to show u how i get the old value to the user name input
{!!Form::text('name','',array('required' => 'required', 'placeholder' => 'Name', 'class'=>'form-control'))!!}-->
{!! Form::text('name',$user->name, [
'class' => 'form-control',
'placeholder' => 'Name',
'required',
'id' => 'name',
'data-parsley-required-message' => 'Name is required',
'data-parsley-trigger' => 'change focusout'
]) !!}
notice $user->name
the problem is i cant retrieve coordinates variables and put there values in the field of the update form so when i use $user->location or $user->CheckInLocation ,as u can see in the object above , it bring me nothing ,
image show the form update coordinates fields
this is the tag for coordiantes field in update form :-
<div class="form-group">
<label class="control-label col-md-2" for="Locations">Locations</label>
<div class="col-md-10">
<button id="stop_btn" disabled="disabled" class="btn btn-default" onclick="locationClick(); this.disabled = 'disabled';">Location</button>
<button id="pick_btn" class="btn btn-info" onclick="pickClick(); this.disabled = 'disabled';">Pickup Location</button>
<button id="drop_btn" class="btn btn-danger" onclick="dropClick(); this.disabled = 'disabled'; {{ $user->CheckOutLocation }}">Dropoff Location</button>
<div id="map" value="{{ $user->CheckOutLocation }}"></div>
</div>
</div>
so can any one help me to figure how can i make old values of coordintes appear in their fields of update form , thanks in advance , i hope every thing is clear.

MethodNotAllowedHttpException in RouteCollection.php line 218: laravel 5.4

i want to add new law details with a form, this form has two buttons like update and cancel.
when i hit on cancel button the form gets cancelled and is redirected to previous page, and when i hit update button without filling form details it asks for validation.
after filling all required details of form, when i hit update button it throws me error as MethodNotAllowedHttpException in RouteCollection.php line 218:
my form is this:
{!! Form::open(array('url' => 'admin/companymaster/updateLocation', 'id'=>'updatelocations', 'class' => 'form-horizontal create_form', 'files' => true)) !!}
<input type="hidden" value="{{$value->id}}" name="company_master_id">
<div id="sublaws_content1"></div>
<div id="save" style="display:none; margin-bottom: 20px;">
<button type="submit" class="btn btn-success" id="senddatepicker">Update</button>
<a class="btn red" href="{{ URL::to('admin/companymaster/'.$company_master->id) }}">Cancel</a>
</div>
</form>
my route is:
Route::post('admin/companymaster/updatelocations', 'CompanyController#updateLocation');
my controller is:
public function updateLocation(){
//dd(Input::all());
/*Insert Company Law Details*/
$companydetails_id = Input::get('company_master_id');
$company_sub_laws = Input::get('company_sub_laws');
if($company_sub_laws!="")
{
$cld=0;
foreach($company_sub_laws as $rescompany_sublaws)
{
if($companydetails_id!="" && $rescompany_sublaws!="")
{
$law_reg_no = $_POST['law_reg_no'];
$sub_law_start_date = $_POST['sub_law_start_date'][$cld];
$sub_law_end_date = $_POST['sub_law_end_date'][$cld];
$companylawdetails = new CompanyLawDetails;
$companylawdetails->company_master_details_id = $companydetails_id;
$companylawdetails->company_sub_law_id = $rescompany_sublaws;
$companylawdetails->law_reg_no = $law_reg_no;
$company_sub_law_start_date = $sub_law_start_date;
$company_sub_law_end_date = $sub_law_end_date;
if($company_sub_law_end_date!="")
{
$res_company_sub_law_end_date=explode("-",$company_sub_law_end_date);
$company_sub_law_end_date=$res_company_sub_law_end_date[2]."-".$res_company_sub_law_end_date[1]."-".$res_company_sub_law_end_date[0];
$companylawdetails->law_end_date = $company_sub_law_end_date;
}
if($company_sub_law_start_date!="")
{
$res_company_sub_law_start_date=explode("-",$company_sub_law_start_date);
$company_sub_law_start_date=$res_company_sub_law_start_date[2]."-".$res_company_sub_law_start_date[1]."-".$res_company_sub_law_start_date[0];
$companylawdetails->law_start_date = $company_sub_law_start_date;
}
$companylawdetails->save();
}
$cld++;
}
}
$sublaws = CompanyLawDetails::where('company_master_details_id',$companydetails_id)->select('company_sub_law_id')->get()->toArray();
$sublaws = join(",",array_column($sublaws,'company_sub_law_id'));
$update = CompanyDetails::where('id',$companydetails_id)->update(['company_sub_laws' => $sublaws]);
//return Redirect::back();
}
when i submit my form by clicking on update button i get an error page as:
can anyone help me out with this.?
It seems that you are going on the wrong route, and you have an error on url, try this way;
Route::post('admin/companymaster/updatelocations', ['uses'=>'CompanyController#updateLocation',
'as'=>'upload.locations']);
on your blade
{!! Form::open(array('route'=> 'upload.locations', 'method'=>'post', 'id'=>'updatelocations', 'class' => 'form-horizontal create_form', 'files' => true)) !!}
<input type="hidden" value="{{$value->id}}" name="company_master_id">
<div id="sublaws_content1"></div>
<div id="save" style="display:none; margin-bottom: 20px;">
<button type="submit" class="btn btn-success" id="senddatepicker">Update</button>
<a class="btn red" href="{{ URL::to('admin/companymaster/'.$company_master->id) }}">Cancel</a>
</div>
</form>
Please add form method as 'method' => 'post',
{!! Form::open(array('url' => 'admin/companymaster/updateLocation', 'id'=>'updatelocations', 'class' => 'form-horizontal create_form', 'files' => true,'method' => 'post')) !!}
Hope you understand.
Spelling error change your url form
{!! Form::open(array('url' => 'admin/companymaster/updateLocation', 'id'=>'updatelocations', 'class' => 'form-horizontal create_form', 'files' => true)) !!}
to
{!! Form::open(array('url' => 'admin/companymaster/updatelocations', 'id'=>'updatelocations', 'class' => 'form-horizontal create_form', 'files' => true)) !!}

Two forms on same view in Laravel 4

I've tried number of solutions from other posts but still can't get it work.
I have two forms on the page(view)
{{ Form::open(array('action' => 'AdminController#shopMode')) }}
....// form fields
<button type="submit" class="btn btn-primary">Change</button>
{{ Form::close() }}
<hr/>
{{ Form::open(array('action' => 'AdminController#preferencesSubmit')) }}
....// second form fields
<button type="submit" class="btn btn-primary">Save Changes</button>
{{ Form::close() }}
Then in routes I have
Route::post('/admin/preferences', ['uses' => 'AdminController#preferencesSubmit', 'before' => 'csrf|admin']);
Route::post('/admin/preferences', ['uses' => 'AdminController#shopMode', 'before' => 'csrf|admin']);
When I hit submit button nothing change in database. Just page is refreshed and I got success message from FIRST form even if I submit second one.
Is it because url's in routes are same for both posts?
Update: First form input field:
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" <?php if ($settings['preferences_shop_mode'] == 0){ ?> checked="checked" value="1"<?php }else{ ?> value="0" <?php } ?>>
Here I check if preference is =0 to set value to 1 otherwise value = 0. In source I see that value is =1 which is correct because in database I have 0
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked="checked" value="1">
This is the controller
public function shopMode() {
$preferences = Preferences::where('preferences_id', 1)->first();
if (!$preferences) {
App::abort(404);
}
Input::merge(array_map('trim', Input::all()));
$preferences->preferences_shop_mode = Input::get('onoffswitch');
$preferences->save();
return Redirect::to('/admin/preferences')->with('message', 'Shop mode changed successfully.');
}
Any idea why isn't updated in database?
Routes are read in cascade. Since both routes have the same path, the first takes priority (an entry was found, so no further route lookup is needed).
You should split them with just different paths, for example:
Route::post('/admin/preferences/general', ['uses' => 'AdminController#preferencesSubmit', 'before' => 'csrf|admin']);
Route::post('/admin/preferences/shop', ['uses' => 'AdminController#shopMode', 'before' => 'csrf|admin']);

Prevent from submiting form several times by clicking fast in laravel

So I ran into issue, that If i click fast enough subnmit button, my form is submited several times. How can I prevent this? Token is added automatically, but it doesnt help at all I guess.
Form example:
<div class="row padding-10">
{!! Form::open(array('class' => 'form-horizontal margin-top-10')) !!}
<div class="form-group">
{!! Form::label('title', 'Title', ['class' => 'col-md-1 control-label padding-right-10']) !!}
<div class="col-md-offset-0 col-md-11">
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('body', 'Body', ['class' => 'col-md-1 control-label padding-right-10']) !!}
<div class="col-md-offset-0 col-md-11">
{!! Form::textarea('body', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="col-md-offset-5 col-md-3">
{!! Form::submit('Submit News', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
</div>
My NewsController store method:
public function store()
{
$validator = Validator::make($data = Input::all(), array(
'title' => 'required|min:8',
'body' => 'required|min:8',
));
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
News::create($data);
return Redirect::to('/news');
}
One approach is to use a click handler for the button where it first disables the button, then submits the form.
<script>
function submitForm(btn) {
// disable the button
btn.disabled = true;
// submit the form
btn.form.submit();
}
</script>
<input id="submitButton" type="button" value="Submit" onclick="submitForm(this);" />
Use PHP sessions to set a session variable (for example $_SESSION['posttimer']) to the current timestamp on post. Before actually processing the form in PHP, check if the $_SESSION['posttimer'] variable exists and check for a certain timestamp difference (IE: 2 seconds). This way, you can easily filter out multiple submits.
// form.html
<form action="foo.php" method="post">
<input type="text" name="bar" />
<input type="submit" value="Save">
</form>
// foo.php
if (isset($_POST) && !empty($_POST))
{
if (isset($_SESSION['posttimer']))
{
if ( (time() - $_SESSION['posttimer']) <= 2)
{
// less then 2 seconds since last post
}
else
{
// more than 2 seconds since last post
}
}
$_SESSION['posttimer'] = time();
}
Original POST
How to prevent multiple inserts when submitting a form in PHP?
Want to submit value of button as well and prevent double form submit?
If you are using button of type submit and want to submit value of button as well, which will not happen if the button is disabled, you can set a form data attribute and test afterwards.
// Add class disableonsubmit to your form
$(document).ready(function () {
$('form.disableonsubmit').submit(function(e) {
if ($(this).data('submitted') === true) {
// Form is already submitted
console.log('Form is already submitted, waiting response.');
// Stop form from submitting again
e.preventDefault();
} else {
// Set the data-submitted attribute to true for record
$(this).data('submitted', true);
}
});
});
Step 1: write a class name in the form tag Exp: "from-prevent-multiple-submits"
<form class="pt-4 from-prevent-multiple-submits" action="{{ route('messages.store') }}" method="POST">
#csrf
Step 2: write a class in button section
<button type="submit" id="submit" class="btn btn-primary from-prevent-multiple-submits">{{ translate('Send') }}</button>
Step 3: write this script code
(function(){
$('.from-prevent-multiple-submits').on('submit', function(){
$('.from-prevent-multiple-submits').attr('disabled','true');
})
})();

PHP Laravel - how to test if a checkbox is checked, if the value is a variable?

I'm a noob in Laravel, so please bear with me.
I'm continuing work on a friend's webpage that displays a list of items (with a checkbox beside each item). There are plenty of ways to interact with said items, such as "Delete", "Update", and the one I'm working on, "Download". There's a delete button per row/item/checkbox, so that a user can easily delete just one item. There's also a mass delete option, where the user can check multiple rows, check a "Delete" checkbox, and click on "Update". The webpage stores data on mongodb.
Supposedly, a user checks the box, clicks on Download, and a file is created and downloaded for the user.
But I'm not getting to that part yet. For now I'm having trouble even checking if the checkboxes are checked.
Here's my code:
Download Button:
<div class="col-md-1 col-md-offset-1">
{{ Form::open( array(
'url' => 'contents/download',
'role' => 'form',
'method' => 'POST',
'class' => 'form-inline'
)
) }}
<div class="form-inline" role="form">
<div class="form-group">
<input type="submit" class="btn btn-success" name="download" id="download" value="Download Selected">
</div>
</div>
{{ Form::close() }}
</div>
Here's the rows of checkboxes/items. Notice that the value of the checkbox is a variable - it corresponds to the ID of the item in the database.
#foreach($children as $child)
#if($mother->id == $child->mother_id)
<tr>
<td class="text-center">
{{--*/ $child->id /*--}}
<input type="checkbox" class="child" value="{{ $child->id }}" onclick=isSelected(this)>
</td>
<td>
<span class="glyphicon glyphicon-file"></span>
{{ ucwords($child->child) }}
</td>
<td class="text-center">
Coder
</td>
<td class="text-center">
{{ $child->updated_at }}
</td>
<td class="text-center">
{{ Form::open(array(
'url' => 'contents/delete',
'role' => 'form',
'method' => 'POST',
'class' => 'form-inline'
)
) }}
<input type="hidden" value="{{ $child->id }}" name="id">
<input type="submit" class="btn btn-danger btn-xs" name="deleteChild" value="Delete" onclick="return confirmDelete();" />
{{ Form::close() }}
</td>
</tr>
#endif
#endforeach
Controller Code:
public function postDownload()
{
$input = Input::all();
if(Input::has("child"))
{
echo $input["child"];
// Begin download
}
else
{
echo "none";
// Error - No Item selected
}
}
My understanding of Laravel is basic at best. Where did I go wrong? Or perhaps there's another approach to this?
First of all, in HTML you should give your checkboxes a name, perhaps something like items.
When you submit the form, Laravel get those data. And now if retrieve input by using Input::get('items'),
$itemIds = Input::get('items');
you will get an array whose elements are those checkboxes that were checked. This array is basically an indexed array, the structure could be like this
array(
[0] => '1', // item 1 ID
[1] => '5', // item 5 ID
[2] => '33' // item 33 ID
)
Finally, you are ready to process $itemIds however you want.
By the way, if no boxes were checked in your UI, you cannot get an array by calling Input::get('items'). Therefore, it might be better to check whether this field exists first by calling Input::has('items').
In your HTML , name the checkboxes dynamically after your item IDs.
Example , item1 , item2 etc.
Then check for selected items like this in your controller
$items = Item::all();
foreach($items as $item)
{
if($request->has('item'.$item->id)){
// item has been ticked
}
else{
// item was not ticked
}
}

Categories