500 Interval server error in ajax - php

I would like to ask what are the causes of this error? When i check the inspect elements to check it out, it said console.log(xhr.status); console.log(xhr.responseText); console.log(thrownError); are my errors. what is wrong in here?
My view
<h3> Product
<span class = "fa fa-plus-square-o ">
<div class="modal fade" id="new_product" role="dialog" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add New Product</h4>
</div>
<form method="post" id="form-submit" enctype="multipart/form-data">
<!-- <form method="post" enctype="multipart/form-data" name = "select_design"action="<?php echo base_url(); ?>Administrator/new_product"> -->
<div class="modal-body">
<!-- <div class="form-group">
<label class="control-label ">Genre:</label>
<select name = "product_genre" class="select2_multiple " multiple="multiple" >
<option>Choose option</option>
<option value ="drama">Drama</option>
<option value ="action">Action</option>
<option value ="comedy">Comedy</option>
<option value ="horror">Horror</option>
</select>
</div> -->
<div class="form-group">
<label>Product Name</label>
<input type="text" class="form-control" id="product_name" name="product_name" placeholder="Name" value="<?php echo set_value('product_name'); ?>"> </div>
<div class="form-group">
<label>Product Description</label>
<input type="text" class="form-control" id="product_description" name="product_description" placeholder="Description" value="<?php echo set_value('product_description'); ?>">
</div>
<div class="form-group">
<label>Stocks</label>
<input type="number" class="form-control" id="quantity" name="quantity" placeholder="Quantity" value="<?php echo set_value('quantity'); ?>">
</div>
<div class="form-group">
<label>Product Image</label>
<input type="file" required class="form-control" id="userfile" name="userfile">
</div>
<div class="form-group">
<label>Product Price</label>
<input type="number" min="1" class="form-control" id="product_price" name="product_price" placeholder="Price" value="<?php echo set_value('price'); ?>">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Register</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
My js
<script>
$("#form-submit").on('submit',function(event){
// $.LoadingOverlay("show");
var form = new FormData(document.getElementById("form-submit"));
$.ajax({
url: base_url + "Administrator/new_product",
type: "POST",
data: form,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function(data) {
var result = JSON.parse(data);
//alert(data);
if(result===1)
{
swal({
type: 'success',
html: 'New Product Added',
timer: 2000,
})
setTimeout(function() {
document.location.href= base_url + "Administrator/view_products";
}, 2000);
}
else
{
swal({
type: 'error',
html: result
});
}
// $.LoadingOverlay("hide");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(xhr.responseText);
console.log(thrownError);
}
})
event.preventDefault();
});
</script>
My controller
public function new_product()
{
// $data['new_product'] = $this->AdministratorModel->getCourses();
$config['upload_path'] = './products/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048000';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
$this->form_validation->set_rules('product_name', ' Name', 'required|trim');
$this->form_validation->set_rules('product_description', ' Name', 'required|trim');
$this->form_validation->set_rules('quantity', 'stocks', 'required|trim');
$this->form_validation->set_rules('product_price', 'price', 'required|trim');
$this->form_validation->set_rules('userfile', 'image', 'callback_handle_upload');
if ($this->form_validation->run() == FALSE)
{
echo json_encode(validation_errors());
}
else
{
$products = array(
'product_name' => strip_tags($_POST['product_name']),
'product_description' => strip_tags($_POST['product_description']),
'product_category' => "Drama",
'product_quantity' => strip_tags($_POST['quantity']),
'product_image' => $this->input->post('userfile'),
'upload_data' => $this->upload->data(),
'product_price' => strip_tags($_POST['product_price'])
);
$this->AdministratorModel->addProduct($products);
echo json_encode(1);
}
}
My model
public function addProduct($products)
{
$products = array(
'product_name' => strip_tags($_POST['product_name']),
'product_description' => strip_tags($_POST['product_description']),
'product_category' => strip_tags($_POST['product_genre']),
'product_quantity' => strip_tags($_POST['quantity']),
'product_image' => $this->input->post('userfile'),
'product_image' => $this->upload->data('file_name'),
'product_price' => strip_tags($_POST['product_price'])
);
$this->db->insert('products',$products);
}

Related

Updating Image in Modal Yajra Datatable

