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
Related
I am using laravel and ajax to update records from table. Currently, the records are successfully being updated but somehow a refresh is triggered, making the ajax feature useless. i need a way to just post the form to update my database record without refreshing the page.
The following is my code.
View File Ajax
$(document).on("click", "#primaryButton", function(e) {
e.preventDefault(); // Prevent Default form Submission
$.ajax({
type: "post",
url: "{{ route('event-qr-post') }}",
data: $("#message").serialize(),
success: function(store) {
location.href = store;
console.log("success!");
console.log(location.href);
console.log($("#message").serialize());
},
error: function() {
console.log("fail");
}
}).done(function(store) {
console.log("itsdone");
});
// e.preventDefault();
return false;
});
View File Submit Form
<form enctype="multipart/form-data" id="message">
#csrf
<div class="form-l">
<div id="ref-lookup">
<label style="font-size: 22px; font-weight: 700;margin-block:10px;" for="eventTitle">Reference
number</label>
<input id="id" name="id" value="{{ '' }}" required>
{{-- <input type="hidden" name="name" value="{{ $eid->name }}" required> --}}
<input type="hidden" name="staffName" value="{{ $sid->name }}" required>
<input type="hidden" name="submitType" id="submitType" value="">
<input type="hidden" name="pageType" id="pageType" value="{{ $type }}">
{{-- <input type="hidden" name="guestLeft" id="guestLeft" value=""> --}}
<div style="display:flex;justify-content:space-between;gap:10px">
<button type="button" style="background-color:green"
onclick="findGuest(document.getElementById('id').value);">Find Contact</button>
<button id="addGuest" type="button" style="background-color:red" onclick="addGuests();">Add a
Replacement</button>
</div>
</div>
<div id="guestForm">
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">First Name</label>
<input id="guestFirstName" name="first_name" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Last Name</label>
<input id="guestSurname" name="last_name" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Email</label>
<input id="guestEmail" name="email" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Company</label>
<input id="companyName" name="company" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Job Title</label>
<input id="guestTitle" name="title" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Tel</label>
<input id="guestPhone" name="tel" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Country</label>
<input id="guestCountry" name="country" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Notes</label>
<input id="guestNotes" name="notes" value="">
</div>
<button type="button" class="btn-blue" id="primaryButton">
Submit
<span class="foo fa fa-star checked"></span>
</button>
</div>
</div>
Controller
public function post_eventQR_attendance(Request $request)
{
// $ins = $request->all();
// unset($ins['_token']);
// dd($ins);
$User = MasterTempAward::where('id', $request->get('id'))->first();
$User->modified_by = $request->get('staffName');
$User->attended = "Yes";
$User->time = Carbon::now();
$User->business_card = "";
$User->save();
}
Your page is being refreshed because of the location.href = store; that you passed after the ajax request receives a success response.
location.href redirects the webpage to the specified URL.
So change your Ajax code to this:
$(document).on("click", "#primaryButton", function(e) {
e.preventDefault(); // Prevent Default form Submission
$.ajax({
type: "post",
url: "{{ route('event-qr-post') }}",
data: $("#message").serialize(),
success: function(store) {
// location.href = store;
console.log("success!");
// console.log(location.href);
console.log($("#message").serialize());
},
error: function() {
console.log("fail");
}
}).done(function(store) {
console.log("itsdone");
});
// e.preventDefault();
return false;
});
I have done a Modal form and trying to submit the form, but it is not working.
This is my form
<div class="modal-body">
<div class="card-body">
<form action="{{ url('/admin/modaluser/add')}}" method="POST" id="customerSubmit">
<div class="row">
<div class="col">
#if(session('success'))
<div class="alert alert-success">{{session('success')}}</div>
#endif
#if(session('error'))
<div class="alert alert-error">{{session('error')}}</div>
#endif
#csrf
<div class="row">
<div class="form-group col-md-6">
<label for="name">Name</label>
<input class="form-control" name="name" id="name"
type="text"
placeholder="Enter Name" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="hpcontact">HP Contact No</label>
<input class="form-control" name="hpcontact" id="hpcontact"
type="text"
placeholder="HP Contact No" data-original-title="" title=""
required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="icno">IC No</label>
<input class="form-control" name="icno" id="icno"
type="text"
placeholder="Enter IC No" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="homephone">Home Contact No</label>
<input class="form-control" name="homephone" id="homephone"
type="text"
placeholder="Enter home contact no" data-original-title="" title=""
required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="dob">D.O.B</label>
<input class="form-control" name="dob" id="dob"
type="date"
placeholder="Enter DOB" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="officeno">Office No</label>
<input class="form-control" name="officeno" id="officeno"
type="text"
placeholder="Enter Office No" data-original-title="" title=""
required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="address">Address</label>
<input class="form-control" name="address" id="address"
type="text"
placeholder="Enter Address" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="email">Email</label>
<input class="form-control" name="email" id="email"
type="email"
placeholder="Enter Email" data-original-title="" title=""
required>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
This is my jQuery for the Ajax
$(document).ready(function(){
$('body').on('click','#addcustomer',function(e){
e.preventDefault();
// AJAX request
console.log($('#customerSubmit').serialize())
$.ajax({
method: 'post',
url: '/admin/modaluser/add',
data: $('#customerSubmit').serialize(),
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
});
});
And this my Controller
public function adduser(Request $request)
{
if(Request::ajax()){
$name = Input::get( 'name' );
$hpcontact = Input::get( 'hpcontact' );
$icno = Input::get( 'icno' );
$homephone = Input::get( 'homephone' );
$dob = Input::get( 'dob' );
$officeno = Input::get( 'officeno' );
$address = Input::get( 'address' );
$email = Input::get( 'email' );
$customer = new Customer();
$customer->name = $name;
$customer->hpcontact = $hpcontact;
$customer->icno = $icno;
$customer->homephone = $homephone;
$customer->dob = $dob;
$customer->officeno = $officeno;
$customer->address = $address;
$customer->email = $email;
$customer->save();
$response = array(
'status' => 'success',
'msg' => 'Customer created successfully',
);
return Response::json($response);
}
else {
echo 'no';
exit;
}
}
And finally, this is my Router
Route::post('modaluser/add', 'CustomerController#adduser')->name('customer.adduser');
When I click the button, nothing has happened. But this error is coming.
POST http://127.0.0.1:8000/admin/modaluser/add 500 (Internal Server Error)
And showing me the console error, which is defined in the ajax. Is there anything wrong I am doing. This is my First Ajax in Laravel. Please help me to solve this. Thanks in advance.
add /admin into your route:
Route::post('admin/modaluser/add', 'CustomerController#adduser')->name('customer.adduser');
and change url path in ajax:
$(document).ready(function(){
$(document).on('submit','#customerSubmit',function(e){
e.preventDefault();
// AJAX request
console.log($(this).serialize())
$.ajax({
method: 'post',
url: "{{route('customer.adduser')}}",
data: $(this).serialize(),
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
});
});
remove form action:
<form action="" method="POST" id="customerSubmit">
You should check all class used paths declared on top of the controller or not. You should add the CSRF header in your ajax request.
$.ajax({
method: 'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "route name or url",
data: $(this).serialize(),
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
I have a small contact form that almost works as i should. The file is uploaded and sent correctly, but all the other values from the input fields in the form does not pass throug the script. Does anyone see what I am missing?
Form:
<form id="contactForm" name="sentMessage" novalidate="" method="post" enctype="multipart/form-data">
<input type="hidden" name="path" id="path" value="projectpage">
<div><div class="textwidget custom-html-widget"><div class="moduletable pt-2 pb-2 mb-4">
<div class="custom pl-2 pr-2 pt-4 pb-2 mb-4">
<div class="control-group form-group">
<div class="col"><label for="name">Navn:</label><input id="name" class="form-control" required="" type="text" data-validation-required-message="Skriv inn ditt navn.">
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="phone">Telefonnummer:</label><input id="phone" class="form-control" required="" type="tel" data-validation-required-message="Skriv inn et telefonnummer.">
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="email">E-post:</label><input id="email" class="form-control" required="" type="email" data-validation-required-message="Skriv inn en e-postadresse.">
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="message">Melding:</label><textarea id="message" class="form-control" style="resize: none;" cols="100" maxlength="999" required="" rows="10" data-validation-required-message="Skriv en melding"></textarea>
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="attachment">Vedlegg:</label> <input type="file" name="attachment[]" class="form-control border-0 w-auto" multiple="multiple">
</div>
</div>
<div class="control-group form-group">
<div class="col"><label class="checkbox"> <input id="terms-and-conditions" name="terms-and-conditions" required="" type="checkbox" data-validation-required-message="Kryss av denne boksen hvis du vil fortsette"> Ved avkryssning samtykker du i vår personvernerklæring. </label>
<div class="help-block"></div>
</div>
</div>
<p class="help-block"></p>
<div id="success"></div>
<div class="col"><button id="sendMessageButton" class="btn btn-success" type="submit">Send oss melding</button></div></div>
</div></div></div></form>
JS: I think the problem is here, but I cant figure out what to change or add to make the data from the fields pass through along with the attachment.
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {},
submitSuccess: function($form, event) {
$("#btnSubmit").attr("disabled", true);
event.preventDefault();
var data = new FormData(contactForm);
$.ajax({
url: "/wp-content/themes/bootstrap/mail/contact_me.php",
type: "POST",
method: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function() {
$("#btnSubmit").attr("disabled", false);
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×").append("</button>");
$('#success > .alert-success').append("<strong>Takk for din interesse. </strong>");
$('#success > .alert-success').append('</div>');
$('#contactForm').trigger("reset");
},
error: function() {
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×").append("</button>");
$('#success > .alert-danger').append("<strong>Sorry, it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
$('#contactForm').trigger("reset");
},
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
$('#name').focus(function() {
$('#success').html('');
});
PHP:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
/* Exception class. */
require 'Exception.php';
/* The main PHPMailer class. */
require 'PHPMailer.php';
$name = strip_tags(htmlspecialchars($_POST['name']));
$from = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$path = strip_tags(htmlspecialchars($_POST['path']));
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$mail->AddReplyTo(($email_address), ($name));
$mail->setFrom('noreply#mydomain.no', 'Kontaktskjema på nettside');
$mail->addAddress('email#gmail.com', 'My NAME');
$mail->Subject = 'Melding fra ' .$name. ' via kontaktskjema';
$mail->Body = "Du har fått en melding via kontaktskjemaet på nettsiden.\n\n"."Her er detaljene:\n\nNavn: $name\n\nE-post: $email_address\n\nTelefon: $phone\n\nMelding:\n$message";
foreach ($_FILES["attachment"]["name"] as $k => $v) {
$mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k] );
}
if(!$mail->send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
return true;
?>
Most of your <input> elements don't have name attributes. So this won't include them:
new FormData(contactForm)
The file input works because it has a name:
<input type="file" name="attachment[]" class="form-control border-0 w-auto" multiple="multiple">
^----- here ------^
Add names to the rest of the inputs that you want included in the FormData object.
Like David said most of your <input> elements dont have name attributes and thats why the FormData method dont include them, you have two work arounds here:
Get all your data into an array using the id of each element and pass this array to your ajax e.g:
let data = {
name : $('#name').val(),
email: $('#email').val(),
.....
};
add the name attribute to each input.
Hope it helps
I am trying to post data though ajax post but somehow unable to post . am getting 403 forbidden. Fortunately my other ajax posts are submitting properly as they are getting right re-generated token. But in form_open_multipart it's not working.
CI config
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'my_token';
$config['csrf_cookie_name'] = 'my_cookie';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
form_open is working well, but in the case of multi part it's not working well !!!!
my HTML
<?php $parameter = array('id' => 'frm_id', 'class' => 'form-horizontal'); echo form_open_multipart('controller/save',$parameter) ;?>
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Name</label>
<div class="col-md-6">
<div class="input-icon">
<i class="fa fa-bell-o"></i>
<input type="text" id="catId" class="form-control " placeholder="Type Something..." name='name' />
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Description</label>
<div class="col-md-6">
<div>
<textarea class="form-control" rows="3" name="description"></textarea>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Image 1</label>
<div class="col-md-6">
<div>
<input type="file" name="thumb_image">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Image 2</label>
<div class="col-md-6">
<div>
<input type="file" name="banner_image">
</div>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn btn-flat green">Submit</button>
<button type="button" class="btn btn-flat grey-salsa">Cancel</button>
</div>
</div>
</div>
<?php echo form_close() ;?>
My JS
<script type="text/javascript">
var frmSave = $('#frm_id');
frmSave.on('submit', function(event){
event.preventDefault();
$form=$(this);
var fd = new FormData($('#frm_id')[0]);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
dataType: 'json',
data: fd,
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data)
}
})
});
</script>
Still I am getting this message
An Error Was Encountered. The action you have requested is not
allowed.
var vl = "; " + document.cookie;
var pr = vl.split("; csrf_cookie=");
var obj; if (pr.length == 2) { obj = pr.pop().split(";").shift(); }
using this variable in the ajax body section like
data : '<?php echo $this->security->get_csrf_token_name(); ?>': obj
Now it's working fine.
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>