I need to post data from a form that creates fields from looping through some ids, so the fields have the same id and names but different data which i need to pass to my controller an eventually save
My Form View
<form class="form" id="addForm">
<div class="panel-body">
<?php foreach ($lab_result->result() as $results){?>
<div class="form-group">
<div class="col-md-5">
<input type="hidden" id="request_details_id" name="request_details_id" class="form-control" value="<?php echo $results->id; ?>"/>
<label class="col-sm-12 control-label"><span class="text-warning"><strong>Requested Service : </strong></span> <span class="text-success"><?php echo $results->service_name; ?> - <?php echo $results->service_description; ?></span></label>
<label class="col-sm-12 control-label"><span class="text-warning"><strong>Service Costs : </strong></span> <span class="text-success">Ksh. <?php echo $results->service_price; ?></span></label>
</div>
<div class="col-sm-7">
<textarea class="form-control" rows="2" id="results" name="results" placeholder="Input Lab Results, if none type N/A"></textarea>
</div>
</div>
<?php }?>
</div><!-- panel-body -->
<div class="panel-footer">
<button type="submit" class="btn btn-primary">Send Results</button>
</div>
</form>
Ajax to post data
$.ajax({
url: '<?php echo base_url(); ?>laboratory/addLabResult',
type: 'post',
data: $('#addForm :input'),
dataType: 'html',
success: function(html) {
$('#addForm')[0].reset();
bootbox.alert(html, function()
{
window.location.reload();
});
}
});
If i print_r in my controller, I only see the post from the last row
You need to use input name in array format to upload all values
<input type="hidden" id="request_details_id" name="request_details_id[]" class="form-control" value="<?php echo $results->id; ?>"/>
and
<textarea class="form-control" rows="2" id="results" name="results[]" placeholder="Input Lab Results, if none type N/A"></textarea>
Related
I use the same form to view details of a record that is in the database and make form submission. But an error occurs when I view a log and then register other data. In this case the new registration is registered three times in the database. And the reason this happens is that the form data is cached when I view or register a record. All the solutions I searched on the internet didn't work for me.
This is my form
<div id="form" style="display: none;" class="col-md-12">
<div class="row">
<h5 class="title">Add</h5>
<div class="float-right" style="margin-left: 80%">
<button class="btn btn-secondary" id="close_form">Close</button>
</div>
</div>
<form method="post" id="sample_form" class="form-horizontal" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fas fa-minus"></i></button>
</div>
</div>
<div class="card-body">
<fieldset disabled>
<div class="row">
<div class="form-group col-md-3">
<label for="inputCity">Código do documento:</label>
<input type="text" class="form-control" id="id_docs" name="id_docs">
</div>
<div class="form-group col-md-8">
<label for="inputCity">Status</label>
<input type="text" class="form-control" id="status" name="status">
</div>
</div>
</fieldset>
<div class="form-group">
<label>Assunto</label>
<textarea class="form-control" id="assunto" name="assunto" required></textarea>
</div>
<div class="form-group">
<label for="inputAddress2">Proveniencia</label>
<input type="text" class="form-control" id="prov" placeholder="Proveniencia" name="prov" required>
</div>
<div class="form-group col-md-4">
<label for="inputCity">Correspondência</label>
<input type="date" class="form-control" id="corre" name="corre">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" id="img_cad" style="margin-left: 10px;">
<span class="control-label col-md-4"><b class="span_doc">File:</b></span><br><br>
<input type="file" id="image" aria-describedby="inputGroupFileAddon01" name="image">
<span id="store_image"></span>
</div><br>
<br>
<input type="hidden" name="action" id="action" />
<input type="hidden" name="hidden_id" id="hidden_id" />
<input type="hidden" name="hidden_id_docs" id="hidden_id_docs" />
<button type="submit" name="action_button" id="action_button" class="btn btn-warning">Save</button>
</div>
</div>
</form>
</div>
This is the function to view the details of a record on the form
$(document).on('click', '.edit', function(){
var id_scr = $(this).attr('id_scr');
$('#div_table').hide();
$.ajax({
url:"/scr/"+id_scr+"/edit",
cache: false,
dataType:"json",
success:function(html){
$('#action_button').text("Edit Data");
$('#assunto').val(html.data.assunto);
$('#prov').val(html.data.prov);
$('#corre').val(html.data.corre);
$('#status').val(html.data.descricao);
$('#cod_cadastro').val(html.data.cod_cadastro);
$('#hidden_id').val(html.data.id);
$('#hidden_id_docs').val(html.data.id_docs);
$('#id_docs').val(html.data.id_docs);
$('.title').text("Details...");
$('.span_doc').text("Alter Doc");
$('#action').val("Edit");
$('#form').show();
}
})
});
To clear the form data after viewing a record, I created thisTo clear the form data after viewing a record, I created this function:
$(document).on('click', '#close_form', function(){
$('#sample_form')[0].reset();
$('#form').hide();
$('#div_table').show();
});
And finally, this is the function for registering a new record
$('#sample_form').on('submit', function(event){
event.preventDefault();
$('.progress').show();
if($('#action').val() == 'Add')
{
$.ajax({
url:"{{ route('scr.store') }}",
method:"POST",
data: new FormData(this),
contentType: false,
cache:false,
processData: false,
dataType:"json",
success:function(data)
{
alert('SUCCESSFULLY SAVED');
$('#sample_form')[0].reset();
$('#formModal').modal('hide');
location.reload(); //**This is the only way I found to clear the form after submitting the data**
}
})
}
})
You could try this method :
function submitForm() {
// Get the first form with the name
// Usually the form name is not repeated
// but duplicate names are possible in HTML
// Therefore to work around the issue, enforce the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit the form
frm.reset(); // Reset all form data
return false; // Prevent page refresh
}
Or you could just call this method in your submit method
I'm using laravel and trying to save data using post through ajax but data is not saved in database. I'm getting following error: jquery.min.js:2 POST http://localhost:8000/admin/products/attributes/add 500 (Internal Server Error). My code is as follows:
view:
<script>
$("#add_attributes_info").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success'+msg);
}
});
});
</script>
<form action="#" id="frmattributes" method="POST">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price"/>
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
Controller:
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->data);
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
You should use:
$productAttribute = ProductAttribute::create($request->all());
However you should keep in mind this is very risky without validation.
You should add input validation and then use:
$productAttribute = ProductAttribute::create($request->validated());
Use $request->all();
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->all());
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
PS : I made some changes to get it works
Hope this help
<head>
<title></title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function submitForm() {
$.ajax({
type: "POST",
url: '../admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success' + msg);
}
});
}
</script>
</head>
<body>
<form id="frmattributes">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price" />
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info" type="button" onclick="submitForm()">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
</body>
</html>
So in the controller, change the $request->data with :
$productAttribute = ProductAttribute::create($request->all());
or also check what the request contains, before creating you can check using:
dd($request->all());
iam trying to pass multiple check box value to the database using ajax.But this code is not working,please help me to find the answer. This is my jquery and ajax
jQuery(".bus-cat-drop").change(function(event) {
$('.check').html("");
var businesscategoryid = $(this).val();
hitURL = baseURL + "user/postbusiness/get_businesscategoryid/";
alert(baseURL + "user/postbusiness/get_businesscategoryid");
//alert(businesscategoryid);
jQuery.ajax({
type : "POST",
dataType : "json",
url : hitURL,
data : { categoryid : businesscategoryid }
}).done(function(data){
$.each(data, function(key,value) {
//alert(key);
//alert(value.value);
/* var opt = $('<option />');
opt.val(value.value);
opt.text(value.label);
$('#subcategory').append(opt);
$('#subcategory').get(0).selectedIndex = 1; */
$('.check').append("<input name=check[]:checked type=checkbox>"+value.label+"</br>");
$('.check').push(this.value);
});
});
iam trying to pass multiple check box value to the database using ajax.But this code is not working,please help me to find the answer. Here is my view.
<form client ="form" id="bus-reg-form" action="<?php echo base_url().'user/postbusiness/DirectoryCategory/'.$userId ?>" method="post" role="form">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="company">Name of Business / Company </label>
<input type="text" class="form-control required" id="company" name="company" value="<?php echo $company_name;?>">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Category">Category</label>
<select class="form-control bus-cat-drop" id="businesscategory" name="businesscategory">
<option value="0">Select Category</option>
<?php
if(!empty($list_directorycategory))
{
foreach ($list_directorycategory as $rl)
{
?>
<option value="<?php echo $rl->dr_cat_id; ?>"><?php echo $rl->dr_cat_name;?></option>
<?php
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<div class="subcategory-dropdown">
<label for="subcategory"> Sub Category [Maximum 3 subcategory]</label>
<div class="check" name="check[]" >
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="Business-Offer">
<label for="business">Business Offer / Highlights</label>
<textarea class="form-control required" title="Business description" id="business" rows="6" name="business"></textarea>
</div>
</div>
</div>
</div>
<div class="row">
<div class="control-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group">
<label for="Tags">Tags [Maximum 10 tags]</label>
<input type="text" class="form-control required" id="tags" name="tags">
</div>
</div>
</div>
please help me with this error. I have a javascript that i want to append a single image file to my form and i want to send the form data into ajax.
Here is my code:
<form id="frm_product" class="form-horizontal" enctype="multipart/form-data">
<div style="position:relative;">
<input type="file" name="addfiles" id="addfiles">
<span class='label label-info' id="upload-file-info"></span>
</div>
<br>
<div class="form-group">
<label for="cat_name">Product Name: </label>
<input type="text" class="form-control" name="prod_name">
<span class="error prod_name"></span>
</div>
<div class="form-group">
<label for="cat_desc">Description: </label>
<input type="text" class="form-control" name="prod_desc">
<span class="error prod_desc"></span>
</div>
<div class="form-group">
<label for="cat_desc">Price: </label>
<input type="text" class="form-control" name="prod_price">
<span class="error prod_price"></span>
</div>
<div class="form-group">
<label for="cat_desc">Category: </label>
<select class="form-control" name="prod_cat">
<?php foreach($data as $category){ ?>
<option value="<?php echo $category->id; ?>"><?php echo $category->name; ?></option>';
<?php } ?>
</select>
<span class="error prod_cat"></span>
</div>
</form>
here is my ajax code where i want to append a single file:
function submitProduct() {
var formData = new FormData($("#frm_product")[0]);
formData.append('image', $("#addfiles")[0].files);
$.ajax({
url : siteurl+"/product/addproduct",
type: "POST",
data: formData,
dataType: "JSON",
contentType: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
success: function(resp) {
$('.error').html('');
if(resp.status == false) {
$.each(resp.message,function(i,m){
$('.'+i).text(m);
});
}
else if(resp.status == true) {
$('#addProduct').modal('hide');
$('#frm_product')[0].reset();
alert("Successfully Added");
}
}
});
}
when i do upload file it says error:
you didn't select a file to upload
i have a form that insert in dbase what i write
here is the form,
<form id="contact-form" class="bl_form text-center" action="<?php echo "index.php?page=rooms&room=$rid&rpw=$rpw&r=$r";
?>" method="post" novalidate>
<span class="field-wrap scrollimation fade-right">
<input type="hidden" id="contact-name" name="contactName" type="text"
class="label_better requiredField" data-new-placeholder="Name" placeholder="Name" value="<?php echo "$uid"; ?>" data-error-
empty="*Enter your name">
</span>
<span class="field-wrap scrollimation fade-left">
<label class="control-label" for="contact-message">Message</label>
<textarea id="contact-message" name="message" rows="1" class="label_better
requiredField" data-new-placeholder="Message" placeholder="Message" data-error-empty="*Enter your message"></textarea>
</span>
<p class="text-center"><button name="sy2" id="submit_post" type="submit" class="btn btn-meflat
icon-left" data-error-message="Error!" data-sending-message="Sending..." data-ok-message="Message Sent"><i class="fa fa-paper-
plane"></i>Send Message</button></p>
<input type="hidden" name="submitted" id="submitted" value="true" />
<?php echo "<postfield name=\"message\" value=\"$(message)\"/>"; ?>
</form>
and i want to put a ajax code that display this message from dbase
<?php echo make_clickable($tosay)."$link_delete"; ?>
Can someone provide me an example?Thank you
Look at this
Ajax tutorial for post and get
So, the jQuery
$('body').on('submit', '#contact-form', function(){
$.post({$(this).attr("action"), $(this).serialize(), function(data){
if(data){
alert(data.message);
}
}, 'json');
return false;
});
And the server side
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// do your thing here
echo json_encode(array("message" => make_clickable($tosay).$link_delete));
die();
}
?>