I'm trying to achieve updating Image I tried finding for the answer but it seems that they don't work on mine maybe because I am using Yajra DataTables, I already inserted or added the image seems to be working fine but whenever I click the button it doesn't popup the modal Thank you in Advance.
This is my Controller:
public function edit($id)
{
if (request()->ajax()) {
$shippings = Shipping_data::findOrFail($id);
return response()->json(['result' => $shippings]);
}
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Shipping_data $shippings_data)
{
$rules = array(
'name' ,
'mobile',
'items',
'shippingAddress',
'amount',
'facebookLink',
'facebookName',
"modePayment",
"shipVia"=> 'required',
"trackingNumber"=> 'required',
"shippingReceipt"=> 'required',
"shippingCharged"=> 'required',
"shippingWeight"=> 'required'
);
$error = Validator::make($request->all(), $rules);
if ($error->fails()) {
return response()->json(['errors' => $error->errors()->all()]);
}
// Handle File Upload
if ($request->hasFile('shippingReceipt')) {
// Get filename with the extension
$filenameWithExt = $request->file('shippingReceipt')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('shippingReceipt')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('shippingReceipt')->storeAs('public/shippingReceipts', $fileNameToStore);
}else {
$fileNameToStore = '';
}
$form_data = array(
'name' => $request->name,
'mobile'=> $request->mobile,
'items'=> $request->items,
'shippingAddress'=> $request->shippingAddress,
'amount'=> $request->amount,
'facebookLink'=> $request->facebookLink,
'facebookName'=> $request->facebookName,
"modePayment"=> $request->modePayment,
"shipVia"=> $request->shipVia,
"trackingNumber"=> $request->trackingNumber,
"shippingReceipt"=> $request->fileNameToStore,
"shippingWeight"=> $request->shippingWeight,
"shippingCharged"=> $request->shippingCharged,
);
Shipping_data::whereId($request->hidden_id)->update($form_data);
return response()->json(['success' => 'Shipping Data is successfully updated']);
}
This is my blade.php:
#extends('layouts.navbar')
#section('content')
<br />
<br />
<br />
Add Order Data
<br>
<br>
<!-- Table -->
<div style="margin: 10px 15px;">
<table id="shipping_table" class="table table-bordered table-striped ">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Mobile Number</th>
<th scope="col">Item Orders</th>
<th scope="col">Shipping Address</th>
<th scope="col">Amount</th>
<th scope="col">Facebook Link</th>
<th scope="col">Facebook Name</th>
<th scope="col">Mode of Payment</th>
<th scope="col">Ship Via</th>
<th scope="col">Tracking Number</th>
<th scope="col">Shipping Receipt</th>
<th scope="col">Shipping Charged</th>
<th scope="col">Shipping Weight</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
<br />
<br />
<!-- End Table -->
</body>
</html>
<!-- Modal -->
<div id="formModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title text-center">Add Shipping Data</h4>
</div>
<div class="modal-body">
<span id="form_result"></span>
<form method="post" id="shipping_form" class="form-horizontal">
#csrf
#if(Auth::check() && Auth::user()->role == "admin")
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" placeholder="Please Enter Client Name"
id="name">
</select>
</div>
<div class="form-group">
<label>Mobile</label>
<input type="text" class="form-control" name="mobile" placeholder="Please Enter Mobile Number"
id="mobile">
</div>
<div class="form-group">
<label>Items Order</label>
<input type="text" class="form-control" name="items" placeholder="Please Enter Items Order"
id="items">
</div>
<div class="form-group">
<label>Shipping Address</label>
<input type="text" class="form-control" name="shippingAddress" id="shippingAddress"
placeholder="Please Enter Shipping Address">
</div>
<div class="form-group">
<label>Amount</label>
<input type="text" class="form-control" name="amount" placeholder="Please Enter Amount"
id="amount">
</div>
<div class="form-group">
<label>Facebook Link</label>
<input type="text" class="form-control" name="facebookLink" id="facebookLink"
placeholder="Please Enter Facebook Link">
</div>
<div class="form-group">
<label>Facebook Name</label>
<input type="text" class="form-control" name="facebookName" id="facebookName"
placeholder="Please Enter Facebook Name">
</div>
<div class="form-group">
<label>Mode of Payment</label>
<input type="text" class="form-control" name="modePayment" id="modePayment"
placeholder="Please Enter Mode of Payment">
</div>
#endif
#if(Auth::check() && Auth::user()->role == "employee")
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" placeholder="Please Enter Name" id="name"
READONLY>
</div>
<div class="form-group">
<label>Mobile</label>
<input type="text" class="form-control" name="mobile" placeholder="Please Enter Mobile Number"
id="mobile" READONLY>
</div>
<div class="form-group">
<label>Items Order</label>
<input type="text" class="form-control" name="items" placeholder="Please Enter Items Order"
id="items" READONLY>
</div>
<div class="form-group">
<label>Shipping Address</label>
<input type="text" class="form-control" name="shippingAddress" id="shippingAddress" READONLY
placeholder="Please Enter Shipping Address">
</div>
<div class="form-group">
<label>Amount</label>
<input type="text" class="form-control" name="amount" placeholder="Please Enter Amount"
id="amount" READONLY>
</div>
<div class="form-group">
<label>Facebook Link</label>
<input type="text" class="form-control" name="facebookLink" id="facebookLink" READONLY
placeholder="Please Enter Facebook Link">
</div>
<div class="form-group">
<label>Facebook Name</label>
<input type="text" class="form-control" name="facebookName" id="facebookName" READONLY
placeholder="Please Enter Facebook Name">
</div>
<div class="form-group">
<label>Mode of Payment</label>
<input type="text" class="form-control" name="modePayment" id="modePayment" READONLY
placeholder="Please Enter Mode of Payment">
</div>
#endif
<div class="form-group">
<label>Shipping Via</label>
<input type="text" class="form-control" name="shipVia" placeholder="Please Enter Shipping Via"
id="shipVia">
</div>
<div class="form-group">
<label>Tracking Number</label>
<input type="text" class="form-control" name="trackingNumber" id="trackingNumber"
placeholder="Please Enter Tracking Number">
</div>
<div class="form-group">
<label>Shipping Receipt</label>
<br>
<input type="file" class="form-control file-form" name="shippingReceipt" id="shippingReceipt">
</div>
<div class="form-group">
<label>Shipping Charged</label>
<input type="text" class="form-control" name="shippingCharged" id="shippingCharged"
placeholder="Please Enter Shipping Charged">
</div>
<div class="form-group">
<label>Shipping Weight</label>
<input type="text" class="form-control" name="shippingWeight" id="shippingWeight"
placeholder="Please Enter Shipping Weight">
</div>
<br />
<div class="form-group" align="center">
<input type="hidden" name="action" id="action" value="Add" />
<input type="hidden" name="hidden_id" id="hidden_id" />
<input type="submit" name="action_button" id="action_button" class="btn btn-success"
value="Add" />
</div>
</form>
</div>
</div>
</div>
</div>
<div id="confirmModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Confirmation</h2>
</div>
<div class="modal-body">
<h4 align="center" style="margin:0;">Are you sure you want to remove this data?</h4>
</div>
<div class="modal-footer">
<button type="button" name="ok_button" id="ok_button" class="btn btn-danger">OK</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<!-- End Modal -->
<script>
$(document).ready(function () {
$('#shipping_table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('shipping.index') }}",
},
columns: [
{
data: 'name',
name: 'name'
},
{
data: 'mobile',
name: 'mobile'
},
{
data: 'items',
name: 'items'
},
{
data: 'shippingAddress',
name: 'shippingAddress'
},
{
data: 'amount',
name: 'amount'
},
{
data: 'facebookLink',
name: 'facebookLink'
},
{
data: 'facebookName',
name: 'facebookName'
},
{
data: 'modePayment',
name: 'modePayment'
},
{
data: 'shipVia',
name: 'shipVia'
},
{
data: 'trackingNumber',
name: 'trackingNumber'
},
{
data: 'shippingReceipt',
name: 'shippingReceipt',
"render": function (data, type, full, meta) {
return "<img src=\"storage/shippingReceipts/" + data + "\" height=\"50\"/>";
},
},
{
data: 'shippingCharged',
name: 'shippingCharged'
},
{
data: 'shippingWeight',
name: 'shippingWeight'
},
{
data: 'action',
name: 'action',
orderable: false
}
]
});
$('#create_record').click(function () {
$('.modal-title').text('Add Client Data');
$('#action_button').val('Add Client Data');
$('#action').val('Add');
$('#form_result').html('');
$('#formModal').modal('show');
});
$('#shipping_form').on('submit', function (event) {
event.preventDefault();
var action_url = '';
if ($('#action').val() == 'Add') {
action_url = "{{ route('shipping.store') }}";
}
if ($('#action').val() == 'Edit') {
action_url = "{{ route('shipping.update') }}";
}
$.ajax({
url: action_url,
method: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
var html = '';
if (data.errors) {
html = '<div class="alert alert-danger">';
for (var count = 0; count < data.errors.length; count++) {
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if (data.success) {
html = '<div class="alert alert-success">' + data.success + '</div>';
$('#shipping_form')[0].reset();
$('#shipping_table').DataTable().ajax.reload();
}
$('#form_result').html(html);
}
});
});
$(document).on('click', '.edit', function () {
var id = $(this).attr('id');
$('#form_result').html('');
$.ajax({
url: "/shipping/" + id + "/edit",
dataType: "json",
success: function (data) {
$('#name').val(data.result.name);
$('#mobile').val(data.result.mobile);
$('#items').val(data.result.items);
$('#shippingAddress').val(data.result.shippingAddress);
$('#amount').val(data.result.amount);
$('#facebookLink').val(data.result.facebookLink);
$('#facebookName').val(data.result.facebookName);
$('#modePayment').val(data.result.modePayment);
$('#shipVia').val(data.result.shipVia);
$('#trackingNumber').val(data.result.trackingNumber);
$('#shippingReceipt').val(data.result.shippingReceipt);
$('#shippingCharged').val(data.result.shippingCharged);
$('#shippingWeight').val(data.result.shippingWeight);
$('#hidden_id').val(id);
$('.modal-title').text('Edit Record');
$('#action_button').val('Save');
$('#action').val('Edit');
$('#formModal').modal('show');
}
})
});
var shipping_id;
$(document).on('click', '.delete', function () {
shipping_id = $(this).attr('id');
$('#confirmModal').modal('show');
});
$('#ok_button').click(function () {
$.ajax({
url: "shipping/destroy/" + shipping_id,
beforeSend: function () {
$('#ok_button').text('Deleting...');
},
success: function (data) {
setTimeout(function () {
$('#confirmModal').modal('hide');
$('#shipping_table').DataTable().ajax.reload();
}, 2000);
}
})
});
});
</script>
#endsection
You can't view an image on input field, but you can do it with img tag :
<img class="img-circle" id="view_photo">
Change this line :
$('#shippingReceipt').val(data.result.shippingReceipt);
To,
$("#view_photo").attr("src", data.result.shippingReceipt);

