I'm making a small system that has inventory in it. I have a products table that has an image column that represents a picture of a specific product. My problem is why I can't upload using my modal and ajax code in my project in Laravel? Does anyone know how to solve this issue? I spend 2 days already in figuring out how to solve this error:
message: "Undefined index: product_name"
I already made the fields fillable in my model. Help will be highly appreciated.
Modal Code
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Register New Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p style="font-weight: bold;">Name </p>
<input type="text" class="form-control" id="product_name"/>
<p style="font-weight: bold;">Description </p>
<input type="text" class="form-control" id="description"/>
<p style="font-weight: bold;">Price </p>
<input type="text" class="form-control" id="currentprice"/>
{{-- <input style="text-transform:uppercase" type="text" class="form-control" id="supplier_id"/> --}}
<p style="font-weight: bold;">Supplier </p>
<select class="form-control" id="supplier_id" >
#foreach ($suppliers as $supplier)
<option value="{{$supplier->id}}">{{$supplier->name}}</option>
#endforeach
</select>
<p style="font-weight: bold;">Picture </p>
<input type="file" class="form-control" id="picture"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="add_product">Add</button>
</div>
</div>
</div>
</div>
Script
$(document).ready(function() {
//add
$('#add_product').click(function(e) {
e.preventDefault();
var name = $('#product_name').val();
var description = $('#description').val();
var price = $('#currentprice').val();
var supplier_id = $('#supplier_id').val();
var image = $('#picture').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ url('/product') }}",
method: 'post',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data:{
product_name: name,
description: description,
price: price,
supplier_id: supplier_id,
image: image,
},
success: function (res) {
console.log(res);
window.location.href = '{{route("products")}}'
}
});
});
});
ProductsController.php
public function store(Request $request)
{
$data = $request->all();
$data['product_name'] = ($data['product_name']);
$data['description'] = ($data['description']);
$data['supplier_id'] = ($data['supplier_id']);
$data['price'] = ($data['price']);
if ($request->hasFile('image')){
//Add new photo
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('img/' . $filename);
Image::make($image)->resize(300,300)->save($location);
$oldFilename = $products->image;
//Update DB
$products->image = $filename;
//Delete the old photo
// Storage::delete($oldFilename);
}
Product::create($data);
return response()->json($data);
}
route for products
//products
Route::resource('product', 'ProductsController');
Seems like you send to server an object, when server expect JSON. Try to add dataType:
$.ajax({
url: "{{ url('/product') }}",
method: 'post',
enctype: 'multipart/form-data',
contentType: false,
dataType: 'json', // setting of data type
data:{
product_name: name,
description: description,
price: price,
supplier_id: supplier_id,
image: image,
},
success: function (res) {
console.log(res);
window.location.href = '{{route("products")}}'
}
});
I know this question is quite old but I faced the same problem in the past days so I think an answer could be usefull to other developers.
You need only to use FormData instead of serialize your form. Note that FormData need an HTMLFormElement so you need to add [0] to your jQuery object. And you have NOT to add dataType directive.
This is my code:
$('#submit').on('click', function(e) {
e.preventDefault();
$(this).attr('disabled','disabled');
var form = $(this).closest('form');
jQuery.ajax({
type: 'POST',
processData: false,
contentType: false,
data: new FormData(form[0]),
url: form.attr('action'),
enctype: 'multipart/form-data',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
$('#submit').removeAttr('disabled');
// YOUR SUCCESS MANAGEMENT
},
error: function (e) {
$('#submit').removeAttr('disabled');
// YOUR ERROR MANAGEMENT
}
});
});
Related
So im building my own website and i have this feature wherein a logged-in user can upload and change his avatar. it is my first time doing this so i am having a hard time making this work. i'll provide the codes below, you guys might see the faults that i dont know. it will be greatly appreciated if you can provide links that will help me improve. thanks in advance!
Blade.php file
<form method='POST' action="{{ route('image-upload') }}" enctype="multipart/form-data">
#csrf
<div class=" overflow-auto" style="padding-top:5%">>
<div class="p-3">
<div class="card">
<div class="card-body" >
<h4 class="card-title text-info"><strong> Attach your picture </strong></h4>
<div class="row justify-content-center">
<div class="col-sm-12 col-lg-4">
<div class="form-group row">
<label for="step5_picture" class="col-sm-3 text-right control-label col-form-label">Please upload your photo here:</label>
<div class="col-sm-9">
<input class="form-control" type="file" value="" id='upload_picture' >
</div>
</div>
</div>
</div>
Next
<button class="btn btn-lg waves-effect waves-light btn-info" id="btn-upload" style="float:right; margin-right:10px;">Upload</button>
</div>
</div>
</div>
</div>
</form>
Ajax code
$("#btn-upload").click(function(e){
e.preventDefault();
var data = {
'photo_filename': $('#upload_picture').val(),
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/image-upload",
data: data,
dataType: "json",
success: function (response) {
}
});
});
});
Controller.php file The name of the column in my database is also photo_filename
public function image-upload(Request $request,){
$data = UserInfoModel::where('app_id', '=' ,Session::get('loginId'))->first();
$validator=Validator::make($request->all(), [
'photo_filename' => 'required',
'photo_filename.*' => 'image|mimes:jpeg,png,jpg,svg|max:5000'
]);
if($request->hasfile('photo_filename')){
$data->update([
'photo_filename' => $request->input('photo_filename')
]);
$photo = $request->file('photo_filename')->getClientOrginalName();
$destination = public_path() . '/public/image';
$request->file('photo_filename')->move($destination, $photo);
return back()->with('success', 'Your image has been successfully uploaded!');
}
}
Web.php file
Route::post('/image-upload',[CustomAuthController::class, 'image-upload'])->name('image-upload');
I am getting a payload and here it is
No error but still not uploading
Here's a minimal working example to create file upload in Laravel:
blade file:
<form method="POST" enctype="multipart/form-data" action="{{ route('save') }}">
#csrf
<input type="file" name="image" placeholder="Choose image" id="image">
<button>Send</button>
</form>
Controller:
public function save(Request $request) {
$path = $request->file('image')->store('public/images');
return $path;
}
web.php:
Route::post('/foobar', [\App\Http\Controllers\FoobarController::class, 'save'])->name('save');
Please note Ajax call is not necessary here, since html form will do the POST call with the CSRF token.
Also please note that using hyphens in function names won't work in php.
use FormData to send file in form, and add contentType: false and processData: false, you can read function setting contentType and processData in here https://api.jquery.com/jquery.ajax/
var formData = new FormData();
formData.append('photo_filename', $('#upload_picture')[0].files[0])
$.ajax({
url: "/image-upload",
type: "post",
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(response) {
}
});
I want to pass some form data and file to a flask application from a form. but I can't pass it with ajax. There is a problem in data I guess. I've send data in ajax but in flask application I don't get any string or files.
Here is my html code:
<form id="user_vote" enctype = "multipart/form-data">
<br>
<br>
<div class="row">
<label class="col-sm-2">Name:</label>
<div class="col-sm-10">
<input type="text" name="name" id="name" rows="2" class="form-control" required>
</div>
</div>
<div class="row">
<label class="col-sm-2">National ID Image:</label>
<div class="col-sm-10">
<input type="file" name="national_id_image" id="national_id_image" rows="2" class="form-control" required>
</div>
</div>
<br>
<div class="row">
<label class="col-sm-2">Vote:</label>
<div class="col-sm-10">
<input type="number" name="vote" id="vote" rows="2" class="form-control" required>
</div>
</div>
<div class="row">
<div class="col-lg-12 text-center">
<input type="button" id="submit_vote" class="btn btn-primary btn-lg"
value="Authenticate and Encrypt Vote">
</div>
</div>
And here is my ajax code::
$(function(){
var form = $('#user_vote')[0];
var data = new FormData(form);
//console.log('hello');
//console.log(document.getElementById('submit_vote'));
$('#submit_vote').click(function(){
//console.log(data);
//console.log('hello');
$.ajax({
url: '/encrypt/vote',
type: "POST",
dataType: 'json',
enctype: 'multipart/form-data',
data: data,
contentType: false,
cache: false,
processData:false,
success: function(response){
//console.log("SUCCESS : ", data);
document.getElementById("encrypted_vote").innerHTML = response['encrypted_vote'];
document.getElementById("public_key").innerHTML = response['signature'];
document.getElementById("warning").style.display = "block";
},
error: function(error){
console.log(error);
}
});
});
})
Flask codes::
app.route('/encrypt/vote', methods=['POST'])
def encrypt_vote():
print('test')
name = request.form['name']
print(name)
family_name = request.form['family_name']
birth_date = request.form['birth_date']
national_id = request.form['national_id']
file = request.files['national_id_image']
filename = str(name) + str(family_name)# + secure_filename(file.filename)
#file.save(os.path.join(app.root_path, UPLOAD_FOLDER, filename))
#voter_national_cart_hash = get_digest('files/uploads/' + filename)
print('test vote type')
print(request.form['vote'])
vote = int(float(request.form['vote']))
pk = int(float(request.form['public_key']))
encrypted_vote = encrypt(pk, vote)
response = {
'encrypted_vote': str(encrypted_vote)
}
return jsonify(response), 200
Anyone can help me??
Thanks
It seems that you set enctype: 'multipart/form-data', which is non-existent property of the $.ajax() method. You should correct this error and simplify the request:
$.ajax({
type: "POST",
data: data,
url: '/encrypt/vote',
cache: false,
contentType: false,
processData: false,
success: function(response) {
/*The rest of your code*/
},
error: function(error){
console.log(error);
}
});
There is no need to set dataType, the default is Intelligent Guess (xml, json, script, or html). Read more here.
EDIT: Make sure you are using correct full path in the url, try not to use relative address, use https://www.your-server.com/encrypt/vote instead.
guys, I am trying to submit my form using ajax but I don't know exactly what happened it's not posting the values to my table in the database, This is the first time I am using ajax for form submit can anyone help me what mistake I have done.
Here is my view code:
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script type='text/javascript' src="<?php echo base_url(); ?>assets/theme1/js/jquery-2.1.3.min.js"></script>
<!-- <script type="text/javascript"> -->
<script type = "text/javascript">
// Ajax post
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
var organisation_name = $("input#organisation_name").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Organisation/createOrg",
dataType: 'json',
data: { organisation_name: organisation_name },
success: function(res) {
if (res) {
// Show Entered Value
jQuery("div#result").show();
jQuery("div#value").html(res.organisation_name);
}
}
});
});
});
</script>
<div class="modal fade" id="createGroup" tabindex="-1" role="dialog" aria-labelledby="createGroup" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" id="modal-content">
<form action="" id="user-groups-create" class="form-horizontal" method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Create a New Organisation</h4>
</div>
<div class="modal-body" id="modal-body">
<div class="form-group">
<label for="group_name" class="col-sm-4 control-label">New Organisation Name : </label>
<div class="col-md-8">
<input type="text" id="organisation_name" name="organisation_name" class="form-control" placeholder="Organisation Name" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" value="submit" class="btn btn-primary submit" id="submit">Create Organisation</button>
</div>
</form>
</div>
</div>
</div>
Here is my controller's method createOrg:
public function createOrg() {
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('organisation_name', 'organisation_name', 'required|min_length[5]|max_length[15]');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error', 'Organisation name need to be more than 3 characters and less than 15.');
redirect('Organisation', $error);
} else {
//Setting values for tabel columns
$data = array(
'organisation_name' => $this->input->post('organisation_name')
);
//Transfering data to Model
$this->Org_model->orgInsert($data);
$this->session->set_flashdata('success', 'Organisation created.');
//Loading View
redirect('Organisation');
}
}
Here is my Model's method orgInsert:
function orgInsert($data) {
// Inserting in Table(organisation)
$this->db->insert('organisation', $data);
}
Can anyone help me what mistake I have done and I have checked my code properly I didn't find exactly where I have done a mistake and I want my modal popup should be there after submitting it until a user clicks on the close button. when I try to keep alert after jQuery.ajax({ it is not coming alert.. and I can able to get the value from var organisation_name in alert...
Thanks in advance.
Hope this will work you :
$('#user-groups-create').on('submit',function(e){
var organisation_name = $("#organisation_name").val();
$.ajax({
type: "POST",
url: "<?=site_url('Organisation/createOrg');?>",
dataType: 'json',
data: {'organisation_name': organisation_name},
success: function(res) {
if (res)
{
alert(res);
window.location.href = "<?=site_url('Organisation');?>";
$("div#result").show();
$("div#value").html(res.organisation_name);
}
},
});
e.preventDefault();
});
Your controller's method createOrg should be like this :
public function createOrg()
{
$data = array(
'organisation_name' => $this->input->post('organisation_name')
);
//Transfering data to Model
$this->Org_model->orgInsert($data);
$this->session->set_flashdata('success', 'Organisation created.');
echo json_encode($data);
exit;
}
}
Working by changing the script to like this
<script type="text/javascript">
// Ajax post
$(document).ready(function() {
$('form').submit(function(e){
e.preventDefault();
var organisation_name = $("input#organisation_name").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Organisation/createOrg",
dataType: "html",
data: {organisation_name: organisation_name},
success: function(data) {
alert('success');
}
});
});
});
</script>
I downloaded a web application and i found out that it is created using Smarty Template Engine. I want to add an avatar field when creating new company so i added enctype="multipart/form-data" and <input type="file" name="avatar"> to the existing <form> and i also added avatar to my companies table in my database. Here is the HTML code:
<form class="form-horizontal" id="ib_modal_form" enctype="multipart/form-data">
<div class="form-group"><label class="col-lg-4 control-label" for="company_name">{$_L['Company Name']}<small class="red">*</small></label>
<div class="col-lg-8"><input type="text" id="company_name" name="company_name" class="form-control" value="{$val['company_name']}"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="avatar">{$_L['Avatar']}</label>
<div class="col-lg-8"><input type="file" name="avatar"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="email">{$_L['Email']}</label>
<div class="col-lg-8"><input type="text" id="email" name="email" class="form-control" value="{$val['email']}"> </div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-danger">{$_L['Cancel']}</button>
<button class="btn btn-primary modal_submit" type="submit" id="modal_submit"><i class="fa fa-check"></i> {$_L['Save']}</button>
</div>
I found out that the form goes to this javascript code when clicking the Save Button:
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
$.post( _url + "contacts/add_company_post/", $("#ib_modal_form").serialize())
.done(function( data ) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
});
});
Here is the code in the Controller:
case 'add_company_post':
$data = ib_posted_data();
$company = Model::factory('Models_Company')->create();
$company->company_name = $data['company_name'];
$company->url = $data['url'];
$company->email = $data['email'];
$company->phone = $data['phone'];
$company->logo_url = $data['logo_url'];
$company->avatar = $_FILES['avatar']['name'];
$company->save();
break;
The problem is that it does not recognize $_FILES['avatar']['name']; in the Controller Whenever i add a new company, i get a NULL value in my database. I cant seem to solve this problem. Any help would be appreciated. Thanks.
Change
From
$("#ib_modal_form").serialize()
To
new FormData($("#ib_modal_form")[0])
You should use FormData for uploading files using ajax. $(form).serialize() will give you just key and value.
Can you change your ajax call below way
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
var formData = new FormData($("#ib_modal_form")[0]);
$.ajax({
url: _url + "contacts/add_company_post/",
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
},
});
});
Hello I'm using Codeigniter 3 and jQuery ajax.
I'm using the built in upload library...
I want to upload image on my server, but always get this error message:
You did not select a file to upload.
Here is my code
View
<?php echo form_open_multipart('settings/uploadprofilephoto', array('id' => 'upload-avatar-form'));?>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Upload profile photo</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<div class="row">
<div class="form-group col-md-6">
<input type="file" name="profilephoto" id="profile-photo" class="form-control">
</div>
<div class="form-group col-md-6">
<button type="submit" id="upload" class="btn btn-success">Upload</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<?php echo form_close();?>
Controller
public function uploadProfilePhoto(){
$config = array(
'upload_path' => base_url() . 'uploads/test',
'allowed_types' => 'jpg|jpeg|gif|png',
'min_height' => 480,
'min_width' => 640,
'remove_spaces' => true,
);
$this->load->library('upload', $config);
if($this->upload->do_upload("profilephoto")){
$data = array(
'status' => true,
'messages' => 'Uploaded'
);
echo json_decode($data);
}else{
$data = array(
'status' => false,
'messages' => $this->upload->display_errors()
);
echo json_encode($data);
}
}
ajax
/*
Upload profile photo
*/
$("#upload-avatar-form").submit(function(event){
$.post(base_url + "settings/uploadprofilephoto" , $(this).serialize(), function(data){
console.log(data);
//alert("ok");
});
event.preventDefault();
});
Where am I wrong?
serialize() will not pass image within it. It does not work with multipart formdata.
Instead use like this:
var formData = new FormData(this);
Pass this formData variable instead of $(this).serialize()
Try this
$('#button_name').on('click', function(event) {
event.preventDefault();
$.ajax({
url: "<?php echo base_url('settings/uploadprofilephoto');?>",
type: 'post',
dataType: 'json',
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(json) {
// Success Stuff
},
});
});
On the view part
<button type="button" id="button_name">Upload</button>
You have to try this
$('#logo_form').on('submit',function(form){
form.preventDefault();
var me = $(this);
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: me.attr('action'), // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$("#logo_form")[0].reset();
$('#logo_success').html(response); // display success response from the server
window.setTimeout(function(){location.reload()},1000);
},
error: function (response) {
$('#error').html(response); // display error response from the server
}
});
});
Please check below mentioned solution, This will help you to send file with input data.
var myFormData = new FormData();
$(document).on("click", "button", function(e) {
e.preventDefault();
var inputs = $('#my_form input[type="file"]');
$.each(inputs, function(obj, v) {
var file = v.files[0];
var filename = $(v).attr("data-filename");
var name = $(v).attr("id");
myFormData.append(name, file, filename);
});
var inputs = $('#my_form input[type="text"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("id");
var value = $(v).val();
myFormData.append(name, value);
});
var xhr = new XMLHttpRequest;
xhr.open('POST', '/echo/html/', true);
xhr.send(myFormData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my_form" enctype="multipart/form-data">
<input type="file" name="file_1" id="file_1" data-filename="image.jpg"><br />
<input type="text" name="check1" id="check1"/><br />
<input type="text" name="check2" id="check2"/><br />
<input type="text" name="check3" id="check3"/><br />
<button>Submit</button>
</form>
Let me know if it not works.