Ajax file upload without formdata - php

when i try to upload a file, all data send to database but the input file is empty and won't upload the file how can i send file with my
actual ajax submit form ? without dataForm i'm new to ajax and mysql
here's my code:
function getUsers(){
$.ajax({
type: 'POST',
url: 'tpl/add.php',
data: 'action_type=view&'+$("#userForm").serialize(),
success:function(html){
$('#userData').html(html);
}
});
}
function userAction(type,idb){
id = (typeof idb == "undefined")?'':idb;
var statusArr = {add:"ajouter",edit:"mises à jour",delete:"supprimer"};
var userData = '';
if (type == 'add') {
userData = $("#addForm").find('.form').serialize()+'&action_type='+type+'&idb='+idb;
}else if (type == 'edit'){
userData = $("#editForm").find('.form').serialize()+'&action_type='+type;
}else if (type == 'view'){
userData = $("#viewForm").find('.form').serialize()+'&action_type='+type;
}else{
userData = 'action_type='+type+'&idb='+idb;
}
$.ajax({
url: 'tpl/add.php',
cache: false,
data: userData,
type: 'POST',
contentType: false,
processData: false,
success:function(msg){
if(msg == 'ok'){
alert('Le model a été '+statusArr[type]+' avec succès.');
getUsers();
$('.form')[0].reset();
$('#myModal2').modal('hide');
$('#myModal').modal('hide');
}else{
alert('Un probleme à été detecter, veuillez reessayer.');
}
}
});
}
function editUser(idb){
$.ajax({
type: 'POST',
dataType:'JSON',
url: 'tpl/add.php',
data: 'action_type=data&idb='+idb,
success:function(data){
$('#idbEdit').val(data.idb);
$('#modelEdit').val(data.model);
$('#urldemoEdit').val(data.urldemo);
$('#modelfichEdit').val(data.modelfich);
$('#etatEdit').val(data.etat);
$('#editForm').slideDown();
}
});
}
<div class="modal fade" id="myModal" 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">Ajouter un modele</h4>
</div>
<div class="modal-body" id="addForm">
<form class="form form-horizontal" method="post" id="userForm" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-3">Modele HTML</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="model" id="model"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Aperçu</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="urldemo" id="urldemo"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Fichier HTML </label>
<div class="col-sm-9">
<input type="file" name="file" id="file" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Etat</label>
<div class="col-sm-9">
<select name="etat" id="etat" class="form-control">
<option value="0">activé</option>
<option value="1">désactivé</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
Ajouter
<button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
</div>
</form>
</div>
</div>
</div>

Related

PHP/AJAX: Insert BLOB into MySQL Database

