This question already has answers here:
Stop form refreshing page on submit
(20 answers)
How can I prevent refresh of page when button inside form is clicked?
(16 answers)
Closed 4 years ago.
Im trying to insert data with ajax, but i got error :
Symfony \ Component \ HttpKernel \ Exception \
MethodNotAllowedHttpException
This is my form in add-gallery.blade.php:
<form method="post" action="" enctype="multipart/form-data" autocomplete="off" class="mt-4 mb-4 card p-4">
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="gallery_name">Name</label>
</div>
<div class="col-md-6 align-self-center">
<input type="text" name="gallery_name" id="gallery_name" class="form-control" placeholder="Type Gallery Name" />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="category">Category</label>
</div>
<div class="col-md-3 align-self-center">
<select class="form-control custom-select" name="category" id="category">
<option value="">Select Category</option>
<option value="Home">Home</option>
<option value="Office">Office</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="subcategory">Sub Category</label>
</div>
<div class="col-md-3 align-self-center">
<select class="form-control custom-select" name="subcategory" id="subcategory">
<option value="">Select Sub Category</option>
<option value="Interior">Interior</option>
<option value="Eksterior">Eksterior</option>
<option value="Decoration">Decoration</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="subsubcategory">Subsub Category</label>
</div>
<div class="col-md-3 align-self-center">
<select class="form-control custom-select" name="subsubcategory" id="subsubcategory">
<option value="">Select Subsub Category</option>
<option value="Room">Room</option>
<option value="Bathroom">Bathroom</option>
<option value="Kitchen">Kitchen</option>
<option value="Terrace">Terrace</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2">
<label for="gallery_image">Image</label>
</div>
<div class="col-md-10">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail w-100" style="display: none;">
<img src="http://placehold.it/1186x800" />
</div>
<div id="toAnnotate" class="fileinput-preview fileinput-exists thumbnail w-100"></div>
<div>
<span class="btn btn-xs btn-success btn-file"><span class="fileinput-new">Select image</span><span class="fileinput-exists">Change</span><input type="file" name="gallery_image" id="gallery_image"></span>
Remove
</div>
</div>
<p><small><em>Image Size : 1186px (width), 800px (height)</em></small></p>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center"> </div>
<div class="col-md-10 align-self-center">
<button type="button" class="btn btn-secondary">Cancel</button>
<button type="submit" class="btn btn-success" id="save">Save</button>
</div>
</div>
</div>
</form>
And below is my ajax in same page add-gallery.blade.php:
<script type="text/javascript">
$(document).ready(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//Save
$('#save').on('click', function () {
var gallery_name = $('#gallery_name').val();
var category = $('#category').val();
var subcategory = $('#subcategory').val();
var subsubcategory = $('#subsubcategory').val();
var gallery_image = $('#gallery_image').val();
var dataSubmit = $(this).serialize();
var top = top;
var left = left;
var file_data = $('#gallery_image').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : "{{ url('galleries/store') }}",
dataType : 'text', // what to expect back from the server
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
dataType : 'json',
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
});
</script>
This is my routes file web.php:
Route::post('galleries/store','Dashboard\GalleryController#store');
And this is my controller GalleryController.php:
public function store(Request $request){
if($request->hasFile('gallery_image')){
$fileImage = $request->file('gallery_image');
$fileImageExtension = $fileImage->extension();
$renameFileImage = 'ImageGalleries'.time().'.'.$fileImageExtension;
$pathFileImage = $fileImage->storeAs('public/galleries_documents/images_galleries', $renameFileImage); /images_articles
$galleries = new Gallery;
$points = new Point;
$galleries->name = $request->gallery_name;
$galleries->category = $request->category;
$galleries->sub_category = $request->subcategory;
$galleries->sub_subcategory = $request->subsubcategory;
$galleries->image = $renameFileImage;
$galleries->lang_id = session('lang_id');
$galleries->save();
$lastInsertId = $galleries->id;
for($i = 0; $i < count($request->node); $i++) {
$node[] = [
'node_position_top' => $request->node[$i],
'node_position_left' => $request->node[$i],
'id_gallery' => $lastInsertId,
];
$points->lang_id = session('lang_id');
}
Point::insert($node); //save to table
print_r($node[]);
exit();
}
}
Related
I have a view where I pull the data with an "onclick" of the "Asisgnar" button and when I click on the "Enviar formulario" button, an email is sent directly with the loaded data... this works perfectly, but I would like it to be sent the mail without redirecting me to another page.
My form code
<form action="{{route('contactanos.store')}}" method="POST">
{{ csrf_field() }}
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="inspector">Inspector</label>
<select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" id="inspector" for="inspector" name="inspector" >
<option selected></option>
#foreach($users as $user)
<option value="{{ $user->name }}">{{ $user->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<label for="estado">Estado</label>
<select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" id="estado" for="estado" name="estado">
<option selected></option>
<option value="Pendiente">Pendiente</option>
<option value="Coordinado">Coordinado</option>
<option value="Peritando">Derivado a inspector</option>
<option value="Baja">Baja</option>
</select>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="localidad">Localidad</label>
<input type="text" name="localidad" id="localidad" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="fechaip">Fecha IP</label>
<input type="date" name="fechaip" id="fechaip" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="siniestro">Siniestro</label>
<input type="text" name="siniestro" id="siniestro" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="inspector">Inspector</label>
<select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" id="emailperito" for="emailperito" name="emailperito" >
<option selected></option>
#foreach($users as $user)
<option value="{{ $user->email }}">{{ $user->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="email">Email taller</label>
<input type="text" name="email" id="email" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="patente">Patente</label>
<input type="text" name="patente" id="patente" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="modalidad">Tipo de inspección</label>
<input type="text" name="modalidad" id="modalidad" class="form-control" >
</div>
</div>
<input type="hidden" id="id">
<button type="submit" id="updateButton" class="btn btn-success" onclick="updateData(event)">Guardar</button>
<button type="submit" class="btn btn-primary float-right">Enviar formulario</button>
</form>
Controller Code to send mail
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
//mail
use App\Mail\ContactanosMailable;
use Illuminate\Support\Facades\Mail;
use App\Models\Siniestro;
class CoordinacionesController extends Controller
{
public function index(){
return view('contactanos.index');
}
public function store(Request $request){
$siniestro = Siniestro::paginate(1000);
$this->siniestro = $siniestro;
$email = $this->siniestro['emailperito'];
$cc = $this->siniestro['email'];
$correo = new ContactanosMailable($request->all());
Mail::to($email)->cc($cc)->send($correo);
return redirect()->route('siniestros.index');
}
}
View.blade
My view
I have tried removing the post method and removing the "return redirect()->route('sinisters.index');" of the controller, but it doesn't work.
you can do it with an ajax like this
$.ajax({
url: '{{route("your-route")}}',
method: "POST",
data: {
_token: '<?php echo csrf_token() ?>',
... // the rest of your form
}
})
Try this solution
add jquery in your blade file
jquery cdn
<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
Give class to your form
<form action="{{route('contactanos.store')}}" method="POST" class="my_form">
Change your javascript code as per below
$(document).on('submit', '.my_form', function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (response) {
if(response.success){
//handle success message
} else {
//handle error message
}
},
error: function (xhr, textStatus, errorThrown) {
console.log("ERROR");
}
});
});
change your controller->store function
public function store(Request $request){
try {
$siniestro = Siniestro::paginate(1000);
$this->siniestro = $siniestro;
$email = $this->siniestro['emailperito'];
$cc = $this->siniestro['email'];
$correo = new ContactanosMailable($request->all());
Mail::to($email)->cc($cc)->send($correo);
return response()->json([
'success' => true,
'message' => 'Your success message'
]);
} catch (\Throwable $th) {
return response()->json([
'success' => false,
'message' => 'Your error message'
]);
}
}
There are texareas in my table: "Case Description", "Case Notes", etc..
I want the case description not to show the entire textarea of more than 500 characters in the <td>...
I want it more like:
This is a case description....
When the Edit button is clicked, it pops a modal to edit the data via ajax (already done).
Here are my codes
Edit-report.php:
<!-- Start PHP While -->
<?php
$mysqli = new mysqli('localhost', 'mushref', 'Almadina1!', 'security_db')
or die('Dramatic Error: ' . mysqli_error($mysqli));
if( isset($_POST['id']) ) {
$id = $_POST['id'];
$ccc_employee = $_POST['cccEmployee'];
$IR_number = $_POST['irNumber'];
$case_type = $_POST['caseType'];
$caseLocation = $_POST['caseLocation'];
$startDate = $_POST['startDateTime'];
$endDate = $_POST['endDateTime'];
$case_description = $_POST['caseDesc'];
$action_taken = $_POST['actionsTaken'];
$details = $_POST['caseDetails'];
$notes = $_POST['caseNotes'];
$recommendation = $_POST['caseRecommendation'];
// Query to update data
$result = mysqli_query($mysqli, "UPDATE cases_reports SET
cccEmployee='$ccc_employee',
irNumber='$IR_number',
caseType='$case_type',
caseLocation='$caseLocation',
startDateTime='$startDate',
endDateTime='$endDate',
caseDesc='$case_description',
actionsTaken='$action_taken',
caseDetails='$details',
caseNotes='$notes',
caseRecommendation='$recommendation'
WHERE id='$id'");
}
$selectquery = "SELECT * FROM cases_reports";
$table = mysqli_query($mysqli, $selectquery);
$nums = mysqli_num_rows($table);
while($res = mysqli_fetch_array($table)) {
?>
<tr id="<?php echo $res['id']?>">
<td data-target="cccEmployee"><?php echo $res['cccEmployee'];?></td>
<td data-target="IR_number"><?php echo $res['irNumber'];?></td>
<td data-target="case_type"><?php echo $res['caseType'];?></td>
<td data-target="case_location"><?php echo $res['caseLocation'];?></td>
<td data-target="startDateTime"><?php echo $res['startDateTime'];?></td>
<td data-target="endtDateTime"><?php echo $res['endDateTime'];?></td>
<td data-target="case_description"><?php echo $res['caseDesc'];?></td>
<td data-target="actions_taken"><?php echo $res['actionsTaken'];?></td>
<td data-target="case_details"><?php echo $res['caseDetails'];?></td>
<td data-target="case_notes"><?php echo $res['caseNotes'];?></td>
<td data-target="case_recommendation"><?php echo $res['caseRecommendation'];?></td>
<td class="table-actions">
<a href="#" data-role="update" data-id="<?php echo $res['id']; ?>">
<i class="fas fa-edit"></i>
</a>
<!-- <a href="#!" class="table-action table-action-delete" data-toggle="tooltip" data-original-title="Delete product">
<i class="fas fa-trash"></i>
</a> -->
</td>
<td>
<div class="dropdown">
<a class="btn btn-sm btn-icon-only text-light" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-ellipsis-v"></i>
</a>
<div class="dropdown-menu dropdown-menu-right dropdown-menu-arrow">
<a class="dropdown-item" href="#">Print PDF</a>
<a class="dropdown-item" href="#">Export Excel</a>
<a class="dropdown-item" href="#">Export Access</a>
</div>
</div>
</td>
</tr>
<div class="modal fade" id="reportsModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal- modal-dialog-centered modal-" role="document">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title" id="modal-title-default"> Case Details </h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="case-data">
<div class="form-row">
<div class="col-md-6 mb-3">
<div class="form-group">
<label class="form-control-label" for="cccEmployee">CCC Employee</label>
<input type="text" class="form-control" id="cccEmployee" name="cccEmployee">
</div>
</div>
<div class="col-md-6 mb-3">
<div class="form-group">
<label class="form-control-label" for="IR_number">IR Number</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">IR#</span>
</div>
<input type="number" class="form-control" id="IR_number" name="IR_number">
</div>
</div>
</div>
<div class="col-md-6 mb-3">
<div class="form-group">
<label class="form-control-label" for="case_type">Case Type</label>
<select data-toggle="select" class="form-control" name="case_type" id="case_type">
<option value="" disabled selected>Select Case Type</option>
<option value="Accident">Accident</option>
<option value="Theft">Theft</option>
<option value="Death">Death</option>
<option value="Harrasment">Harrasment</option>
<option value="badBehaviour">Bad Behaviour</option>
<option value="Drugs">Drugs</option>
<option value="Drunk">Drunk</option>
<option value="Fight">Fight</option>
<option value="Medical">Medical</option>
<option value="illegalEntry">Illegal Entry</option>
<option value="illegalWorker">Illegal Worker</option>
<option value="Fire">Fire</option>
<option value="Electric">Electric</option>
<option value="illegalHunting">Illegal Hunting</option>
<option value="oilLeak">Oil Leak</option>
<option value="petrolLeak">Petrol Leak</option>
<option value="Kidnapping">Kidnapping</option>
<option value="Blackmail">Blackmail</option>
<option value="Misunderstanding">Misunderstanding</option>
<option value="propertyDamage">Property Damage</option>
<option value="smoke_NoFire">Smoke, No Fire</option>
<option value="stuck_InElevator">Stuck in Elevator</option>
<option value="Scooter">Scooter</option>
<option value="Drifting">Drifting</option>
<option value="LostPerson">Lost Person</option>
<option value="Fraud_Forgery">Fraud/Forgery</option>
<option value="Other">Other</option>
</select>
</div>
</div>
<div class="col-md-6 mb-3">
<div class="form-group">
<label class="form-control-label" for="case_location">Location</label>
<select class="form-control" name="case_location" id="case_location" data-toggle="select">
<option value="" disabled selected>Select Location</option>
<option value="Baylasun">Baylasun</option>
<option value="Baylasun Hotel">Baylasun Hotel</option>
<option value="AL-Waha">AL-Waha</option>
<option value="Al-Morooj">Al-Morooj</option>
<option value="Royal Green">Royal Green</option>
<option value="Beach Towers">Beach Towers</option>
<option value="Emmar Building">Emmar Building</option>
<option value="Industrial Area (East)">Industrial Area (East)</option>
<option value="Industrial Area (West)">Industrial Area (West)</option>
<option value="Hejaz Gate">Hejaz Gate</option>
<option value="Gate 3">Gate 3</option>
<option value="Marina 1">Marina 1</option>
<option value="Marina 2">Marina 2</option>
<option value="Marina 3">Marina 3</option>
<option value="Tala Garden">Tala Garden</option>
<option value="AL-Shorooq">AL-Shorooq</option>
<option value="Yam Beach">Yam Beach</option>
<option value="Sales Center">Sales Center</option>
</select>
</div>
</div>
<div class="col-md-6 mb-3">
<div class="form-group">
<label class="form-control-label" for="startDate">Start Date & Time</label>
<input class="form-control" type="datetime-local" name="startDate" id="startDateTime">
</div>
</div>
<div class="col-md-6 mb-3">
<div class="form-group">
<label class="form-control-label" for="endDateTime">End Date & Time</label>
<input class="form-control" type="datetime-local" name="endDateTime" id="endDateTime">
</div>
</div>
<div class="col-md-12 mb-3">
<div class="form-group">
<label class="form-control-label" for="case_description">Case Description</label>
<textarea class="form-control" name="case_description" id="case_description" rows="3"></textarea>
</div>
</div>
<div class="col-md-12 mb-3">
<div class="form-group">
<label class="form-control-label" for="actions_taken">Actions Taken</label>
<textarea class="form-control" name="actions_taken" id="actions_taken"></textarea>
</div>
</div>
<div class="col-md-12 mb-3">
<div class="form-group">
<label class="form-control-label" for="details">Details</label>
<textarea class="form-control" name="case_details" id="case_details"></textarea>
</div>
</div>
<div class="col-md-12 mb-3">
<div class="form-group">
<label class="form-control-label" for="case_notes">Notes</label>
<textarea name="case_notes" id="case_notes" class="form-control"></textarea>
</div>
</div>
<div class="col-md-12 mb-3">
<div class="form-group">
<label class="form-control-label" for="case_recommendation">Recommendations</label>
<textarea name="case_recommendation" id="case_recommendation" class="form-control"></textarea>
</div>
</div>
<input type="hidden" id="caseId" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<button type="button" id="save_report_changes" class="btn btn-primary">Save changes</button>
</div>
<?php } //End php While ?>
Ajax:
$(document).ready(function() {
// Append values in input fields
$(document).on('click', 'a[data-role=update]', function(){
var id = $(this).data('id');
var cccEmployee = $("#"+id).children('td[data-target=cccEmployee]').text();
var irNumber = $("#"+id).children('td[data-target=IR_number]').text();
var caseType = $("#"+id).children('td[data-target=case_type]').text();
var caseLocation = $("#"+id).children('td[data-target=case_location]').text();
var startDateTime = $("#"+id).children('td[data-target=startDateTime]').text();
var endDateTime = $("#"+id).children('td[data-target=endDateTime]').text();
var caseDesc = $("#"+id).children('td[data-target=case_description]').text();
var actionsTaken = $("#"+id).children('td[data-target=actions_taken]').text();
var caseDetails = $("#"+id).children('td[data-target=case_details]').text();
var caseNotes = $("#"+id).children('td[data-target=case_notes]').text();
var caseRecommendation = $("#"+id).children('td[data-target=case_recommendation]').text();
//Append the variables
$('#cccEmployee').val(cccEmployee);
$('#IR_number').val(irNumber);
$('#case_type').val(caseType);
$('#case_location').val(caseLocation);
$('#startDateTime').val(startDateTime);
$('#endDateTime').val(endDateTime);
$('#case_description').val(caseDesc);
$('#actions_taken').val(actionsTaken);
$('#case_details').val(caseDetails);
$('#case_notes').val(caseNotes);
$('#case_recommendation').val(caseRecommendation);
$('#caseId').val(id);
$('#reportsModal').modal('toggle');
});
//Create event to get data from fields and update.
$('#save_report_changes').click(function() {
var id = $('#caseId').val();
var cccEmployee = $('#cccEmployee').val();
var irNumber = $('#IR_number').val();
var caseType = $('#case_type').val();
var caseLocation = $('#case_location').val();
var startDateTime = $('#startDateTime').val();
var endDateTime = $('#endDateTime').val();
var caseDesc = $('#case_description').val();
var actionsTaken = $('#actions_taken').val();
var caseDetails = $('#case_details').val();
var caseNotes = $('#case_notes').val();
var caseRecommendation = $('#case_recommendation').val();
$.ajax({
url: '/edit-report',
method: 'post',
data: {
id: id,
cccEmployee: cccEmployee,
irNumber: irNumber,
caseType: caseType,
caseLocation: caseLocation,
startDateTime: startDateTime,
endDateTime: endDateTime,
caseDesc: caseDesc,
actionsTaken: actionsTaken,
caseDetails: caseDetails,
caseNotes: caseNotes,
caseRecommendation: caseRecommendation
},
success: function(response) {
$("#"+id).children('td[data-target=cccEmployee]').text(cccEmployee);
$("#"+id).children('td[data-target=IR_number]').text(irNumber);
$("#"+id).children('td[data-target=case_type]').text(caseType);
$("#"+id).children('td[data-target=case_location]').text(caseLocation);
$("#"+id).children('td[data-target=startDateTime]').text(startDateTime);
$("#"+id).children('td[data-target=endDateTime]').text(endDateTime);
$("#"+id).children('td[data-target=case_description]').text(caseDesc);
$("#"+id).children('td[data-target=actions_taken]').text(actionsTaken);
$("#"+id).children('td[data-target=case_details]').text(caseDetails);
$("#"+id).children('td[data-target=case_notes]').text(caseNotes);
$("#"+id).children('td[data-target=case_recommendation]').text(caseRecommendation);
$('#reportsModal').modal('toggle');
},
});
});
});
You can use mb_strimwidth("Hello World", 0, 10, "...");
where "Hello Word is your description"
This will return This will return Hello W....
I'm using Form Repeater in a simple HTML page, when I send the form, I only get the first values (First line).
HTML:
<div id="kt_repeater_1">
<div class="form-group row" id="kt_repeater_1">
<div data-repeater-list="product_list" class="col-lg-12">
<div data-repeater-item class="form-group row">
<div class="col-md-9">
<label>Produit:</label>
<select class="form-control selectpicker" name="product">
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
</select>
<div class="d-md-none mb-2"></div>
</div>
<div class="col-md-2">
<label>Qte:</label>
<input type="text" name="qty" class="form-control" />
<div class="d-md-none mb-2"></div>
</div>
<div class="col-md-1">
<a href="javascript:;" data-repeater-delete="" style="margin-top: 25px;" class="btn btn-sm font-weight-bolder btn-light-danger">
<i class="la la-trash-o"></i>
</a>
</div>
</div>
</div>
</div>
<div class="form-group row" style="margin-top: -20px;">
<label class="col-lg-2 col-form-label text-right"></label>
<div class="col-lg-12">
<a href="javascript:;" data-repeater-create="" class="btn btn-sm font-weight-bolder btn-light-primary">
<i class="la la-plus"></i>Add Product
</a>
</div>
</div>
</div>
JS:
var KTFormRepeater = function() {
// Private functions
var demo1 = function() {
$('#kt_repeater_1').repeater({
initEmpty: false,
defaultValues: {
},
show: function() {
$(this).slideDown();
},
hide: function(deleteElement) {
$(this).slideUp(deleteElement);
},
});
}
return {
// public functions
init: function() {
demo1();
}
};
}();
$(document).ready(function() {
KTFormRepeater.init();
});
PHP when I print_r($_POST[]) AND send 2 Lines
(Product 1, QTY: 10 - Product 1, QTY: 20):
"product_list":[{"product":"1","qty":"10"}]
Can anyone help me with this, please?
correct :
name="product[0][qty]"
not correct
name="qty"
I am a little late here but I am uploading a complete solution to how to add form repeater in your page if you are using metronic keen theme version 8.*.
< script >
var hostUrl = "assets/"; < /script> <
script src = "{{ asset('assets/Metronic-Theme/plugins/global/plugins.bundle.js') }}" > < /script> <
script src = "{{ asset('assets/Metronic-Theme/js/scripts.bundle.js') }}" > < /script> <
script src = "{{asset('assets/Metronic-Theme/plugins/custom/prismjs/prismjs.bundle.js')}}" > < /script> <
script src = "{{asset('assets/Metronic-Theme/plugins/custom/formrepeater/formrepeater.bundle.js')}}" > < /script> <
script src = "{{asset('assets/Metronic-Theme/js/custom/documentation/documentation.js')}}" > < /script> <
script src = "{{asset('assets/Metronic-Theme/js/custom/documentation/search.js')}}" > < /script>
<
script >
"use strict";
var KTFormRepeaterBasic = {
init: function() {
$("#kt_docs_repeater_basic").repeater({
initEmpty: !1,
defaultValues: {
"text-input": "foo"
},
show: function() {
$(this).slideDown()
},
hide: function(t) {
$(this).slideUp(t)
}
})
}
};
KTUtil.onDOMContentLoaded((function() {
KTFormRepeaterBasic.init()
}));
<
/script>
<link href="{{ asset('assets/Metronic-Theme/plugins/custom/datatables/datatables.bundle.css') }}" rel="stylesheet" type="text/css" /><link href="{{ asset('assets/Metronic-Theme/plugins/global/plugins.bundle.css') }}" rel="stylesheet" type="text/css" /><link href="{{ asset('assets/Metronic-Theme/css/style.bundle.css') }}" rel="stylesheet" type="text/css" />
<!--begin::Repeater-->
<div id="kt_docs_repeater_basic">
<!--begin::Form group-->
<div class="form-group">
<div data-repeater-list="kt_docs_repeater_basic">
<div data-repeater-item>
<div class="form-group row">
<div class="col-md-3">
<label class="form-label">Accessory</label> {{-- <input type="email" class="form-control mb-2 mb-md-0" placeholder="Enter full name" name="name1" id="check1" /> --}}
<select class="form-control mb-2 mb-md-0" placeholder="Select Accesory" id="sel1" name="accessory">
<option value="" disabled selected>Select Accessory</option>
#foreach ($shop->getCrmSetting('Accessory',$shop->id) as $item)
<option>{{$item->accessory}}</option>
#endforeach
</select>
</div>
<div class="col-md-3">
<label class="form-label">Accessory Serial Number</label>
<input type="text" class="form-control mb-2 mb-md-0" placeholder="Enter Accessory Serial Number" name="accessoryserialno" />
</div>
<div class="col-md-4">
<a href="javascript:;" data-repeater-delete class="btn btn-sm btn-light-danger mt-3 mt-md-8">
<i class="la la-trash-o"></i>Delete
</a>
</div>
</div>
</div>
</div>
</div>
<!--end::Form group-->
<!--begin::Form group-->
<div class="form-group mt-5">
<a href="javascript:;" data-repeater-create class="btn btn-light-primary">
<i class="la la-plus"></i>Add
</a>
</div>
<!--end::Form group-->
</div>
<!--end::Repeater-->
and now the code from backened server
just to tell how you can retrieve data.
Remember to add name="" attribute to html element to retrieve data in backend server.as i have added it to select and input elements.
foreach ($request->kt_docs_repeater_basic as $key => $value) {
CustomerAccessory::create([
'order_id' => $order->id,
'accessory' => $value['accessory'],
'accessoryserialno' => $value['accessoryserialno'],
]);
}
this project is in laravel so code is from controller.
In this way you can loop through the form repeater
and then can store and use the values any way you like in the backend.
You can make changes according to your theme and layout.
but you have to add the form repeater scripts and css and jquery.
and if you only want to use first row from foreach you can either put a break statement or you can do this.
$request->kt_docs_repeater_basic[0]['accessory'];
$request->kt_docs_repeater_basic[0]['accessoryserialno'];
or
foreach ($request->kt_docs_repeater_basic as $key => $value) {
CustomerAccessory::create([
'order_id' => $order->id,
'accessory' => $value['accessory'],
'accessoryserialno' => $value['accessoryserialno'],
]);
break;
}
I am using the Croppie script to edit images before uploading to my server.
https://foliotek.github.io/Croppie/
The problem is Croppie encodes the cropped image in a base64 format. I have created a hidden input and attached the base64 string. I need to know how to grab the string so i can decode it and post it with my form.
I have tried so many methods but i am stuck. Any help will be appreciated
Controller
$post = new Post;
$post->post_category_id = $request->post_category_id;
$post->title = $request->title;
$post->body = $request->body;
$post->meta_description = $request->meta_description;
$post->slug = $request->slug;
$post->user_id = auth()->id();
$image = $request->input('featimage'); // image base64 encoded
preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
$image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
$image = str_replace(' ', '+', $image);
$imageName = 'image_' . time() . '.' . $image_extension[1]; //generating unique file name;
\Storage::disk('public')->put($imageName,base64_decode($image)
$post->save();
}
View
<form class="form-horizontal" action="{{route('posts.store')}}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<fieldset>
<div class="form-group row"><label class="col-md-2 col-form-label">Title</label>
<div class="col-md-10"><input class="form-control" name="title" type="text"><span class="form-text">Please insert a title <small>eg. Exciting new event coming to London</small>
</span></div>
</div>
</fieldset>
<fieldset class="">
<div class="form-group row"><label class="col-md-2 col-form-label">Category</label>
<div class="col-md-10"><select name="post_category_id" class="custom-select custom-select-sm">
#foreach($postCategories as $postCategory)
<option value="{{ $postCategory->id }}">{{ $postCategory->name }}</option>
#endforeach
</select></div>
</div>
</fieldset>
<fieldset>
<div class="form-group row"><label class="col-md-2 col-form-label">Post Body</label>
<div class="col-md-10">
<textarea type="textarea" class="form-control" rows="10" name="body"></textarea>
</div>
</div>
</fieldset>
<fieldset>
<div class="form-group row"><label class="col-md-2 col-form-label">Meta Description</label>
<div class="col-md-10">
<textarea type="textarea" class="form-control" rows="4" name="meta_description"></textarea>
</div>
</div>
</fieldset>
<fieldset>
<select name="tags[]" multiple="multiple" class="form-control select2-multi">
#foreach($tags as $tag)
<option value="{{ $tag->id }}">{{ $tag->name }}</option>
#endforeach
</select>
</fieldset>
</div>
</div><!-- END card-->
</div>
<div class="col-md-4">
<div class="card card-default">
<div class="card-header">Featured Image</div>
<div class="card-body">
<fieldset>
<figure>
<img src="" class="gambar img-responsive img-thumbnail" id="item-img-output" /></figure>
<input type="hidden" id="featimage" name="featimage">
</fieldset>
<input type="file" class="item-img file center-block" name="upload"/>
</label>
</div>
<div>
</div>
<!-- START card-->
<div class="card card-default">
<div class="card-header">Slug</div>
<div class="card-body">
<div class="input-group mb-3">
<div class="input-group-prepend"><span class="input-group-text" id="basic-addon1">www.sixmedia.co.uk/</span></div><input class="form-control" name="slug" type="text" placeholder="slug" aria-label="Username" aria-describedby="basic-addon1">
</div>
</div>
</div><!-- END card-->
<!-- START card-->
<div class="card card-default">
<div class="card-header">Featured</div>
<div class="card-body">
<div class="col-md-12">
<fieldset>
<div class="form-group row">
#foreach($featured as $feat)
<div class="checkbox c-checkbox"><label><input name="featured[]" type="checkbox" value="{{$feat->id}}"><span class="fa fa-check"></span>{{ $feat->name }} </label></div>
#endforeach
</div>
</fieldset>
</div>
</div>
</div><!-- END card-->
<button class="btn btn-primary btn-block" name="submit">Save</button>
<button class="btn btn-danger btn-block" name="submit">Cancel</button>
</form>
JS
<script type="text/javascript">
$(".gambar").attr("src", "http://www.pngall.com/wp-content/uploads/2/Upload-PNG-Image-File.png");
var $uploadCrop,
tempFilename,
rawImg,
imageId;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.upload-demo').addClass('ready');
$('#cropImagePop').modal('show');
rawImg = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 500,
height: 281,
},
enforceBoundary: false,
enableExif: true
});
$('#cropImagePop').on('shown.bs.modal', function(){
// alert('Shown pop');
$uploadCrop.croppie('bind', {
url: rawImg
}).then(function(){
console.log('jQuery bind complete');
});
});
$('.item-img').on('change', function () { imageId = $(this).data('id'); tempFilename = $(this).val();
$('#cancelCropBtn').data('id', imageId); readFile(this); });
$('#cropImageBtn').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'base64',
format: 'png',
size: {width: 350, height: 200}
}).then(function (resp) {
$('#item-img-output').attr('src', resp);
$('#featimage').attr('src', resp);
$('#cropImagePop').modal('hide');
});
});
// End upload preview image
</script>
The problem seems to be in your jquery script, you are setting the base64 string as the source of <input type="hidden" id="featimage">
change this:
$('#featimage').attr('src', resp);
to this
`$('#featimage').val(resp);`
I'm burned out finding ways to exclude hidden elements from form serialization.
I tried to use this code:
$("#form-user :not(.hide_element) > :input").serialize();
or this one:
$("#form-user").not(".hide_element > input").serialize();
but still got the same form-data response
I've put the form inside my modal.
<div class="modal-body">
<?php echo form_open('#',array("class"=>"form-horizontal","id"=>"form-user")); ?>
<div id="message"></div>
<div class="form-group">
<label class="control-label col-md-3">Username:</label>
<div class="col-md-9">
<input type="text" name="uname" class="form-control">
</div>
</div>
<div class="form-group hide_element" >
<label class="control-label col-md-3" id='lblpass'>Password:</label>
<div class="col-md-9">
<input type="password" name="pass" class="form-control">
</div>
</div>
<div class="form-group hide_element">
<label class="control-label col-md-3" id='lblnewpass'>Confirm Password:</label>
<div class="col-md-9">
<input type="password" name="confirmpass" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Email Address:</label>
<div class="col-md-9">
<input type="email" name="email" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">User Status:</label>
<div class="col-md-9">
<select name="userstatus" class="form-control">
<option hidden>Select user status of the account (Default = Active)</option>
<option value="1">Active</option>
<option value="2">Inactive</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">User Type:</label>
<div class="col-md-9">
<select name="usertype" class="form-control">
<option hidden>Select user type of the account (Default = Customer)</option>
<option value=1>Customer</option>
<option value=2>Admin</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-success" type="button" id="action"><i class="fa fa-save"></i> Add user</button>
<button class="btn btn-danger" type="button" data-dismiss="modal"><i class="fa fa-close"></i> Close</button>
<?php echo form_close(); ?>
my ajax function:
$(document).ready(function(){
$('#form-user').on('click','#action',function(e){
e.preventDefault();
if(action == 'add'){
$.ajax({
url: site_url('User/add_user'),
data: $("#form-user :not(.working) > input").serialize(),
type:'POST',
encode: true,
dataType:'json',
success:function(data){
if(!data.success){
if(data.errors){
$('#message').html(data.errors).addClass('alert alert-danger');
}
}else{
$('#message').html("").removeClass('alert alert-danger');
$('.modal-title').html('Processing request');
$('#alert').modal('show');
$('#mymodal').modal('hide');
$('#body-message').html("<i class='fa fa-spinner fa-pulse fa-3x fa-fw'></i> Updating...");
setTimeout(function(){
$('#body-message').html("<i class='fa fa-check fa-3x'></i>"+ data.message);
},3000)
setTimeout(function(){
$('#alert').modal('hide');
$('#form-user')[0].reset();
reloadData();
},5000);
}
}
});
}else{
$.ajax({
url: site_url('User/update_user'),
data: $("#form-user :not(.working) > :input").serialize() +"&id=" + id,
type:'POST',
encode: true,
dataType:'json',
success:function(data){
if(!data.success){
if(data.errors){
$('#message').html(data.errors).addClass('alert alert-danger');
}
}else{
$('#message').html("").removeClass('alert alert-danger');
$('.modal-title').html('Processing request');
$('#alert').modal('show');
$('#mymodal').modal('hide');
$('#body-message').html("<i class='fa fa-spinner fa-pulse fa-3x fa-fw'></i> Updating...");
setTimeout(function(){
$('#body-message').html("<i class='fa fa-check fa-3x'></i>"+ data.message);
},3000)
setTimeout(function(){
$('#alert').modal('hide');
$('#form-user')[0].reset();
reloadData();
},5000);
}
}
});
}
});
});
Disabled elements do not get posted nor serialized, so you can temporarily add the disabled attribute to them, and restoring them to their previous state after successfull response:
$('#form-user').on('click','#action',function(e){
$("#form-user .hide_element > input").attr('disabled','disabled');
$.ajax({
...
data: $("#form-user").serialize(),
success:function() {
$("#form-user .hide_element > input").removeAttr('disabled');
}
});
});
Try this:
var frm = $('#finalform').find(":input:not(:hidden)").serialize();
Or
var frm = $('#finalform :input:not(:hidden)').serialize();