this is my view i am submitted form using jquery,then I want to check which button is clicked either 'ADD PRODUCT' or SUBMIT button in controller
<?php echo form_open_multipart('itemcontroller/submit'); ?>
<div class="col-md-6">
<div class="add-name">
<label>Product Name</label>
<input type="text" id="product_name" name="product_name" placeholder="Product name">
<span id="pnerror" style="display: none;">Please enter Product Name</span>
</div>
<div class="add-name">
<label>Product Image</label>
<input type="file" id="user_file" name="user_file">
<span id="imgerror" style="display: none;">Please select an Image</span>
</div>
<div class="add-name">
<label>Product Category</label>
<?php $attributes = 'id="cat"';
echo form_dropdown('cat', $cat, set_value('cat'), $attributes); ?>
<span id="caterror" style="display: none;">Please select Category</span>
</div>
</div>
<div class="col-md-6">
<div class="add-name">
</div>
<div class="add-name">
<label>Product Description</label>
<textarea class="form-control" rows="8" id="product_description" name="product_description" placeholder="Product Description"></textarea>
<span id="pderror" style="display: none;">Please enter Product Description</span>
</div>
</div>
<div class="sub-add">
<button type="submit" form="form1" id="fill" name="fill" value="add">ADD PRODUCT</button>
</div>
<div class="sub-add">
<button type="submit" id="go" name="go" form="form1" value="go">SUBMIT</button>
</div>
<?php echo form_close(); ?>
this is my jquery code for ADD PRODUCT button.
<script type="text/javascript">
$('#fill').click(function(event){
var product_name = $('#product_name').val();
var image = $('#user_file').val();
var cat = $('#cat').val();
var product_description = $('#product_description').val();
if(product_name.length == 0)
{
$('#pnerror').show();
}
if(image.length == 0)
{
$('#imgerror').show();
}
if(cat == 0)
{
$('#caterror').show();
}
if(product_description.length == 0)
{
$('#pderror').show();
}
else if(product_name.length != 0 && image.length != 0 && cat != 0 && product_description.length != 0)
{
var $target = $( event.target );
$target.closest("form").submit();
}
});
</script>
this is my SUBMIT button
<script type="text/javascript">
$('#go').click(function(event){
var product_name = $('#product_name').val();
var user_file = $('#user_file').val();
var cat = $('#cat').val();
var product_description = $('#product_description').val();
if(product_name.length == 0)
{
$('#pnerror').show();
}
if(user_file.length == 0)
{
$('#imgerror').show();
}
if(cat == 0)
{
$('#caterror').show();
}
if(product_description.length == 0)
{
$('#pderror').show();
}
else if(product_name.length != 0 && user_file.length != 0 && cat != 0 && product_description.length != 0)
{
var $target = $( event.target );
$target.closest("form").submit();
}
});
</script>
This is my controller code:
public function submit()
{
print_r($_POST);
if($this->input->post('go'))
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 2048;
$config['max_height'] = 1024;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('user_file'))
{
$data = array('prod_data' => $this->upload->data());
$user_file = $data['prod_data']['raw_name']."".$data['prod_data']['file_ext'];
$id = $this->session->userdata['record']['id'];
$com_id = $this->session->userdata['record']['com_id'];
$sam = array(
'title' => $this->input->post('product_name'),
'type' => 'product'
);
$this->load->model('registermodel');
$chk = $this->registermodel->insertsam($sam);
if ($chk == TRUE)
{
$id = $this->registermodel->getsampleid();
$data = array(
'product_name' => $this->input->post('product_name'),
'image' => 'images/'.$user_file,
'product_description' => $this->input->post('product_description'),
'cat_id' => $this->input->post('cat'),
'com_id' => $com_id,
'id' => $id
);
$check = $this->registermodel->insertproduct($data);
if($check == TRUE)
{
echo "<script>
alert('Data Submitted Succesfully');
</script>";
redirect('/homecontroller');
}
else
{
echo "Value insertion Failed";
}
}
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
}
else if($this->input->post('fill'))
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 2048;
$config['max_height'] = 1024;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('user_file'))
{
$data = array('prod_data' => $this->upload->data());
$user_file = $data['prod_data']['raw_name']."".$data['prod_data']['file_ext'];
$id = $this->session->userdata['record']['id'];
$com_id = $this->session->userdata['record']['com_id'];
$sam = array(
'title' => $this->input->post('product_name'),
'type' => 'product'
);
$this->load->model('registermodel');
$chk = $this->registermodel->insertsam($sam);
if ($chk == TRUE)
{
$id = $this->registermodel->getsampleid();
$data = array(
'product_name' => $this->input->post('product_name'),
'image' => 'images/'.$user_file,
'product_description' => $this->input->post('product_description'),
'cat_id' => $this->input->post('cat'),
'com_id' => $com_id,
'id' => $id
);
$check = $this->registermodel->insertproduct($data);
if($check == TRUE)
{
echo "<script>
alert('Product added Succesfully');
</script>";
$data['category'] = $this->linkmodel->get_category();
$data['cat'] = $this->registermodel->get_category();
$this->load->view('itemview',$data);
}
else
{
echo "Value insertion Failed";
}
}
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
}
}
print_r($_POST);
this returns only this :
Array ( [product_name] => Multifunction Printer Machine [cat] => 82 [product_description] => Approx Price: Rs 80,000 / Piece)
not return ADD PRODUCT OR SUBMIT button name, please anyone tell me what i am doing wrong ?
You may have to use <input type="submit" ...> instead of <button ...>. It should append buttons' name and value to $_POST.
Add input hidden field in your form and set different value in each JavaScript code.
<?php echo form_open_multipart('itemcontroller/submit'); ?>
<!-- your existing code --->
<input type="hidden" name="submit_type" id="submit_type" value="" />
<?php echo form_close(); ?>
JavaScript code Modification
<script type="text/javascript">
$('#go').click(function(event){
<!-- your existing code --->
$('#submit_type').val('SUBMIT');
var $target = $( event.target );
$target.closest("form").submit();
}
});
</script>
<script type="text/javascript">
$('#fill').click(function(event){
<!-- your existing code --->
$('#submit_type').val('ADD PRODUCT');
var $target = $( event.target );
$target.closest("form").submit();
}
});
</script>
Related
View Page input form. I was trying to upload a product with product images and complete the full crud operation about images and product details. This is the form for product details and image upload.
<form action="" method="post" id="product_form">
<div class="form-group">
<label for="">Subcategory</label>
<select class="form-control input-lg" id="select_subcategory">
<option value="">Choose Subcategory</option>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
</div>
<div class="form-group">
<label for="">Product Title</label>
<input type="text" id="product_title" class="form-control">
</div>
<div class="form-group">
<label for="">Upload Images</label>
<input class="form-control input-lg" type="file" id="prod_img" name="prod_img[]"
multiple="multiple">
</div>
<div class="form-group">
<label for="">Brand</label>
<select class="form-control input-lg" id="select_brand">
<option value="">Choose Brand</option>
<option>One</option>
<option>Two</option>
</select>
</div>
<div class="form-group">
<label for="">Color</label>
<select class="form-control input-lg" id="product_color">
<option value="">Choose Color</option>
<option>White</option>
<option>Black</option>
</select>
</div>
<div class="form-group">
<label for="">Product Size</label>
<select class="form-control input-lg" id="product_size">
<option value="">Select Size</option>
<option>Small</option>
<option>Medium</option>
</select>
</div>
<div class="form-group">
<label for="">Product Price</label>
<input type="number" id="product_price" class="form-control">
</div>
<div class="form-group">
<label for="">Discounted Price</label>
<input type="text" placeholder="INR" class="form-control" id="prod_discount_price">
</div>
<div class="form-group">
<label for="">Description</label>
<input type="text" class="form-control" id="product_description">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="add_product">Add Data</button>
</div>
Ajax code on view page for snding data to the server.
$(document).on("click", "#add_product", function(e){
e.preventDefault();
var select_category = $("#select_category").val();
var select_subcategory = $("#select_subcategory").val();
var product_title = $("#product_title").val();
var prod_img = $("#prod_img")[0].files;
var select_brand = $("#select_brand").val();
var product_color = $("#product_color").val();
var product_size = $("#product_size").val();
var product_price = $("#product_price").val();
var prod_discount_price = $("#prod_discount_price").val();
var product_description = $("#product_description").val();
if( select_category == "" || select_subcategory == "" || product_title == "" || select_brand ==
"" || product_color == "" || product_size == "" || product_price == "" || prod_discount_price ==
"" || product_description == "" )
{
alert("All fields are required");
}
else
{
var fd = new FormData();
var ins = document.getElementById("prod_img").files.length;
for(var i=0; i< ins; i++)
{
fd.append("prod_img[]", document.getElementById("prod_img").files[i]);
}
fd.append("select_category", select_category);
fd.append("select_subcategory", select_subcategory);
fd.append("product_title", product_title);
fd.append("select_brand", select_brand);
fd.append("product_color", product_color);
fd.append("product_size", product_size);
fd.append("product_price", product_price);
fd.append("prod_discount_price", prod_discount_price);
fd.append("product_description", product_description);
$.ajax({
url: "<?php echo base_url(); ?>InsertProduct",
type: "post",
data: fd,
processData: false,
contentType: false,
dataType: "json",
success:function(data)
{
fetch();
if(data.response == "success")
{
$('#ProductModal').modal('hide');
$("#tbody").DataTable().destroy();
toastr["success"](data.message)
}
else
{
toastr["error"](data.message)
}
}
});
$("#product_form")[0].reset();
}
});
Controller Code for uploading multiple image file and product details with session check. files are uploaded successfully in the folder. all details about product are successfully submitted to the database but the image section of database is empty. I was unable to send the image file name.
public function InsertProduct()
{
if($this->session->userdata('email')=="" && $this->session->userdata('password')=="")
{
$this->load->view('Admin/index');
}
else if($this->input->is_ajax_request())
{
$this->form_validation->set_rules('select_category', 'Category', 'required|trim');
$this->form_validation->set_rules('select_subcategory', ' Subcategory', 'required|trim');
$this->form_validation->set_rules('product_title', 'Product Title', 'required|trim');
$this->form_validation->set_rules('select_brand', 'Product Brand', 'required|trim');
$this->form_validation->set_rules('product_color', 'Product Color', 'required|trim');
$this->form_validation->set_rules('product_size', 'Product Size', 'required|trim');
$this->form_validation->set_rules('product_price', 'Product Price', 'required|trim');
$this->form_validation->set_rules('prod_discount_price', 'Discount Price',
'required|trim');
$this->form_validation->set_rules('product_description', 'Product Description',
'required|trim');
if($this->form_validation->run() == FALSE)
{
$data = array('response' =>"error", 'message'=>validation_errors());
}
else
{
//$this->load->library('upload');
$img = array();
$no_of_images = count($_FILES['prod_img']['name']);
if($no_of_images > 10)
{
$data = array('response' =>"error", 'message'=>"10 Images allowed only");
}
else
{
for($i = 0; $i < $no_of_images; $i++)
{
$_FILES['img_file']['name'] = $_FILES['prod_img']['name'][$i];
$_FILES['img_file']['type'] = $_FILES['prod_img']['type'][$i];
$_FILES['img_file']['tmp_name'] = $_FILES['prod_img']['tmp_name'][$i];
$_FILES['img_file']['error'] = $_FILES['prod_img']['error'][$i];
$_FILES['img_file']['size'] = $_FILES['prod_img']['size'][$i];
$config['upload_path'] = "./ProductImages/";
$config['allowed_types'] = "jpg|jpeg|png";
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('img_file'))
{
$img_data = $this->upload->data();
$data[$i]['prod_img'][] = $img_data['file_name'];
}
}
if(!empty($data))
{
$data = $this->input->post();
if($this->adm->InsertProduct($data))
{
$data = array('response'=>"success", 'message'=>"Data updated
successfully");
}
else
{
$data = array('response'=> "error", 'message'=> "failed");
}
}
}
}
echo json_encode($data);
}
}
Model Code for inserting data I have
public function InsertProduct($data)
{
return $this->db->insert('product',$data);
}
I have selected 4 image files to upload. Images are uploaded i get a successful message and i have
checked it in the mentioned folder. But image file name is not showing in the database. Help us
Thank you
You need to save the images name in product table as json_encode.
public function InsertProduct()
{
if($this->session->userdata('email')=="" && $this->session->userdata('password')=="")
{
$this->load->view('Admin/index');
}
else if($this->input->is_ajax_request())
{
$this->form_validation->set_rules('select_category', 'Category', 'required|trim');
$this->form_validation->set_rules('select_subcategory', ' Subcategory', 'required|trim');
$this->form_validation->set_rules('product_title', 'Product Title', 'required|trim');
$this->form_validation->set_rules('select_brand', 'Product Brand', 'required|trim');
$this->form_validation->set_rules('product_color', 'Product Color', 'required|trim');
$this->form_validation->set_rules('product_size', 'Product Size', 'required|trim');
$this->form_validation->set_rules('product_price', 'Product Price', 'required|trim');
$this->form_validation->set_rules('prod_discount_price', 'Discount Price',
'required|trim');
$this->form_validation->set_rules('product_description', 'Product Description',
'required|trim');
if($this->form_validation->run() == FALSE)
{
$data = array('response' =>"error", 'message'=>validation_errors());
}
else
{
//$this->load->library('upload');
$img = array();
$no_of_images = count($_FILES['prod_img']['name']);
if($no_of_images > 10)
{
$data = array('response' =>"error", 'message'=>"10 Images allowed only");
}
else
{
for($i = 0; $i < $no_of_images; $i++)
{
$_FILES['img_file']['name'] = $_FILES['prod_img']['name'][$i];
$_FILES['img_file']['type'] = $_FILES['prod_img']['type'][$i];
$_FILES['img_file']['tmp_name'] = $_FILES['prod_img']['tmp_name'][$i];
$_FILES['img_file']['error'] = $_FILES['prod_img']['error'][$i];
$_FILES['img_file']['size'] = $_FILES['prod_img']['size'][$i];
$config['upload_path'] = "./ProductImages/";
$config['allowed_types'] = "jpg|jpeg|png";
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('img_file'))
{
$img_data = $this->upload->data();
$img[] = $img_data['file_name'];
}
}
if(count($img) > 0){
$data['prod_img'] = json_encode($img);
}
if(!empty($data))
{
$data = $this->input->post();
if($this->adm->InsertProduct($data))
{
$data = array('response'=>"success", 'message'=>"Data updated
successfully");
}
else
{
$data = array('response'=> "error", 'message'=> "failed");
}
}
}
}
echo json_encode($data);
}
}
public function InsertProduct($data)
{
return $this->db->insert('product',$data);
}
I am trying to assign TinyMCE text editor value to my PHP variable but it's not working properly, when I first try to upload information to the MYSQL database with the empty table it stored the data but when I try to store some more data then TinyMCE don't pass the value to PHP variable, I am not getting it that why its happing..
<!--this is my form -->
<form action="" enctype="multipart/form-data" id="fupForm">
<div class="col-md-12">
<div class="post" style="border: none">
<div class="row">
<div class="col-md-2 post-date">
<div class="day">
<?php echo $date_day; ?>
</div>
<div class="month">
<?php echo $date_month; ?>
</div>
<div class="year">
<?php echo $date_year; ?>
</div>
</div>
<div class="col-md-7 post-title">
<a href="#">
<div class="form-group">
<label for="postTitle">Title*</label>
<input type="text" style="border-color:#D07420;" class="form-control form-control-sm" id="InputTitle" aria-describedby="InputTitle" placeholder="Title" name="InputTitle">
</div>
</a>
<p>Written by:
<span>
<?php echo $user_name; ?>
</span>
</p>
</div>
<div class="col-md-3 col-xs-6 profile-picture"> <img src="../../img/profile-pic/pem_profile_imge/<?php echo $user_image; ?>" class="rounded-circle " alt="profie iamge "> </div>
</div>
<a href="#">
<div class="form-group">
<label for="fileUpload">chose your status photo*</label>
<input type="file" style="border-color:#D07420;" class="form-control-file" id="postPicture" name="postPicture">
</div><img src="../../img/post_iamge/default_post_image.png" alt="Post Image" class="img-responsive" id="previe_post_img">
</a>
<div class="form-group">
<label for="writePost">write your post*</label>
<textarea id="myTextArea" class="mceEditor textarea_class" name="myTextArea"></textarea>
</div>
<button type="submit" class="btn btn-secondary submitBtn" id="submit_post" style="margin-top:20px">Submit your post</button>
</div>
</div>
</form>
<script>
//this is my jquery
// form submission here
$(document).ready(function () {
$("#fupForm").on('submit', function (e) {
e.preventDefault();
var post_title = $('#InputTitle').val();
var post_image = $('#postPicture').val();
var post_data = (tinyMCE.get('myTextArea').getContent());
if (post_title.trim() == '') {
alert('Please write Title of your Post.');
$('#InputTitle').focus();
return false;
} else if (post_image == "") {
alert('Please select a valid Post image (JPEG/JPG/PNG).');
return false;
} else if (post_data.trim() == '' || post_data.length < 30) {
alert('Please write somthing in your Post. atleast 30 charachters');
$('#myTextArea').focus();
return false;
} else {
$.ajax({
type: 'POST',
url: '../interfaces/write_post.php',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function () {
$('.submitBtn').attr("disabled", "disabled");
$('#fupForm').css("opacity", ".5");
},
success: function (msg) {
window.console.log(msg);
$('.statusMsg').html('');
if (msg == 'ok') {
$('#fupForm')[0].reset();
$('.statusMsg').html('<span style="font-size:18px;color:#34A853">Form data submitted successfully.</span>');
} else {
$('.statusMsg').html('<span style="font-size:18px;color:#EA4335">Some problem occurred, please try again.</span>');
}
$('#fupForm').css("opacity", "");
$(".submitBtn").removeAttr("disabled");
}
});
}
});
});
</script>
//PHP code for form submission
<?php
ob_start();
session_start();
require_once( '../../inc/db-connect.php' );
if (!isset($_SESSION['username'])) {
header('location:http:../index.php');
}
if (isset($_SESSION['username'])) {
$session_userID = $_SESSION['userid'];
$session_ROLE = $_SESSION['role'];
}
if (!empty($_POST['InputTitle']) || !empty($_POST['myTextArea']) || !empty($_FILES['postPicture']['name'])) {
$uploadedFile = '';
$date = $post_id = time();
$InputTitle = $_POST['InputTitle'];
$myTextArea = $_POST["myTextArea"];
// image upload on the server
if (!empty($_FILES["postPicture"]["type"])) {
$fileName = $post_id . '_' . $_FILES['postPicture']['name'];
$valid_extensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["postPicture"]["name"]);
$file_extension = end($temporary);
if (( ( $_FILES["postPicture"]["type"] == "image/png" ) || ( $_FILES["postPicture"]["type"] == "image/jpg" ) || ( $_FILES["postPicture"]["type"] == "image/jpeg" ) ) && in_array($file_extension, $valid_extensions)) {
$sourcePath = $_FILES['postPicture']['tmp_name'];
$targetPath = "../../img/post_iamge/" . $fileName;
if (move_uploaded_file($sourcePath, $targetPath)) {
$uploadedFile = $fileName;
}
}
$query_insert = "INSERT INTO `post` (`post_serial_num`, `post_id`, `user_id`, `date`, `title`, `post_image`, `post_data`, `view`, `status`) VALUES (NULL, '$post_id', '$session_userID', '$date', '$InputTitle', '$uploadedFile', '$myTextArea', NULL, 'unpublish');";
$query_insert .= "INSERT INTO `objection_report` (`sNo`, `obj_post_id`, `obj_comment_id`, `obj_user_id`, `obj_user_role`, `obj_title`, `obj_message`, `obj_status`, `obj_admin_aprove`) VALUES (NULL, '$post_id', NULL, '$session_userID', '$session_ROLE', NULL, NULL, 'unpublish', 'no');";
}
if (mysqli_multi_query($con, $query_insert)) {
echo "ok";
} else {
echo "error";
}
}
<!--addition important information-->
Although data is being saved in my database with empty space
I'm working on a form that submits via AJAX and is processed using PHP. I am looking to have server side validation with inline styling to correspond to whichever field(s) are are not valid. I have a setup that mostly works, however, it only every validates one field at a time.
i.e. if the user tries to submit the form but leaves 2 fields blank, only the first of those 2 is highlighted with the .error-field class I created. I'd rather that any and all fields that have errors be highlighted at once. I know I can do such a thing in jQuery by using a loop, but I'm wondering if that's something that is possible here using only server-side validation? I don't want to print an error message for each field as the form is very small and I have very little space to work with. I'd prefer to just highlight the field(s) that produce an error then display the "Please fill in the required fields" message.
The HTML for the form:
<form method="post" enctype="multipart/form-data" class="signupForm">
<a class="sidebar">
<span class="glyphicon glyphicon-arrow-left icon-arrow arrow"></span>
</a>
<a class="closeBtn">
<span class="glyphicon glyphicon-remove"></span>
</a>
<h2 class="text-center black">Sign up for our newsletter.</h2>
<p class="errors-container light">Please fill in the required fields.</p>
<div class="success">Thank you for signing up!</div>
<div class="form-field-content">
<div class="form-group">
<input class="form-control FirstNameTxt" type="text" name="first_name" placeholder="*First Name"
autofocus="">
</div>
<div class="form-group">
<input class="form-control LastNameTxt" type="text" name="last_name" placeholder="*Last Name"
autofocus="">
</div>
<div class="form-group">
<input class="form-control EmailTxt" type="email" name="email" placeholder="*Email"
autofocus="">
</div>
<div class="form-group submit-button">
<button class="btn btn-primary btn-block button-submit" type="button">SIGN-UP</button>
<img src="/img/ajax-loader.gif" class="progress" alt="Submitting...">
</div>
</div>
<br/>
</form>
The jQuery + AJAX:
;(function ($) {
$(document).ready(function () {
var FirstName = $('.FirstNameTxt');
var LastName = $('.LastNameTxt');
var EmailAddress = $('.EmailTxt');
var successMessage = $('.success');
var error = $('.errors-container');
var submitbtn = $('.button-submit');
var SubmitProgress = $('img.progress');
var formdata = {};
submitbtn.click(function (e) {
resetErrors();
postForm();
});
function resetErrors() {
$('.signupForm input').removeClass('error-field');
}
function postForm() {
$.each($('.signupForm input'), function(i, v) {
if (v.type !== 'submit') {
formdata[v.name] = v.value;
}
});
submitbtn.hide();
error.hide();
SubmitProgress.show();
$.ajax({
type: "POST",
data: formdata,
url: 'submission.php',
dataType: "json"
}).done(function (response) {
submitbtn.show();
SubmitProgress.hide();
console.log("here");
for (var i = 0; i < response.length; i++) {
var status = response[i].status;
var field = response[i].field;
if (status == "error") {
error.show();
$('input[name="' + field + '"]').addClass('error-field');
}
else if (status == "success") {
$('signupForm')[0].reset();
$('.form-field-content').hide();
successMessage.show();
$('.button-submit').html("Submitted");
}
}
});
}
});
}(jQuery));
The php code that handles the form:
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$emailfield = $_POST['email'];
$return = [];
if($firstname == ""){
$validatonStatus = "error";
$errorField = "first_name";
}
else if($lastname == ""){
$validatonStatus = "error";
$errorField = "last_name";
}
else if($emailfield == "" || !filter_var($emailfield, FILTER_VALIDATE_EMAIL)){
$validatonStatus = "error";
$errorField = "email";
}
else {
$validatonStatus = "success";
$errorField = "";
//send email notification
}
$return[] = array(
"status" => $validatonStatus,
"field" => $errorField,
);
echo (json_encode($return));
The PHP code just returns an array with one element, not an element for each field. It needs to add a separate element to $return for each field.
It also shouldn't be using elseif, that prevents it from validating other fields when one is invalid.
if ($firstname == "") {
$return[] = array('status' => 'error', 'field' => 'first_name');
} else {
$return[] = array('status' => 'success', 'field' => 'first_name');
}
if ($lastname == "") {
$return[] = array('status' => 'error', 'field' => 'last_name');
} else {
$return[] = array('status' => 'success', 'field' => 'last_name');
}
if($emailfield == "" || !filter_var($emailfield, FILTER_VALIDATE_EMAIL)){
$return[] = array('status' => 'error', 'field' => 'email');
} else {
$return[] = array('status' => 'success', 'field' => 'email');
}
I have studied the codeigniter documentation for file upload and implemented the file upload with only one file field, but now i have other input fields also , so i used the below code but there is DATABASE error "Column 'userfile' cannot be null", please tell me where i am wrong
view
<html>
<body>
<head>
<title>VALIDATION</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
</script>
<script>
$(document).ready(function(){
$("#sub").click(function(){
alert("Please check all required fields are filled.");
});
});
</script>
</head>
<form method="POST" action="<?php echo site_url('Dob_control/insert');?>" enctype="multipart/form-data">
<p>NAME:</p>
<?php echo form_error('name'); ?>
<input type="text" name="name" value="<?php echo set_value('name'); ?>" size="50">
<p>EMAIL:</p>
<?php echo form_error('email'); ?>
<input type="email" name="email" value="<?php echo set_value('email'); ?>" size="50">
<p>DATE:</p>
<?php echo form_error('date'); ?>
<input type="date" id="datepicker" name="date" value="<?php echo set_value('date'); ?>" size="50">
<p>NOTES:</p>
<?php echo form_error('notes'); ?>
<textarea name="notes" rows="4" cols="39"><?php echo set_value('notes'); ?></textarea>
<p>IMAGE:</p>
<input type="file" name="userfile" size="20" />
<br>
<input type="submit" id="sub" name="submit" value="submit">
</form>
</body>
</html>
model
<?php
class Dob_model extends CI_Model {
function __construct(){
parent::__construct();
$this->load->database();
}
function insert_record($student){
$this->db->insert('validate_table', $student); // insert data into `validate_table table`
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
}
?>
controller
<?php
class Dob_control extends CI_controller {
function __construct(){
parent::__construct();
$this->load->model('Dob_model');
}
function index(){
$this->load->helper(array('form','url'));
$this->load->view('simple_form');
}
public function insert(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('date','Date','required');
$this->form_validation->set_rules('notes','Notes','required', array( 'required' => 'Please complete this field'));
if ($this->form_validation->run() == FALSE)
{
$this->load->view('simple_form');
} else {
if ($this->input->post('submit') == true){
$student = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'date' => $this->input->post('date'),
'notes' => $this->input->post('notes'),
'userfile'=> $this->input->post('userfile'));
$result = $this->Dob_model->insert_record($student);
if($result==true){
echo "inserted";
}else
echo "Not Inserted";
} } }
public function do_upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10000;
$config['max_width'] = 10244;
$config['max_height'] = 7685;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->Dob_control->display_errors());
$this->load->view('simple_form', $error);
} else {
$data = array('upload_data' => $this->Dob_control->data());
$this->load->view('upload_success', $data);
} } }
?>
First load the library.
$this->load->library('upload', $config);
Then upload your file
if ( $this->upload->do_upload('userfile'))
{
$data = array('upload_data' => $this->upload->data());
// $data will contain your file information
}
Please refer https://codeigniter.com/user_guide/libraries/file_uploading.html
I have a user registration form and it's working fine but would like to add an image upload feature inside it. This is basically what I'd like to achieve
ScreenShot 1
ScreenShot 2
So far, this is what I have done
Controller:
class Employees extends CI_Controller {
var $pgToLoad;
public function __construct() {
parent::__construct();
#this will start the session
session_start();
$this->load->helper(array('form', 'url'));
if(!isset($_SESSION['userId']) || !isset($_SESSION['userLevel']) || !isset($_SESSION['employeeid']) || !isset($_SESSION['firstname']) || !isset($_SESSION['lastname'])) {
redirect('home', 'location');
}
#this will load the model
$this->load->model('Contents');
#get last uri segment to determine which content to load
$continue = true;
$i = 0;
do {
$i++;
if ($this->uri->segment($i) != "") $this->pgToLoad = $this->uri->segment($i);
else $continue = false;
} while ($continue);
}
public function index() {
$this->main();
}
public function main() {
#set default content to load
$this->pgToLoad = empty($this->pgToLoad) ? "employees" : $this->pgToLoad;
$disMsg = "";
#this will delete the record selected
if($this->uri->segment(2) == 'delete') {
$this->deleteRecord();
}
#this will check if the post value is trigger
if(isset($_POST['addnew'])) {
$this->addRecord();
}
#this will check if the post value is trigger
if(isset($_POST['saveinfo'])) {
$this->updateinfo();
}
if($this->uri->segment(2) == 'add' || $this->uri->segment(2) == 'edit') {
#this display the form for products
$this->displayForm();
} else {
#this will display the job orders
$this->getAllEmployees();
}
if($this->uri->segment(2) == 'print') {
#this display the form for products
$this->pdf();
}
if($this->uri->segment(2) == 'do_upload') {
#this display the form for products
$this->do_upload();
}
#this will logout the user and redirect to the page
if($this->uri->segment(2) == 'logout') {
session_destroy();
redirect('home', 'location');
}
$data = array ( 'pageTitle' => 'Payroll System | ADMINISTRATION',
'disMsg' => $disMsg,
'mainCont' => $this->mainCont );
$this->load->view('mainTpl', $data, FALSE);
}
function do_upload(){
if($this->input->post('upload')){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('pages/employeesform', $error);
}
else{
$data=$this->upload->data();
$this->thumb($data);
$file=array(
'img_name'=>$data['raw_name'],
'thumb_name'=>$data['raw_name'].'_thumb',
'ext'=>$data['file_ext'],
'upload_date'=>time()
);
$this->Contents->add_image($file);
$data = array('upload_data' => $this->upload->data());
$this->load->view('pages/upload_success', $data);
}
}
else{
redirect(site_url('employees'));
}
}
function thumb($data){
$config['image_library'] = 'gd2';
$config['source_image'] =$data['full_path'];
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 275;
$config['height'] = 250;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
public function displayForm() {
$data['level'] = $this->Contents->exeGetUserLevel();
$data['status'] = $this->Contents->exeGetUserStatus();
$data['employee'] = $this->Contents->exeGetEmpToEdit($_SESSION['userId']);
if($this->uri->segment(2) == 'edit') {
$data['employee'] = $this->Contents->exeGetEmpToEdit($_SESSION['userId']);
$data['emp'] = $this->Contents->exeGetEmpToEdit($this->uri->segment(3));
$data['info'] = $this->Contents->exeGetUserInfo($this->uri->segment(3));
$this->mainCont = $this->load->view('pages/employeesform', $data, TRUE);
}
$this->mainCont = $this->load->view('pages/employeesform', $data, TRUE);
}
#this will add new record
public function addRecord() {
if(empty($_POST['fname']) || empty($_POST['mname']) || empty($_POST['lname']) || empty($_POST['empass']) || empty($_POST['emailadd']) || empty($_POST['gender']) || empty($_POST['datehired']) || empty($_POST['salary'])) {
$disMsg = "Please fill up the form completely.";
$_SESSION['disMsg'] = $disMsg;
} else {
$addNew = $this->Contents->exeAddNewRecord();
if($addNew['affRows'] > 0) {
$_SESSION['disMsg'] = "New Employee has been added.";
redirect('employees', 'location');
} else {
$disMsg = "Unable to add new employee.";
}
}
}
Views:
<?php echo form_open_multipart('employees/do_upload');?>
<img id="preview" style = "width: 200px; height: 200px;">
<input type="file" name = "userfile" id="input">
<br /><br />
<input type="submit" value="upload" name="upload" />
</form>
<form action="" method="post" enctype="multipart/form-data" id="empform" role="form" name="empform">
<div class="box-body">
<div class="row">
<div class="col-lg-6">
<div class="input-field col s12">
<label>Firstname</label>
<input type="text" id="fname" name="fname" class="form-control" value="<?php if(!empty($_POST['fname'])) { echo $_POST['fname']; } elseif(!empty($emp[0]['firstname'])) { echo $emp[0]['firstname']; } ?>">
</div>
<div class="input-field col s12">
<label>Middle Name</label>
<input type="text" id="mname" name="mname" class="form-control" value="<?php if(!empty($_POST['mname'])) { echo $_POST['mname']; } elseif(!empty($emp[0]['middlename'])) { echo $emp[0]['middlename']; } ?>">
</div>
<div class="input-field col s12">
<label>Password</label>
<input type="password" id="empass" name="empass" class="form-control" value="<?php if(!empty($_POST['empass'])) { echo $_POST['empass']; } ?>">
</div>
<div class="input-field col s12">
<label>Employee ID</label>
<input type="text" id="empno" name="empno" class="form-control" value="<?php if(!empty($_POST['empno'])) { echo $_POST['empno']; } elseif(!empty($emp[0]['employeeid'])) { echo $emp[0]['employeeid']; } ?>">
</div>
</div>
<div class="col-lg-4" style="padding-left:0;">
<?php if($this->uri->segment(2) == "edit") { ?>
<button type="submit" name="saveinfo" class="btn btn-lg btn-primary btn-block">Save</button>
<?php } else { ?>
<button type="submit" name="addnew" class="btn btn-lg btn-primary btn-block">Save</button>
<?php } ?>
</div>
</div>
</div>
</form>
As you can see in views, there are 2 forms. First form is for image upload and the other one is user registration form. How will I be able to include the image upload in the reg form and perform image upload, save user info and form validation once save button is clicked?
This is how I handle file uploads with form... it's a generic example but it should help.
View
<?php echo form_open_multipart('someController/someFunction') ?>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name">
</div>
<div class="form-group">
<label for="uploads">Upload a file</label>
<input name="uploads[]" id="fileupload" type="file" multiple="true">
</div>
<input type="submit">
<?php echo form_close() ?>
Controller
public function addRecordToTable()
{
$this->form_validation->set_rules('name' , 'Name', 'required');
if ($this->form_validation->run() == true) {
$array = array(
'name' => $this->input->post('name')
);
$record_id = $this->some_model->addData('some_table', $array);
$this->uploadFiles($record_id);
}
}
public function uploadFiles($record_id)
{
$config = array(
'upload_path' => FCPATH . "path\to\directory",
'allowed_types' => 'jpg|png|jpeg',
'overwrite' => TRUE,
);
$this->load->library('upload', $config);
$files = $_FILES['uploads'];
foreach ($files['name'] as $key => $filename) {
$_FILES['uploads[]']['name'] = $files['name'][$key];
$_FILES['uploads[]']['type'] = $files['type'][$key];
$_FILES['uploads[]']['tmp_name'] = $files['tmp_name'][$key];
$_FILES['uploads[]']['error'] = $files['error'][$key];
$_FILES['uploads[]']['size'] = $files['size'][$key];
$config['file_name'] = $filename;
$this->upload->initialize($config);
if (isset($_FILES['uploads[]']['name']) && !empty($_FILES['uploads[]']['name'])) {
if ( ! $this->upload->do_upload('uploads[]')) {
$error = array('error' => $this->upload->display_errors());
} else {
$uploads[] = $this->upload->data();
$array = array(
'record_id' => $record_id,
'filename' => $_FILES['uploads[]']['name'],
'size' => $_FILES['uploads[]']['size']
);
$this->some_model->addData('uploads', $array);
}
}
}
redirect(base_url() . 'someController/someFunction/' . $record_id);
}
Model
public function addData($table, $array)
{
$this->db->insert($table, $array);
return $this->db->insert_id();
}
Edit:
As per your comment, to insert data into multiple tables, simply modify the code in your controller so:
public function submitEmployeeDetails()
{
$this->form_validation->set_rules('value1' , 'Value 1', 'required');
$this->form_validation->set_rules('value2' , 'Value 2', 'required');
if ($this->form_validation->run() == true) {
$array1 = array(
'value1' => $this->input->post('value1')
);
$array2 = array(
'value2' => $this->input->post('value2')
);
$this->your_model->addData('employees', $array1);
$this->your_model->addData('employees_details', $array2);
}
}
So you have two arrays and you call the addData() function in the model, the first parameter specifies the name of the table and the second passes the associative array to be added.