Laravel post form without refresh problem

I wrote a code to submit a form without page refresh in laravel and here's my codes :
my view :
<form action="{{ url('/admin/products/new') }}" method="post">
{{ csrf_field() }}
<div class="form-group row">
<label for="example-text-input" class="col-sm-2 col-form-label">pid</label>
<div class="col-sm-10">
<input type="text" id="pid" name="pid" class="form-control" placeholder="مثال : Oil distillation machine" id="name">
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-sm-2 col-form-label">name</label>
<div class="col-sm-10">
<input type="text" id="name" name="name" class="form-control" placeholder="مثال : Oil distillation machine" id="name">
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-sm-2 col-form-label">value</label>
<div class="col-sm-10">
<input type="text" id="value" name="value" class="form-control" placeholder="مثال : Oil distillation machine" id="name">
</div>
</div>
<div class="form-group">
<button type="submit" id="submit" class="btn btn-primary btn-lg text-center waves-effect waves-light">ارسال</button> </div>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#submit').click(function(e){
e.preventDefault();
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/admin/products/new') }}",
method: 'post',
data: {
name: jQuery('#pid').val(),
email: jQuery('#name').val(),
subject: jQuery('#value').val(),
},
success: function(data){
jQuery.each(data.errors, function(key, value){
jQuery('.alert-danger').show();
jQuery('.alert-danger').append('<p>'+value+'</p>');
});
}
});
});
});
</script>
</form>
my controller :
public function add_product_post(Request $request)
{
$pid = $request->pid;
$name = $request->name;
$value = $request->value;
DB::table('product_features')->insert([
'pid' => $pid,
'name' => $name,
'value' => $value
]);
return ['message' => 'success'];
}
my problem is that when i click on submit button i just get a response in blank page {"message":"success"}
I want to submit my form without any page refreshing.
What is wrong with my code?
Thanks
In your controller action, you just return an array, plz change it to response:
public function add_product_post(Request $request)
{
$pid = $request->pid;
$name = $request->name;
$value = $request->value;
DB::table('product_features')->insert([
'pid' => $pid,
'name' => $name,
'value' => $value
]);
return response()->json(['message' => 'success']);
}
Another thing is in jquery ajax,you need to display the success message instead of the error message.
I'm not sure but try to change the button type into "button"
<button type="button" id="submit" class="btn btn-primary btn-lg text-center waves-effect waves-light">ارسال</button>

