Problem to insert into mysql with ajax and php - php

I want to insert in 2 tables of mysql, one table is about information of a product and the other one is for the images of those products.
I have this form
<form action="#" method="post" enctype="multipart/form-data" id="upload-multi-images">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Price</label>
<input type="text" name="price" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Stock</label>
<input type="text" name="stock" class="form-control" required autocomplete="off">
</div>
<div class="row">
<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="add-photo-container">
<div class="add-new-photo first" id="add-photo">
<span><i class="icon-camera"></i></span>
</div>
<input type="file" multiple id="add-new-photo">
</div>
</div>
<div class="button-container">
<button type="submit">Subir imágenes</button>
</div>
</form>
I get the images and the information with this JS
$(document).on("submit", "#upload-multi-images", function (e) {
e.preventDefault();
$(document).on("submit", "#upload-multi-images", function (e) {
var namePro = document.getElementsByName('name')[0].value;
var price = document.getElementsByName('price')[0].value;
var stock = document.getElementsByName('stock')[0].value;
formData.append('namePro', namePro);
formData.append('price', price);
formData.append('stock', stock);
e.preventDefault();
//Envio mediante Ajax
$.ajax({
url: "upload.php",
type: "post",
dataType: "json",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
loading(true, "Adding photo...");
},
success: function (res) {
loading(false);
if (res.status == "true") {
createImages(res.all_ids);
$("#Images form .row > div:not(#add-photo-container)").remove();
formData = new FormData();
} else {
alert(res.error);
}
},
error: function (e) {
console.log(e.responseText);
}
});
});
Then y send the images to this php to send them to mysql
$namePRO = $_REQUEST['namePro'];
$price = $_REQUEST['price'];
$stock = $_REQUEST['stock'];
$insertDatos = $conexion->prepare("INSERT INTO products (name , price, stock) VALUES (:name, :price, :stock)");
$wasUploadedDATA = $insertDatos->execute(array(
":name" => $namePRO,
":price" => $price,
":stock" => $stock,
));
$idPRO = $conexion->lastInsertId();
if (isset($_FILES) && !empty($_FILES)) {
$files = array_filter($_FILES, function($item) {
return $item["name"][0] != "";
});
foreach ($files as $file) {
$tmp_name = $file["tmp_name"];
$name = $file["name"];
$path = "/images/$name";
$pathSYS = "/var/www/html/images/$name";
$insertImages = $conexion->prepare("INSERT INTO product_files (id_pro, name, web_path, system_path) VALUES (:idPRO, :name, :path, :pathSYS)");
$wasUploaded = $insertImages->execute(array(
":name" => $name,
":idPRO" => $idPRO,
":path" => $path,
":pathSYS" => $pathSYS,
));
if ($wasUploaded) {
$id = $conexion->lastInsertId();
$data["all_ids"]["id_$id"]["id"] = $id;
$data["all_ids"]["id_$id"]["name"] = $name;
move_uploaded_file($tmp_name, "images/$name");
}
else {
die("There was an error. Please contact with the admin.");
}
}
}
I also have these other JS but I think they are not very important
function getRandomString(length) {
var text = "";
var possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function createPreview(file, id) {
var imgCodified = URL.createObjectURL(file);
var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12"
id="'
+ id + '"><div class="image-container"> <figure> <img src="' + imgCodified +
'" alt="Foto del usuario"> <figcaption> <i class="icon-cross"></i>
</figcaption> </figure> </div></div>');
$(img).insertBefore("#add-photo-container");
}
function createImages(all_ids) {
for (const key in all_ids) {
var image = all_ids[key];
var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12"
data-id="' + image.id + '"><div class="image-container"> <figure> <img
src="images/' + image.name + '" alt="Foto del usuario"> <figcaption> <i
class="icon-cross"></i> </figcaption> </figure> </div></div>');
$("#my-images").append(img);
}
}
function showModal(card) {
$("#" + card).show();
$(".modal").addClass("show");
}
function closeModal() {
$(".modal").removeClass("show");
setTimeout(function () {
$(".modal .modal-card").hide();
}, 300);
}
function loading(status, tag) {
if (status) {
$("#loading .tag").text(tag);
showModal("loading");
}
else {
closeModal();
}
}
function showMessage(message) {
$("#Message .tag").text(message);
showModal("Message");
}

I don't have all of your code, but I've identified the issue in your code and I'll just add add the fix here for you.
First of all, if you are using jquery, it's better to write your code in a unified format and use jquery everywhere and not switch between jquery and plain JavaScript.
Having that said, instead of using document.getElementsByName you can easily add id attribute to your html element and access them with $('#<id>') way in jquery.
Second, even if you are using javascript to grab your html element data, what you are doing is wrong. var namePro = document.getElementsByName('name'); will select the whole html <input> object and not it's value. So you have to change it to: document.getElementsByName("name")[0].value
So you have 2 options:
1- Use what you have already and just change it a bit to:
var namePro = document.getElementsByName('name')[0].value;
var price = document.getElementsByName('price')[0].value;
var stock = document.getElementsByName('stock')[0].value;
2- Or for switching to jquery, you need to add id to all of these elements in your html:
<div class="form-group">
<label>Name</label>
<input type="text" id="name" name="name" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Price</label>
<input type="text" id="price" name="price" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Stock</label>
<input type="text" id="stock" name="stock" class="form-control" required autocomplete="off">
</div>
And then change you JavaScript to:
formData.append('name', $('#name').val());
formData.append('price', $('#price').val());
formData.append('stock', $('#stock').val());
Update:
The sample code which works on my machine is like this:
HTML:
<form action="#" method="post" enctype="multipart/form-data" id="upload-multi-images">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Price</label>
<input type="text" name="price" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Stock</label>
<input type="text" name="stock" class="form-control" required autocomplete="off">
</div>
<div class="row">
<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="add-photo-container">
<div class="add-new-photo first" id="add-photo">
<span><i class="icon-camera"></i></span>
</div>
<input type="file" multiple id="add-new-photo">
</div>
</div>
<div class="button-container">
<button type="submit">Subir imágenes</button>
</div>
</form>
JS #1:
var formData = new FormData();
$(document).ready(function(){
$(".modal").on("click", function (e) {
console.log(e);
if (($(e.target).hasClass("modal-main") || $(e.target).hasClass("close-modal")) && $("#loading").css("display") == "none") {
closeModal();
}
});
$(document).on("click", "#add-photo", function(){
$("#add-new-photo").click();
});
$(document).on("change", "#add-new-photo", function () {
var files = this.files;
var element;
var supportedImages = ["image/jpeg", "image/png", "image/gif"];
var InvalidElementFound = false;
for (var i = 0; i < files.length; i++) {
element = files[i];
if (supportedImages.indexOf(element.type) != -1) {
var id = getRandomString(7);
createPreview(element, id);
formData.append(id, element);
}
else {
InvalidElementFound = true;
}
}
if (InvalidElementFound) {
showMessage("Invalid Elements Found.");
}
else {
showMessage("All the files were uploaded succesfully.");
}
});
$(document).on("click", "#Images .image-container", function(e){
var parent = $(this).parent();
var id = $(parent).attr("id");
formData.delete(id);
$(parent).remove();
});
$(document).on("submit", "#upload-multi-images", function (e) {
e.preventDefault();
var namePro = document.getElementsByName('name')[0].value;
var price = document.getElementsByName('price')[0].value;
var stock = document.getElementsByName('stock')[0].value;
formData.append('namePro', namePro);
formData.append('price', price);
formData.append('stock', stock);
//Envio mediante Ajax
$.ajax({
url: "upload.php",
type: "post",
dataType: "json",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
loading(true, "Adding photo...");
},
success: function (res) {
console.log('success');
console.log(res);
loading(false);
if (res.status == "true") {
createImages(res.all_ids);
$("#Images form .row > div:not(#add-photo-container)").remove();
formData = new FormData();
} else {
alert(res.error);
}
},
error: function (e) {
console.log('error');
console.log(e.responseText);
}
});
});
$(document).on("click", "#MyImages .image-container", function (e) {
var parent = $(this).parent();
var id = $(parent).attr("data-id");
var data = {
id : id
}
$.post("delete.php", data, function(res) {
if (res == "true") {
showMessage("¡Images successfully removed!");
$(parent).remove();
}
else {
showMessage("Sorry, there was an error uploading the images.");
}
});
});
});
JS #2:
function getRandomString(length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
function createPreview(file, id) {
var imgCodified = URL.createObjectURL(file);
var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="'+ id + '"><div class="image-container"> <figure> <img src="' + imgCodified + '" alt="Foto del usuario"> <figcaption> <i class="icon-cross"></i></figcaption> </figure> </div></div>');
$(img).insertBefore("#add-photo-container");
}
function createImages(all_ids) {
for (const key in all_ids) {
var image = all_ids[key];
var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" data-id="' + image.id + '"><div class="image-container"> <figure> <img src="images/' + image.name + '" alt="Foto del usuario"> <figcaption> <i class="icon-cross"></i> </figcaption> </figure> </div></div>');
$("#my-images").append(img);
}
}
function showModal(card) {
$("#" + card).show();
$(".modal").addClass("show");
}
function closeModal() {
$(".modal").removeClass("show");
setTimeout(function () {
$(".modal .modal-card").hide();
}, 300);
}
function loading(status, tag) {
if (status) {
$("#loading .tag").text(tag);
showModal("loading");
}
else {
closeModal();
}
}
function showMessage(message) {
$("#Message .tag").text(message);
showModal("Message");
}
PHP: (upload.php)
$arr_ajax = array();
$arr_ajax['namePro'] = $_REQUEST['namePro'];
$arr_ajax['price'] = $_REQUEST['price'];
$arr_ajax['stock'] = $_REQUEST['stock'];
if (isset($_FILES) && !empty($_FILES)) {
$files = array_filter($_FILES, function($item) {
return $item["name"][0] != "";
});
$iCnt = 0;
foreach ($files as $file) {
$arr_ajax['Filename'.$iCnt] = $file["name"];
$iCnt++;
}
}
echo json_encode($arr_ajax);
And with this code, when I click on Submit button, I get the following response in my browser console:
index.html:79 success
index.html:80 {namePro: "Test Product", price: "100.00", stock: "15", Filename0: "faces1.jpg"}

Related

Record not insert into the database using laravel 8 ajax

i am a begineer of laravel and ajax i can do the system well in core php. i just converted to laravel.
i creating simple crud using laravel with ajax but i don't know how call the path through ajax request. what i tried so fat i attached below.pls give me the solution for it.
Screen shot of folder structure
this is view part. i name it
list.blade.php
div class="row">
<div class="col-sm-4">
<form class="card" id="frmProject">
<div class="form-group" align="left">
<label class="form-label">First name</label>
<input type="text" class="form-control" placeholder="first_name" id="first_name" name="first_name" size="30px" required>
</div>
<div class="form-group" align="left">
<label class="form-label">Last name</label>
<input type="text" class="form-control" placeholder="last_name" id="last_name" name="last_name" size="30px" required>
</div>
<div class="form-group" align="left">
<label class="form-label">Address</label>
<input type="text" class="form-control" placeholder="Address" id="address" name="address" size="30px" required>
</div>
<div class="card" align="right">
<button type="button" id="save" class="btn btn-info" onclick="addProject()">Add</button>
</div>
</form>
</div>
Ajax Call
function addProject() {
if ($("#frmProject").valid())
{
var _url = '';
var _data = '';
var _method;
if (isNew == true) {
_url = '/student';
_data = $('#frmProject').serialize();
_method = 'POST';
}
else {
_url = '/student',
_data = $('#frmProject').serialize() + "&project_id=" + project_id;
_method = 'POST';
alert(project_id);
}
$.ajax({
type: _method,
url: _url,
dataType: 'JSON',
data: _data,
beforeSend: function () {
$('#save').prop('disabled', true);
$('#save').html('');
$('#save').append('<i class="fa fa-spinner fa-spin fa-1x fa-fw"></i>Saving</i>');
},
success: function (data) {
$('#frmProject')[0].reset();
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Add');
get_all();
var msg;
console.log(data);
if (isNew)
{
msg="Brand Created";
}
else{
msg="Brand Updated";
}
$.alert({
title: 'Success!',
content: msg,
type: 'green',
boxWidth: '400px',
theme: 'light',
useBootstrap: false,
autoClose: 'ok|2000'
});
isNew = true;
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr.responseText);
$.alert({
title: 'Fail!',
content: xhr.responseJSON.errors.product_code + '<br>' + xhr.responseJSON.msg,
type: 'red',
autoClose: 'ok|2000'
});
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
}
Student Controller
class StudentController extends Controller
{
public function index()
{
$data['students'] = Student::orderBy('id','desc')->paginate(5);
return view('student.list',$data);
}
public function create()
{
}
public function store(Request $request)
{
$student = new Student([
'first_name' => $request->post('first_name'),
'last_name'=> $request->post('lastname'),
'address'=> $request->post('address')
]);
]);
$student->save();
return Response::json($student);
}
routes
Route::get('/', [App\Http\Controllers\StudentController::class, 'index']);
Route::get('student', [App\Http\Controllers\StudentController::class, 'index']);
Route::post('student', [App\Http\Controllers\StudentController::class, 'store'])->name('student.store');
$(document).ready(function() {
$(".btn-submit").click(function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var email = $("#email").val();
var pswd = $("#pwd").val();
var address = $("#address").val();
$.ajax({
url: "url",
type:'POST',
data: {_token:_token, email:email, pswd:pswd,address:address},
success: function(data) {
printMsg(data);
}
});
});
function printMsg (msg) {
if($.isEmptyObject(msg.error)){
console.log(msg.success);
$('.alert-block').css('display','block').append('<strong>'+msg.success+'</strong>');
}else{
$.each( msg.error, function( key, value ) {
$('.'+key+'_err').text(value);
});
}
}
});
Please use csrf token

Undefined index when trying to upload image ( with jquery validate and steps )

I'm using form steps with jquery steps and jquery validate. But when i try to upload image, it show "Undefined Index: picture". When i try without both of jquery, it works.
register.php
<form class="form-contact contact_form" id="register" enctype="multipart/form-data">
<input name="remarks" id="remarks" type="hidden" value="SMP">
<div class="row">
<h3> Profil </h3>
<section>
<div class="col-md-3">
<p class="katapen">NISN</p>
</div>
<div class="col-md-9">
<input class="form-control required number" name="nisn" id="nisn" type="text" placeholder='Please enter your NISN'>
</div>
<div class="col-md-3">
<p class="katapen">School Status</p>
</div>
<div class="col-md-4">
<div class="switch-wrap d-flex justify-content-between">
<div class="primary-radio">
<input type="radio" name="schoolstatus" value="A" id="primary-radio" required>
<label for="primary-radio"></label>
</div>
<p class="spasidrradio">A</p>
</div>
</div>
<div class="col-md-4">
<div class="switch-wrap d-flex justify-content-between">
<div class="primary-radio">
<input type="radio" name="schoolstatus" value="B" id="primary-radio">
<label for="primary-radio"></label>
</div>
<p class="spasidrradio">B</p>
</div>
</div>
</section>
<h3> Personal Data </h3>
<section>
<div class="col-md-3">
<p class="katapen">Full Name</p>
</div>
<div class="col-md-9">
<input class="form-control required" name="fullname" id="fullname" type="text" placeholder='Please enter your fullname' required>
<div class="col-md-3">
<p class="katapen">Picture</p>
</div>
<div class="col-md-9">
<input class="form-control" name="picture" id="picture" type="file">
</div>
</section>
test.js
var former = $("#register");
former.validate
({
errorPlacement: function errorPlacement(error, element)
{
element.before(error);
},
rules:
{
}
});
former.children("div").steps
({
headerTag: "h3",
bodyTag: "section",
transitionEffect: "slideLeft",
onStepChanging: function (event, currentIndex, newIndex)
{
former.validate().settings.ignore = ":disabled,:hidden";
return former.valid();
},
onFinishing: function (event, currentIndex)
{
former.validate().settings.ignore = ":disabled";
return former.valid();
},
onFinished: function (event, currentIndex)
{
studentregister();
}
});
function studentregister()
{
var remarks = document.getElementById('remarks');
$.ajax
({
type: "POST",
url : base_url + "register/" + remarks.value,
data: $('#register').serialize(),
dataType: 'json',
success: function(data)
{
if(data.log.status == '1')
{
swal
({
title: "",
type: "success",
text: data.log.ket,
confirmButtonClass: "btn-success",
confirmButtonText: "Con"
},function(){
});
}else{
swal
({
title: "",
type: "error",
text: data.log.ket,
confirmButtonClass: "btn-default",
confirmButtonText: "Back"
},function(){
});
}
$("#register")[0].reset();
},
error: function(ts)
{
alert(ts.responseText);
}
});
return false;
};
base_url + "register/" + remarks.value will be route to saveregister and remarks.value as uri2
This is my adm.php
public function saveregister()
{
$uri1 = $this->uri->segment(1);
$uri2 = $this->uri->segment(2);
$uri3 = $this->uri->segment(3);
$uri4 = $this->uri->segment(4);
//var post from json
$p = json_decode(file_get_contents('php://input'));
$_log = array();
if($uri2 == "SD")
{
}else if($uri2 == "SMP"){
$p = $this->input->post();
$folder = "./upload/register/";
$allowed_type = array("image/jpeg", "image/jpg", "image/png", "image/gif",
"audio/mpeg", "audio/mpg", "audio/mpeg3", "audio/mp3", "audio/x-wav", "audio/wave", "audio/wav","video/mp4", "application/octet-stream", "application/pdf", "application/doc");
$file_name = $_FILES['picture']['name'];
$file_type = $_FILES['picture']['type'];
$file_tmp = $_FILES['picture']['tmp_name'];
$file_error = $_FILES['picture']['error'];
$file_size = $_FILES['picture']['size'];
$ekstensi = explode("/", $file_type);
$time = date("Yhsms");
$filename= $this->db->escape($p['nisn'])."_".$time .".".$ekstensi[1];
#move_uploaded_file($file_tmp, $folder .$filename);
}else{
}
}
If you look at the jquery serialize() Documentation, it says the data from file select elements is not serialized. You could use FormData to send file input through ajax :
function studentregister()
{
var remarks = document.getElementById('remarks');
var form = $("#register")[0]; // use the form ID
var formData = new FormData(form);
$.ajax
({
type: "POST",
url : base_url + "register/" + remarks.value,
data: formData,
dataType: 'json',
contentType: false, // required
processData: false, // required
success: function(data)
{
if(data.log.status == '1')
{
swal
({
title: "",
type: "success",
text: data.log.ket,
confirmButtonClass: "btn-success",
confirmButtonText: "Con"
},function(){
});
}else{
swal
({
title: "",
type: "error",
text: data.log.ket,
confirmButtonClass: "btn-default",
confirmButtonText: "Back"
},function(){
});
}
$("#register")[0].reset();
},
error: function(ts)
{
alert(ts.responseText);
}
});
return false;
};

Activate JS functionality on clone two inputs fields

i have a form with various fields, and a pair of buttons of clone and remove the cloned part of the form.
Also, i have in those fields a pair of inputs of integers that when i click in one of them
the value "jump" to the other field when clicked.
The problem is when i clone the form the functionality of "jump" do not attach to the other cloned inputs.
this is the clone function :
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = 1;//$(".clonedInput").length;
function clone(){
cloneIndex++;
$(this).parents(".clonedInput").clone()
.appendTo("form")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
//console.log(this.val);
//this.value = $(match).val();
//console.log("El valor seleccionado es ");
//this.val = match[1].val;
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
return false;
}
function remove(){
if($('.actions').length == 2){
console.log('accion cancelada');
}else{
$(this).parents(".clonedInput").remove();
}
return false;
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
an approach to this was made with this code using dinamicaly for php
$("input[id^='montoa']").on("click", function(e){
var montoa_id = this.id;
var montob_id = 'montob'+montoa_id.match(/(\d+)/g)[0];
$('#'+montoa_id).value = $('#'+montob_id).val();
$('#'+montob_id).value = '';
});
the inputs are this :
<div class="col-md-1">
<input type="text" name="monto[]" class="form-control" id="montoa1" placeholder="Debe">
</div>
<div class="col-md-1">
<input type="text" name="monto[]" class="form-control" id="montob1" placeholder="Haber">
</div>
and all the n-cloned fields are numbered by auto-increase the id like id="montoa2" and id="montob3" and so on.
all comments wil be very appreciated.
EDIT : Create a jsfiddle https://jsfiddle.net/o63c61sj/
today solved !
This time was add a param to a .clone() function
This because this is a deepWithDataAndEvent clonation event as jquery says.
.clone( [withDataAndEvents ] [, deepWithDataAndEvents ] )
The solution this time for me was clone(true).
Hope someone else could be useful. `
$(document).ready(function() {
$("input[id^='montoa']").attr("placeholder", "dollars");
$("input[id^='montob']").attr("placeholder", "dollars");
$("#montoa1").on('click', function() {
var montoa = $('#montoa1').val();
$('#montoa1').val($('#montob1').val());
$('#montob1').val(0);
});
$("#montob1").on('click', function() {
var montoa = $('#montoa1').val();
$('#montoa1').val(0);
$('#montob1').val(montoa);
});
}
/*
$("input[id^='montoa']").on("click", function(e){
var montoa_id = this.id;
var montob_id = 'montob'+montoa_id.match(/(\d+)/g)[0];
$('#'+montoa_id).value = $('#'+montob_id).val();
$('#'+montob_id).value = '';
});
$("input[id^='montob']").click(function(){
console.log(this.id);
});
*/
);
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = 1; //$(".clonedInput").length;
function clone() {
cloneIndex++;
$(this).parents(".clonedInput").clone(true)
.appendTo("form")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
return false;
}
function remove() {
if ($('.actions').length == 2) {
console.log('accion cancelada');
} else {
$(this).parents(".clonedInput").remove();
}
return false;
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form action="#" method="post">
<div id="clonedInput1" class="clonedInput">
<div class="form-group row">
<div class="actions">
<div class="panel-group">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="actions">
<button class="clone btn btn-success">Duplicar</button>
<button class="remove btn btn-warning">Quitar</button>
</div>
</div>
<div class="panel-body">
<div class="form-group row">
<div class="col-md-2">
same js functions on all cloned
</div>
<div class="col-md-1">
<input type="text" name="monto[]" class="form-control" id="montoa1" placeholder="Debe">
</div>
<div class="col-md-1">
<input type="text" name="monto[]" class="form-control" id="montob1" placeholder="Haber">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
`

I am not getting any text value in form input in codeigniter

I am very new to Codeigniter. I m trying to create a form with some text input field along with two image upload field. The image uploading working fine but the text input field value are not coming. Can anyone please check my code and tell me where I am doing wrong Here is my Code:
Front End
<body>
<div class="custom-container">
<div id="msg"></div>
<form id="product-upload" action="/index.php/uploadproduct/upload" method="POST" accept-charset="utf-8" enctype="multipart/form-data"">
<div class="form-group">
<label for="product-name">Product name</label>
<input type="text" name="product_name" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Code</label>
<input type="text" name="product_code" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Link</label>
<input type="text" name="product_link" class="form-control">
</div>
<div class="form-group">
<label for="product-image">Product image</label>
<input type="file" id="product-image" name="product_image" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Screenshots</label>
<input type="file" id="product-screen" name="product_screen" class="form-control" multiple>
</div>
<div class="form-group">
<input id="add-product" type="Submit" class="btn btn-primary" value="Add new product">
</div>
</form>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#add-product').click(function(e){
e.preventDefault();
var formData = new FormData();
//for product profile images
var productProfile = $('#product-image').prop('files')[0];
formData.append('file',productProfile);
// for product detail image
var imageCount = document.getElementById('product-screen').files.length;
for (var i = 0; i< imageCount; i++) {
formData.append("files[]", document.getElementById('product-screen').files[i]);
}
//AJAX Call
$.ajax({
url: 'http://localhost/ci/index.php/uploadproduct/upload/', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
beforeSend: function() {
// setting a timeout
$('#msg').html('Loading');
},
success: function (response) {
$('#msg').html(response); // display success response from the server
$('input').attr('value').html();
},
error: function (response) {
$('#msg').html("no response"); // display error response from the server
}
});
});
});
</script>
Controller Script is this
public function upload(){
$uploadData = "";
//Get the details
$productName = $_POST['product_name'];
$productCode = $this->input->post('product_code');
$productLink = $this->input->post('product_link');
$uploadData = $productName.','.$productCode.','.$productLink;
// setting cofig for image upload
$config['upload_path'] = 'uploads/profile/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE;
//$config['max_size'] = '1024'; //1 MB
// Get the profile image
$errorMsg = "";
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
$errorMsg = 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/profile/' . $_FILES['file']['name'])) {
$errorMsg = 'File already exists : uploads/profile/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
$errorMsg = $this->upload->display_errors();
} else {
$data = $this->upload->data();
$errorMsg = 'File successfully uploaded : uploads/profile/' . $_FILES['file']['name'];
$uploadData = $uploadData.','.$data['full_path'];
}
}
}
} else {
$errorMsg = 'Please choose a file';
}
//upload product screenshots
$config['upload_path'] = 'uploads/';
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
$link="";
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
$errorMsg = "Error: " . $_FILES["files"]["error"][$i] . "<br>";
} else {
if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
$errorMsg = 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
} else {
$fileOriginalNmame = $_FILES["files"]["name"][$i];
$explodeFile = explode(".",$fileOriginalNmame);
$fileExtenstion = end($explodeFile);
$fileName = md5(md5(uniqid(rand(), true)).$_FILES["files"]["name"][$i]).'.'.$fileExtenstion;
move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $fileName);
$link= $link.$fileName.',';
}
}
}
$uploadData =$uploadData .','. $link;
$errorMsg = $uploadData;
} else {
$errorMsg = 'Please choose at least one file';
}
echo $errorMsg;
}
And if anyone can improve my controller code that will be very helpful tnx.
FormData() Method:
As per our definition .FormData() submit a element data in a Key/Value form. The Form element must have a name attribute. One advantage of FormData() is now you can post a files on next page.
Simple Syntax:
var formData = new FormData(form);
Highlight Points:
This method does post files.
This method post complete form using Get & Post method including files.
var formData = new FormData();
formData.append('username', 'joe');
In addition you could add a key/value pair to this using FormData.append.
So your code broke because you need to pass value of input as key/pair format that you missed except for file.
Hope this will help you.
Please find solution describe below.
$(document).ready(function(){
$('#add-product').click(function(e){
e.preventDefault();
var formData = new FormData();
//for product profile images
var productProfile = $('#product-image').prop('files')[0];
formData.append('file',productProfile);
// for product detail image
var imageCount = document.getElementById('product-screen').files.length;
for (var i = 0; i< imageCount; i++) {
formData.append("files[]", document.getElementById('product-screen').files[i]);
}
var inputs = $('#product-upload input[type="text"],input[type="email"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("name");
var value = $(v).val();
formData.append(name, value);
});
//AJAX Call
$.ajax({
url: 'http://localhost/ci/index.php/uploadproduct/upload/', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
beforeSend: function() {
// setting a timeout
$('#msg').html('Loading');
},
success: function (response) {
$('#msg').html(response); // display success response from the server
$('input').attr('value').html();
},
error: function (response) {
$('#msg').html("no response"); // display error response from the server
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-container">
<div id="msg"></div>
<form id="product-upload" action="/index.php/uploadproduct/upload" method="POST" accept-charset="utf-8" enctype="multipart/form-data">
<div class="form-group">
<label for="product-name">Product name</label>
<input type="text" name="product_name" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Code</label>
<input type="text" name="product_code" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Link</label>
<input type="text" name="product_link" class="form-control">
</div>
<div class="form-group">
<label for="product-image">Product image</label>
<input type="file" id="product-image" name="product_image" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Screenshots</label>
<input type="file" id="product-screen" name="product_screen" class="form-control" multiple>
</div>
<div class="form-group">
<input id="add-product" type="Submit" class="btn btn-primary" value="Add new product">
</div>
</form>
</div>
Let me know if it not works for you.

Progress Bar for file uploads to PHP using AJAX and Bootstrap

I have a form with which I upload images using AJAX to a PHP Script
This is my form
<form action ="upload.php" method = "POST" enctype = "multipart/form-data" class = "form-horizontal" name="formData" id="data">
<!--File Upload-->
<div class = "form-group">
<label class="control-label col-sm-1" for = "file">File:</label>
<div class="col-sm-9">
<input type = "file" name = "image_file" id = "image_file" class = "form-control" accept="image/*" onChange="autoPull(this.value)";>
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-1" for = "project_name">ProjectName:</label>
<div class="col-sm-9">
<input type = "text" name ="project_name" id = "project_name" class = "form-control" placeholder="Enter Project Name" value = "" required>
</div>
</div>
<div class = "button">
<div class="form-group">
<div class="col-sm-offset-1 col-sm-6">
<input type="submit" name = "submit" class="btn btn-primary" value = "Submit" id="file_upload">
<input type="reset" name = "submit" class="btn btn-default" value = "Reset">
</div>
</div>
</div>
</form>
<br/>
<div class="progress" style="display:none;">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%;">
</div>
</div>
<div id = "result"></div>
The result div is where the output from PHP is displayed(see in AJAX)
Progress bar is where I wish to see my bootstrap progress bar.
and this is my AJAX
$(function () {
$('form#data').submit(function (e){
e.preventDefault();
e.stopImmediatePropagation();
var formData = new FormData($(this)[0]);
var file = $('input[type=file]')[0].files[0];
formData.append('upload_file',file);
$('.progress').show();
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.progress-bar').css('width',percentComplete+"%");
$('.progress-bar').html(percentComplete+"%");
if (percentComplete === 100) {
}
}
}, false);
return xhr;
},
type:'POST',
url: 'upload.php',
data: formData,
async:false,
cache:false,
contentType: false,
processData: false,
success: function (returndata) {
$('#result').html(returndata);
}
});
return false;
});
});
Now I get an output which shows me the data echoed in the PHP. But for some reason I cant get the progress bar to work.
What could be the issue?
This should do it
var progress_bar = $(".progress-bar");
progress_bar.html("0%");
progress_bar.css("width", 0);
$(".progress").hide();
removing
async : false;
solved it. But I need to see how to reset the bar now.

Categories