I have some hard times to save a blob (image file) to my sql-database.
I have three files: a html form (form.php), an ajax script (ajax.js) and a php-file (save.php).
I think i have some errors in my ajax.js, but after a long google search i couldn`t find a good solution. There must be a problem with the blob handling in JS....
HTML Form:
<div id="editEmployeeModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form id="update_form" enctype="multipart/form-data">
<div class="modal-header">
<h4 class="modal-title">table bearbeiten</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<input type="hidden" id="id_u" name="id" class="form-control" required>
<div class="form-group">
<label>Image</label>
<input type="file" id="image_u" name="image" class="form-control" required>
</div>
<div class="form-group">
<label>Überschrift 1</label>
<input type="text" id="header1_u" name="header1" class="form-control" required>
</div>
<div class="form-group">
<label>Überschrift 2</label>
<input type="text" id="header2_u" name="header2" class="form-control" required>
</div>
<div class="form-group">
<label>Text</label>
<input type="text" id="text_u" name="text" class="form-control" required>
</div>
<div class="form-group">
<label>Link</label>
<input type="text" id="link_u" name="link" class="form-control" required>
</div>
<div class="form-group">
<label>Link-Text</label>
<input type="text" id="linkText_u" name="linkText" class="form-control" required>
</div>
<div class="form-group">
<label>Datum</label>
<input type="date" id="datum_u" name="datum" class="form-control" required>
</div>
</div>
<div class="modal-footer">
<input type="hidden" value="2" name="type">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
<button type="button" class="btn btn-info" id="update">Update</button>
</div>
</form>
</div>
</div>
</div>
In form.php i specified all my Inputs and for the image type=file
Ajax Code:
$(document).on('click','.update',function(e) {
var id=$(this).attr("data-id");
var image=$(this).attr("data-image");
var header1=$(this).attr("data-header1");
var header2=$(this).attr("data-header2");
var text=$(this).attr("data-text");
var link=$(this).attr("data-link");
var linkText=$(this).attr("data-linkText");
var datum=$(this).attr("data-datum");
$('#id_u').val(id);
$('#image_u').val(image);
$('#header1_u').val(header1);
$('#header2_u').val(header2);
$('#text_u').val(text);
$('#link_u').val(link);
$('#linkText_u').val(linkText);
$('#datum_u').val(datum);
});
$(document).on('click','#update',function(e) {
var data = $("#update_form").serialize();
$.ajax({
data: data,
enctype: 'multipart/form-data',
type: "post",
url: "save.php",
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$('#editEmployeeModal').modal('hide');
alert('Data updated successfully !');
location.reload();
}
else if(dataResult.statusCode==201){
alert(dataResult);
}
}
});
});
My PHP-Code:
if($_POST['type']==2){
$id=$_POST['id'];
$image= base64_encode(file_get_contents($_FILES['image']['tmp_name']));
$header1=$_POST['header1'];
$header2=$_POST['header2'];
$text=$_POST['text'];
$link=$_POST['link'];
$linkText=$_POST['linkText'];
$datum=$_POST['datum'];
$sql = "UPDATE `tblTable` SET `image`='$image',`header1`='$header1',`header2`='$header2',`text`='$text',`link`='$link',`linkText`='$linkText',`datum`='$datum' WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo json_encode(array("statusCode"=>200));
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
}
My Datbase-Connection works fine. I can write and read all other Data (Text and Date) to my local Database. I think my problem is in the ajax.js. How can i specify $('#image_u').val(image); that it must handle a blob file and not just normal text input. And do i have to modify these lines?
var data = $("#update_form").serialize();
$.ajax({
data: data,
enctype: 'multipart/form-data',
type: "post",
url: "save.php",

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

bootstrap modal insert form submit won't reset to add another entry

I am using php mysql to insert to the database and that was working, however the bootstrap modal won't let me submitting another item. The button still says inserting and the last inserted data is still showing in the inputs.
I want to insert multiple times as this becomes part of a larger edit form.
This is put outside of the edit form submit button:
<div id="add_data_Modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add A New Item</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<input type="hidden" name="job_id" id="job_id" value="<?php echo $job_id;?>">
<input type="hidden" class="form-control" id="job_mat_qty" name="job_mat_qty" value="1" />
<div class="form-group">
<label for="job_mat_desc" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea class="form-control editors" id="job_mat_desc" name="job_mat_desc" autocomplete="off" placeholder="Enter item title and / or description" />
</textarea>
</div>
</div>
<div class="form-group">
<label for="job_mat_cost" class="col-sm-2 control-label">Price</label>
<div class="col-sm-10">
<div class="input-group input-group"> <span class="input-group-addon"><?php echo CURRENCY ?></span>
<input type="text" class="form-control calculate invoice_product_price txt" autocomplete="off" id="job_mat_cost" name="job_mat_cost" aria-describedby="sizing-addon1" placeholder="0.00" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10"> </div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="insert" id="selected" value="Insert" class="btn btn-success" />
</div>
</form>
</div>
</div>
</div>
$(document).on('click', '.delete-rows', function(){
var id = $(this).attr("id");
if (confirm("Are you sure you want to delete this Item?")) {
$.ajax({
type: "POST",
url: "job_remove_material_new.php",
data: ({
id: id
}),
cache: false,
success: function(html) {
$(".delete_mem" + id).fadeOut('slow');
}
});
} else {
return false;
}
});
$('#insert_form').on("submit", function(event){
event.preventDefault();
if($('#job_mat_desc').val() == "")
{
alert("Description is required");
}
else
{
$.ajax({
url:"add_material.php",
method:"POST",
data:$('#insert_form').serialize(),
cache: false,
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#invoice_table').html(data);
}
});
$(function () {
$(document).on("hidden.bs.modal", "#add_data_Modal", function () {
$('#insert_form')[0].reset();
});
});
}
});
Sorry I have no clue how to add this code correctly for this forum so please be kind....
Thanks
You should try like this
$('#insert_form').on("submit", function(event){
event.preventDefault();
if($('#job_mat_desc').val() == "")
{
alert("Description is required");
}
else
{
$.ajax({
url:"add_material.php",
method:"POST",
data:$('#insert_form').serialize(),
cache: false,
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
//$('#insert_form')[0].reset();
$('#insert_form input[type="text"],textarea').val(''); // here is change
$('#add_data_Modal').modal('hide');
$('#invoice_table').html(data);
}
});
In my case it will work successfully so I hope it will help you

form validation code igniter doesn't work

i am a beginner in using form validation in codeigniter, now i am trying to use form validation codeigniter library, why this is not executed? i already loaded the $this->load->library('form_validation'); at the top of my controller. I mean i want the output where it puts error below my input type. Why my error in array('required' => 'Error Message on rule2 for this field_name')); doesnt appear in my view. Only in Response at console
Here is my fullcode:
VIEW:
<div class="modal fade large" id="admin_create_acct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header btn-success">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Create Account</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" id="frm_create_user">
<div class="form-group">
<label for="userFName" class="control-label col-sm-4">First Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="userFName" id="userFName" placeholder="First name">
<div class="msg"></div><!-- form-group -->
</div><!-- col-sm-6 -->
</div><!-- form-group -->
<div class="form-group">
<label for="userMName" class="control-label col-sm-4">Middle Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="userMName" id="userMName" placeholder="Middle name">
<div class="msg"></div><!-- form-group -->
</div><!-- col-sm-6 -->
</div><!-- form-group -->
</form><!-- form-horizontal -->
<button type="button" id="btn_reg" onclick="create_User()" class="btn btn-primary">Create Account</button>
i am just trying one input type and some error for validating, now here is my Controller code:
public function reg_user(){
$this->form_validation->set_rules('userFName', 'userFName', 'trim|required',
array('required' => 'Error Message on First name ')
);
$this->form_validation->set_rules('userMName', 'userMName', 'trim|required',
array('required' => 'Error Message on Middle Name')
);
if ($this->form_validation->run() == FALSE) {
$result['type'] = 'error';
$result['message'] = validation_errors();
}else {
$result['type'] = 'success';
$result['message'] = 'Whooos..! Your Succes Message';
}
echo json_encode($result);
}
my ajax from view:
function create_User() {
$.ajax({
url: siteurl+"admin_controls/reg_user",
type: "POST",
data: $("#frm_create_user").serialize(),
dataType: "JSON",
success: function(data) {
alert(" User Successfully Added added! ");
$("#frm_create_user")[0].reset();
}
});
}
Please follow this Method.
Or
If you just copy and paste this code it will definately work, all you need to just change the controller name in the form action
public function reg_user(){
$this->form_validation->set_rules('userFName', 'userFName', 'trim|required',
array('required' => 'Error Message on First name ')
);
$this->form_validation->set_rules('userMName', 'userMName', 'trim|required',
array('required' => 'Error Message on Middle Name')
);
if ($this->form_validation->run() == TRUE) {
$result['status'] = true;
$result['message'] = "Data inserted successfully.";
}else {
$result['status'] = false;
$result['message'] = $this->form_validation->error_array();
}
echo json_encode($result);
}
Now the Ajax Part
In Ajax i am using the FormData function instead of using serialize function. In case if you are going to upload files it will be helpful.
<script type="text/javascript">
$(document).ready(function() {
$("#form_data").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_data"));
$.ajax({
url : $("#form_data").attr('action'),
dataType : 'json',
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
$('.error').html('');
if(resp.status == false) {
$.each(resp.message,function(i,m){
$('.'+i).text(m);
});
}
}
});
});
return false;
});
View Part
<a data-toggle="modal" href='#admin_create_acct' class="list_sort">Select<a>
<div class="modal fade large" id="admin_create_acct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header btn-success">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Create Account</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" action="<?php echo base_url('Practice/test_user')?>" method="post" id="form_data">
<div class="form-group">
username : <input type="text" class="form-control" name="name">
<span class="error userFName"></span>
</div>
<div class="form-group">
password : <input type="text" class="form-control" name="userMName">
<span class="error userMName"></span>
</div>
<input type="submit" name="submit" value="submit">
</form>
</div>
</div>
</div>
</div>

Error file Upload Codeigniter Ajax

Error loading file to server and check everything and apparently it's okay please help
enter image description here
View
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form id="myForm" action="" method="post" class="form-horizontal" enctype="multipart/form-data">
<input type="hidden" name="txtProdId" value="0">
<div class="form-group">
<label for="category" class="label-control col-md-4">Nombre categoría</label>
<div class="col-md-8">
<select class="form-control col-md-4" for="name" name="txtId" id="categoria">
</select>
</div>
</div>
<div class="form-group">
<label for="subcategory" class="label-control col-md-4">Nombre subcategoría</label>
<div class="col-md-8">
<select class="form-control col-md-4" for="name" name="txtSubId" id="subcategoria">
</select>
</div>
</div>
<div class="form-group">
<label for="codig" class="label-control col-md-4">Codigo</label>
<div class="col-md-8">
<input type="text" name="txtCodigo" class="form-control">
</div>
</div>
<div class="form-group">
<label for="name" class="label-control col-md-4">Nombre Producto</label>
<div class="col-md-8">
<input type="text" name="txtProducto" class="form-control">
</div>
</div>
<div class="form-group">
<label for="description" class="label-control col-md-4">Descripción</label>
<div class="col-md-8">
<textarea class="form-control" name="txtDescripcion"></textarea>
</div>
</div>
<div class="form-group">
<label for="picture" class="label-control col-md-4">Imagen</label>
<div class="col-md-8">
<input type="file" name="txtFoto" id="txtFoto">
</div>
</div>
<div class="form-group">
<label for="cant" class="label-control col-md-4">Cantidad</label>
<label for="catalog" class="label-control col-md-4">Precio catálogo</label>
<label for="ofert" class="label-control col-md-4">Precio oferta</label>
</div>
<div class="input-group">
<div>
<input type="text" name="txtCantidad" class="form-control">
</div>
<span class="input-group-addon">-</span>
<div>
<input type="text" name="txtCatalogo" class="form-control">
</div>
<span class="input-group-addon">-</span>
<div>
<input type="text" name="txtOferta" class="form-control">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="button" id="btnSave" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
Jquery ajax View
$(function(){
showAllProduct();
//Add New
$('#btnAdd').click(function(){
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Registrar Producto');
$('#myForm').attr('action', '<?php echo base_url() ?>producto/addProduct');
});
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var codig = $('input[name=txtCodigo]');
var productName = $('input[name=txtProducto]');
var description = $('textarea[name=txtDescripcion]');
var cant = $('input[name=txtCantidad]');
var catalog = $('input[name=txtCatalogo]');
var ofert = $('input[name=txtOferta]');
var myFile = $("#txtFoto").val();
alert(myFile);
var result = '';
if(codig.val()==''){
codig.parent().parent().addClass('has-error');
}else{
codig.parent().parent().removeClass('has-error');
result +='1';
}
if(productName.val()==''){
productName.parent().parent().addClass('has-error');
}else{
productName.parent().parent().removeClass('has-error');
result +='2';
}
if(description.val()==''){
description.parent().parent().addClass('has-error');
}else{
description.parent().parent().removeClass('has-error');
result +='3';
}
if(cant.val()==''){
cant.parent().parent().addClass('has-error');
}else{
cant.parent().parent().removeClass('has-error');
result +='4';
}
if(catalog.val()==''){
catalog.parent().parent().addClass('has-error');
}else{
catalog.parent().parent().removeClass('has-error');
result +='5';
}
if(ofert.val()==''){
ofert.parent().parent().addClass('has-error');
}else{
ofert.parent().parent().removeClass('has-error');
result +='6';
}
//if()
if(result=='123456'){
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'añadido';
}else if(response.type=='update'){
var type ='actualizado';
}
$('.alert-success').html('Producto '+type+' con éxtito').fadeIn().delay(4000).fadeOut('slow');
showAllProduct();
}else{
alert('Error');
}
},
error: function(){
alert('No se puede añadir el dato');
}
});
}
});
});
Controller: The file 'txtFoto' does not arrive is as if it had been sent from the form
public function addProduct(){
$pathArchivo = $this->filePath();
$result = $this->m->addProduct($pathArchivo);
$msg['success'] = false;
$msg['type'] = 'add';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
public function filePath(){
$archivo=$_FILES['txtFoto'];
$config['upload_path'] = realpath(APPPATH.'../image/product/');
//$config['file_name'] = "nombre_archivo";
$config['allowed_types'] = "gif|jpg|jpeg|png";
$config['max_size'] = "50000";
$config['max_width'] = "2000";
$config['max_height'] = "2000";
$this->load->library('upload', $config);
$res = '';
if ( ! $this->upload->do_upload($archivo)) {
$error = array('error' => $this->upload->display_errors());
$res = 'hola no funciona';
print_r($error);
}else {
$file_data = $this->upload->data();
$file_path = './image/product/'.$file_data['file_name'];
$res = $file_path;
//print_r($data);
}
return $res;
}
Model
public function addProduct($path){
$field = array(
'sub_id'=>$this->input->post('txtSubId'),
'pr_codigo'=>$this->input->post('txtCodigo'),
'pr_nombre'=>$this->input->post('txtProducto'),
'pr_descripcion'=>$this->input->post('txtDescripcion'),
'pr_cantidad_stock'=>$this->input->post('txtCantidad'),
'pr_precio_catalogo'=>$this->input->post('txtCatalogo'),
'pr_precio_oferta'=>$this->input->post('txtOferta'),
'pr_foto'=>$path
);
$this->db->insert('producto', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
Your method is correct if you are trying to send a TEXT file.
Before you continue doing it with AJAX ,
Lets try and send the file normally
and you would want to receive it like this
$this->upload->do_upload('txtFoto');
I am just curious , If you are using ci's upload handler , why do you take it from PHP's $_FILE?
$_FILES['txtFoto']
Can you share any var_dump from $_FILES?
EDIT
You can do it via AJAX using FormData
var formData = new FormData($('#myForm'))
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
success: function(response){
//handle success
},
error: function(){
//handle error
alert('No se puede añadir el dato');
}
});
On the Controller ,
Initialize your upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
And make sure that the directory you want to upload your image is writable

Categories