Double insertion of data using modal

I`m working on PHP + MYSQL + AJAX project. I used Bootstrap Modal when adding data. After first time I click add, it will insert two records however it only occurs in its first time click.
Is there any way to prevent saving two records.
I appreciate your help and suggestion. Thanks
This is my modal
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data" class="form-horizontal">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label class="col-lg-3 control-label">Name</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sName" maxlength="150" id="sName" placeholder="Enter your Name" />
<span id='remainingC'></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sUsername" maxlength="20" id="sUsername" placeholder="Enter your Username"/>
<span id='remainingCu'></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Birthday</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sBirthday"
onchange ="getAge();" maxlength="20" id="sBirthday" placeholder="YYYY-mm-dd"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Age</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="iAge" maxlength="3" id="iAge" placeholder="Autofill when you fill Birthday"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sEmail" id="sEmail" placeholder="Enter your Email - eg. jb#gmail.com"/>
</div>
</div>
My AJAX requests
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
$('#operation').val("Add");
// $('#user_uploaded_image').html('');
});
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 4],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var sName = $('#sName').val();
var sUsername = $('#sUsername').val();
var sBirthday = $('#sBirthday').val();
var iAge = $('#iAge').val();
var sEmail = $('#sEmail').val();
if(sName != '' && sUsername != '' && sBirthday != '' && iAge != '' && sEmail != '')
{
$.ajax({
url:"insert.php",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Both Fields are Required");
}
});
This is my Function for adding (insert.php)
if($_POST["operation"] == "Add")
{
$statement = $connection->prepare("
INSERT INTO users (sName, sUsername, sBirthday, iAge, sEmail)
VALUES (:sName, :sUsername, :sBirthday, :iAge, :sEmail)
");
$result = $statement->execute(
array(
':sName' => $_POST["sName"],
':sUsername' => $_POST["sUsername"],
':sBirthday' => $_POST["sBirthday"],
':iAge' => $_POST["iAge"],
':sEmail' => $_POST["sEmail"]
)
);
if(!empty($result))
{
echo 'Data Inserted';
}
}
Duplicate data after 1st click of add button in modal:
Duplicate

How to upload image in codeigniter using ajax

Here is my code,
Please check this, Iam trying to upload image its not working. Iam passing data through ajax using id.
Iam getting image name, while passing through codeigniter its showing error undefined user_img
Below code is Ajax
$('#profile_set').validate({
submitHandler: function(form) {
user_zip = $("#user_zip").val();
first_name = $("#xx_first_name").val();
db_email = $("#db_email").val();
datepicker = $("#datepicker").val();
last_name = $("#xx_last_name").val();
new_image = $("#new_image").val();
$.ajax({
url: "<?php echo base_url('myaccount/profile/'.$this->session->userdata('id').''); ?>",
type: "post",
fileElementId :'new_image',
dataType: 'json',
data: {
xx_first_name: first_name,
xx_last_name: last_name,
db_email: db_email,
db_dob: datepicker,
user_zip: user_zip,
user_img: new_image
},
success: function (data) {
if(data.status == 'success'){
$('#message').removeClass('alert alert-danger');
$('#message').addClass('alert alert-success');
$('#message').empty();
$('#message').append(data.message);
$('#message').fadeOut(3000);
}
else if(data.status == 'fail') {
$('#message').removeClass('alert alert-success');
$('#message').addClass('alert alert-danger');
$('#message').empty();
$('#message').append(data.message);
}
}
});
}
});
In this function am getting image name, Its showing undefined index of profile_img['file_name' => $_FILES['user_img']['name'] ]
public function profile($id)
{
$user_id = $id;
$profile_img = $this->input->post('user_img');
if ($user_id !== '' AND $user_id > 0) {
if(!empty($profile_img)){
$uploadconfig = array(
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png',
'max_size' => '204800',
'file_name' => $_FILES['user_img']['name'],
'encrypt_name' => TRUE
);
print_r($uploadconfig); exit;
$this->load->library('upload', $uploadconfig);
if ( ! $this->upload->do_upload("user_img")) {
echo "failed to upload file(s)";
}
$this->upload->initialize($uploadconfig);
$this->upload->do_upload("user_img");
$upload_data = $this->upload->data();
$user_profile = $upload_data['file_name'];
$data = array();
$data['first_name'] = $this->input->post('xx_first_name');
$data['last_name'] = $this->input->post('xx_last_name');
$data['email'] = $this->input->post('db_email');
$data['user_dob'] = $this->input->post('db_dob');
$data['user_zip'] = $this->input->post('user_zip');
$data['user_img'] = $user_profile;
}
else {
$data = array();
$data['first_name'] = $this->input->post('xx_first_name');
$data['last_name'] = $this->input->post('xx_last_name');
$data['email'] = $this->input->post('db_email');
$data['user_dob'] = $this->input->post('db_dob');
$data['user_zip'] = $this->input->post('user_zip');
}
$update_set = $this->users->update($id, $data);
if ($update_set)
{
$ret['status'] = 'success';
$ret['message'] = 'Updated successfully';
echo json_encode($ret);
}
else
{
$ret['status'] = 'fail';
$ret['message'] = 'Error while updating';
echo json_encode($ret);
}
}
}
My forum Code
<div class="account_forum" id="profile">
<h2 class="forum_title">Profile</h2>
<form id="profile_set">
<div class="row row_space">
<div class="col-md-10">
<a class="profile-pic" id="existing_pic">
<div class="profile-pic" style="background-image: url('<?php echo base_url('uploads/')?><?php echo #$users->user_img ?>')" >
<span class="glyphicon glyphicon-camera"></span>
<span>Change Image</span>
</div>
</a>
<input type='file' name="new_image" id="new_image" onchange="readURL(this);" style="display:none;" />
<a class="profile-pic" id="new_upload">
<div class="profile-pic" id="view_image">
<span class="glyphicon glyphicon-camera"></span>
<span>Change Image</span>
</div>
</a>
</div>
</div>
<div class="row row_space">
<div class="col-md-5">
<label>First Name</label>
<input type="text" name="xx_first_name" id="xx_first_name" class="form-control" placeholder="John" value="<?php echo set_value('xx_first_name', #$users->first_name);?>" required>
</div>
<div class="col-md-5">
<label>Last Name</label>
<input type="text" name="xx_last_name" id="xx_last_name" class="form-control" placeholder="Doe" value="<?php echo set_value('xx_last_name', #$users->last_name);?>" required>
</div>
</div>
<div class="row row_space">
<div class="col-md-5">
<label>Email</label>
<input type="text" name="db_email" class="form-control" id="db_email" placeholder="jdoe#gmail.com" value="<?php echo set_value('db_email', #$users->email);?>" required>
</div>
<div class="col-md-5">
<label>Birthday</label>
<input type="text" name="db_dob" class="form-control" data-toggle="datepicker" placeholder="00/0/0000" id="datepicker" value="<?php echo set_value('db_dob', #$users->user_dob);?>" required>
</div>
</div>
<div class="row row_space">
<div class="col-md-5">
<label>Postal Code</label>
<input type="text" id="user_zip" name="user_zip" class="form-control" placeholder="00000" value="<?php echo set_value('xx_user_zip', #$users->user_zip);?>" required>
</div>
</div>
<input type="hidden" id="profile_old" name="profile_old" value="<?php $users->user_img; ?>">
<div class="row row_space">
<div class="col-md-5">
<button type="submit" name="" class="acct_btn" value="Update">Update Profile</button>
</div>
</div>
</form>
</div>
for upload new image to server with ajax, you need to use new FormData():
var fd = new FormData();
fd.append( 'user_zip', user_zip);
fd.append( 'xx_first_name', first_name);
fd.append( 'db_email', db_email);
fd.append( 'db_dob', datepicker);
fd.append( 'xx_last_name', last_name);
fd.append( 'user_img', $('#new_image')[0].files[0]);
$.ajax({
url: "<?php echo base_url('myaccount/profile/'.$this->session->userdata('id').''); ?>",
type: "post",
data: fd,
success: function () {
// do something
}
});

bootstrap modal upload file

I'm having a problem to upload a file using bootstrap modal upload file
This is my modal code
<div id="myModalAtiv" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="alert alert-info" id="myModalLabel"><span class="glyphicon glyphicon-pencil"></span> Edição de Atividades</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="formacoes" enctype="multipart/form-data">
<div class="form-group">
<input type="hidden" name="idformacao" id="idformacao">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Escola:</label>
<input class="form-control" name="escola" id="escola" disabled="true">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Nome:</label>
<input class="form-control" name="nome" id="nome">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Data:</label>
<div class="input-group date" id="datetimePicker">
<input type="text" class="form-control" name="inicio" id="inicio" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</div>
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Horas:</label>
<input class="form-control" name="horas" id="horas">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Local:</label>
<input class="form-control" name="local" id="local">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Destinatários:</label>
<input class="form-control" name="destinatarios" id="destinatarios">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Data Limite:</label>
<div class="input-group date" id="dataLimitePicker">
<input type="text" class="form-control" name="dataLimite" id="dataLimite" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input span3"><i class="icon-file fileupload-exists"></i>
<span class="fileupload-preview"></span></div>
<span class="btn btn-file"><input type="file" name="fileToUpload" id="fileToUpload" /></span>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-info">Atualizar</button>
<button type="button" class="btn btn-default"data-dismiss="modal">Fechar</button>
</div>
</form>
</div>
</div><!-- End of Modal body -->
</div><!-- End of Modal content -->
and this is my ajax function to send the form
<script>
$(document).ready(function () {
$('#datetimePicker').datetimepicker({format: 'YYYY-MM-DD'});
$('#dataLimitePicker').datetimepicker({format: 'YYYY-MM-DD'});
$('#formacoes').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
nome: {
validators: {
notEmpty: {
message: 'Tem de definir alguma formação'
}
}
}
},inicio: {
validators: {
notEmpty: {
message: 'Data inicial obrigatória'
},
date: {
format: 'YYYY-MM-DD',
message: 'Data inicial inválida'
}
}
},
dataLimite: {
validators: {
notEmpty: {
message: 'Data limite obrigatória'
},
date: {
format: 'YYYY-MM-DD',
message: 'Data limite inválida'
}
}
}
}).on('success.form.fv', function (e) {
e.preventDefault();
var $form = $(e.target),
fv = $form.data('formValidation');
$.ajax({
url: 'updates.php',
type: 'POST',
data: $form.serialize(),
success: function (response) {
console.log(response.status);
if (response.status === 'success') {
$("#myModalAtiv").modal('hide');
$('#respostas .modal-title').html('Sucesso');
$('#respostas .modal-body').html('Informação: ' + response.message);
$('#respostas').modal('show');
$('#respostas').on('hidden.bs.modal', function () {
window.location.reload(true);
});
}
}
});
});
});
All seems to be ok, but when i trying to send the from to my function it says
Notice: Undefined index: fileToUpload
This is my php function
$idformacao= filter_input(INPUT_POST, 'idformacao');
if ($idformacao != null) {
echo "aqui";
$userid = filter_input(INPUT_POST, 'userid');
$nome = filter_input(INPUT_POST, 'nome');
$inicio = filter_input(INPUT_POST, 'inicio');
$horas = filter_input(INPUT_POST, 'horas');
$local = filter_input(INPUT_POST, 'local');
$destinatarios = filter_input(INPUT_POST, 'destinatarios');
$dataLimite = filter_input(INPUT_POST, 'dataLimite');
$uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/uploads';
$uploadfile = $uploaddir . '/' . basename($_FILES['fileToUpload']['name']);
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
$target_path = "/uploads/" . basename($_FILES['fileToUpload']['name']);
$ret = $ebspma->updateFormacoes($idformacao, $nome, $inicio, $horas, $local, $destinatarios, $dataLimite,$target_path);
}
echo json_encode($ret);
}
And this is the line where i have the error
$uploadfile = $uploaddir . '/' . basename($_FILES['fileToUpload']['name']);
e.preventDefault();
var fileToUpload= $('#fileToUpload')[0].files[0];
var idformacao = $("#idformacao").val();
var formData = new FormData(this);
formData.append('fileToUpload', fileToUpload);
formData.append('idformacao', idformacao);
//use this same format to append other of your fields
$.ajax({
type:'POST',
url: 'updates.php',
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(response){
//You can continue with your response status code here
}
Just hope that this works for you.
Add data-bs-focus="false" in modal first line at the end:
id="myModalAtiv" class="modal fade bs-example-modal-lg" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-bs-focus="false"

Categories