I'm quite new to the codeigniter library and function. Recently i had a form that had a few dynamic input field to be submit and insert into database for recording purpose.
The image upload file field was dynamically created if user click "+" button, and i was using array name as the name for the input field. However when i trying to call the controller to upload the file or insert with the array field name, it keep prompted me 'You did not select a file to upload'.
If i change the image field's input name to only 'reg_photo' and the do upload field name to 'reg_photo' then everything working fine but that is not i wanted because i wanted to upload it based on the dynamic input array.
I did try to look around the solution at stackoverflow and google but after i try and none of it could help me.
Here are my Controller to do the upload :
//Upload Picture Configuration
$config['upload_path'] = './uploads/profile_picture/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 1920;
$config['max_height'] = 1080;
$this->load->library('upload', $config);
//Check and get the Areas list
$areaList = $this->input->post('areas', true);
$finalSeparator = $areaList;
$resultArea = "";
foreach ($finalSeparator as $i => $a) {
if (next($finalSeparator )) {
$resultArea .= $a.','; // Add comma for all elements instead of last
}
else
{
$resultArea .= $a;
}
}
if ($this->input->post('reg_name')) { // returns false if no property
//Get Last Inserted District ID
$district = "";
$failedUploadNameList = "";
$photoPath = "";
$data = array(
'district_code' => $this->input->post('reg_district_2', true),
'district_country' => '',
);
$this->db->set('district_registered_date', 'NOW()', FALSE); //Submit current date time
if($this->Registerlanguage_admin_model->register_district($data))
{
$district = $this->db->insert_id(); //Last Get ID
$name = $this->input->post('reg_name', true);
$year1 = $this->input->post('reg_year1', true);
$year2 = $this->input->post('reg_year2', true);
$nickname = $this->input->post('reg_nickname', true);
$photo = $this->input->post('reg_photo', true);
foreach ($name as $i => $a) { // need index to match other properties
//Check to whether can upload image or not
if ( ! $this->upload->do_upload($photo[$i]))
{
$error = array('error' => $this->upload->display_errors());
foreach($error as $q)
{
$failedUploadNameList .= $q;
}
}
else
{
$data = array('upload_data' => $this->upload->data('file_name'));
foreach($data as $a)
{
$photoPath = $config['upload_path'].$a;
}
}
$data = array(
'area_district_id' => $district,
'area_name' => $resultArea,
'area_language' => $this->input->post('reg_language', true),
'area_year_1' => isset($year1[$i]) ? $year1[$i] : '',
'area_year_2' => isset($year2[$i]) ? $year2[$i] : '',
'area_leader_name' => isset($name[$i]) ? $name[$i] : '',
'area_leader_nickname' => isset($nickname[$i]) ? $nickname[$i] : '',
'area_leader_photo' => $photoPath
);
$this->db->set('area_registered_date', 'NOW()', FALSE); //Submit current date time
if (!$this->Registerlanguage_admin_model->register_area($data)) {
// quit if insert fails - adjust accordingly
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('index.php/language_admin/index');
}
}
}
else{
// don't redirect inside the loop
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('index.php/language_admin/index');
}
//Redirect back once all successfully insert
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Insert Successfully!</div>'.$failedUploadNameList);
redirect('index.php/language_admin/index');
}
else{
// don't redirect inside the loop
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('index.php/language_admin/index');
}
Here are my view code :
<?php $attributes = array("name" => "registerdistrictform");
echo form_open_multipart("index.php/registerlanguage_admin/registerDistrict", $attributes);?>
<div class="panel panel-default">
<div class="panel panel-info">
<div class="panel-body panel-group">
<div class="form-group">
<input class="form-control" name="reg_language" type="hidden" value="Japanese" />
<label for="concept" class="col-sm-3 control-label">District :</label>
<div class="col-sm-9">
<input class="form-control" name="reg_district_1" placeholder="Ex : District 3500" type="text" value="<?php echo set_value('reg_district_1'); ?>" required/>
<span class="text-danger"><?php echo form_error('reg_district_1'); ?></span><br/>
<input class="form-control" name="reg_district_2" placeholder="Ex : 3500" type="text" value="<?php echo set_value('reg_district_2'); ?>" required/>
<span class="text-danger"><?php echo form_error('reg_district_2'); ?></span><br/>
</div>
</div>
<div class="form-group">
<label for="concept" class="col-sm-3 control-label">Area :</label>
<div id="areaContainer">
<div class="col-sm-6">
Area Record #0<input class="form-control" name="areas[]" placeholder="Your Language" type="text" value="" required/>
</div>
<div class="col-sm-3">
+<br/>
</div>
</div>
</div>
</div>
</div>
<div id = "profileContainer">
<div class="panel panel-danger">
<div class="panel-heading">Profile #0</div>
<div class="panel-body panel-group">
<div class="form-group">
<label for="concept" class="col-sm-3 control-label">Years :</label>
<div class="col-sm-4">
<input class="form-control" name="reg_year1[]" placeholder="2015" type="text" value="" required/>
</div>
<div class="col-sm-1">
<i class="fa fa-arrow-right" aria-hidden="true" ></i>
</div>
<div class="col-sm-4">
<input class="form-control" name="reg_year2[]" placeholder="2017" type="text" value="" required/><br/>
</div>
</div>
<div class="form-group">
<label for="concept" class="col-sm-12 control-label"><u>District Governer</u></label><br/>
<label for="concept" class="col-sm-3 control-label">Name :</label>
<div class="col-sm-9">
<input class="form-control" name="reg_name[]" placeholder="Your Language" type="text" required/><br/>
</div>
<label for="concept" class="col-sm-3 control-label">Nickname :</label>
<div class="col-sm-9">
<input class="form-control" name="reg_nickname[]" placeholder="English" type="text" required/><br/>
</div>
<label for="concept" class="col-sm-3 control-label">Photo :</label>
<div class="col-sm-9">
<input class="form-control" name="reg_photo[]" type="file" required/><br/>
</div>
</div>
<div class="pull-right">
+
</div>
</div>
</div>
</div>
<div class="panel-body panel-group">
<div class="form-group">
<div class="col-sm-1 text-left">
<button name="submit" type="submit" class="btn btn-info btn-lg" >Submit</button>
<!-- <button name="cancel" type="reset" class="btn btn-info">Cancel</button>-->
</div>
</div>
</div>
</div>
<?php echo form_close(); ?>
</div>
The 'reg_photo[]' are dynamically insert into HTML if user press the '+' button, so if i change to 'reg_photo' which is not dynamic anymore then it work, what should i do if i wanted to use the 'reg_photo[]' as a field name to upload my file? Please guide me through this. Thank! :)
/*
* Code above omitted purposely
* In your HTML form, your input[type=file] must be named *upl_files[]*
*/
/*
* Uploads multiple files creating a queue to fake multiple upload calls to
* $_FILE
*/
public function multiple_upload()
{
$this->load->library('upload');
$number_of_files_uploaded = count($_FILES['upl_files']['name']);
// Faking upload calls to $_FILE
for ($i = 0; $i < $number_of_files_uploaded; $i++){
$_FILES['userfile']['name'] = $_FILES['upl_files']['name'][$i];
$_FILES['userfile']['type'] = $_FILES['upl_files']['type'][$i];
$_FILES['userfile']['tmp_name'] = $_FILES['upl_files']['tmp_name'][$i];
$_FILES['userfile']['error'] = $_FILES['upl_files']['error'][$i];
$_FILES['userfile']['size'] = $_FILES['upl_files']['size'][$i];
$config = array(
'file_name' => <your ouw function to generate random names>,
'allowed_types' => 'jpg|jpeg|png|gif',
'max_size' => 3000,
'overwrite' => FALSE,
/* real path to upload folder ALWAYS */
'upload_path'
=> $_SERVER['DOCUMENT_ROOT'] . '/path/to/upload/folder'
);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}else {
$final_files_data[] = $this->upload->data();
// Continue processing the uploaded data
}
}
}
This Worked for me. reffer to this page this is not my code
https://gist.github.com/zitoloco/1558423
Try this code to upload image
$directory = "./images/";
$config['upload_path'] = $directory;
$config['encrypt_name'] = TRUE;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
if (!$this->upload->do_upload('mainimage'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else {
$data = array('upload_data' => $this->upload->data());
print_r($data);
}
And one other change is :
Replace upload.php file.
take latest verison upload.php file from system directory -> libraries directory -> upload.php. Copy new version upload.php file and replace in your project
Hope it will work properly.
Related
I'm trying to do the 2nd drop down population based on the 1st drop down by using ajax in codeigniter. But my problem is after I choose for 1st drop down value, when I try to choose for 2nd drop down value, it shows empty only.
(Update: I already fixed my problem. So, I already updated my code.)
Image below shows that the result after I choose for 1st option. When I try to select for 2nd option, it can't shows the value:
Here's is the code for view:
<div class="container">
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<div class="card">
<div class="card-body">
<h3 class="card-title text-center"><?php echo $content_heading;?></h3>
<form action="#" id="form" novalidate>
<div class="form-row">
<div class="col-sm-12">
<div class="form-group">
<label for="subject_name">Subject Name</label>
<select class="form-control" name="subject_name" id="subject_name">
<option>-- Select Subject Name --</option>
<?php foreach($attendance as $row){
echo "<option value='".$row['subject_id']."'>".$row['subject_name']."</option>";
}
?>
</select>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="lecturer_name">Lecturer Name</label>
<input name="lecturer_name" placeholder="Lecturer Name" class="form-control" type="text" disabled="">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="subject_section">Section</label>
<select class="form-control" name = "subject_section" id='subject_section'>
<option>-- Select Subject Section --</option>
</select>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="attendance_date">Date</label>
<input name="attendance_date" placeholder="Date" class="form-control" type="date">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="attendance_start_time">From</label>
<input name="attendance_start_time" placeholder="From" class="form-control" type="time">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="attendance_end_time">To</label>
<input name="attendance_end_time" placeholder="To" class="form-control" type="time">
<div class="invalid-feedback"></div>
</div>
<button type="button" id="btnSave" class="btn btn-primary btn-block" onclick="save()">Confirm</button>
</div>
</div>
</form>
</div>
</div>
</div>
Here is the javascript for the ajax function. (I already updated my javascript code.)
<script>
$(document).ready(function(){
// Subject change
$('#subject_name').change(function(){
var subject_id = $(this).val();
// AJAX request
$.ajax({
url : "<?php echo site_url('attendance/get_subject_section')?>",
method: 'POST',
data: {subject_id: subject_id},
dataType: 'JSON',
success: function(response){
// Remove options
$('#subjectsection').find('option').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#subject_section').append('<option value="'+data['subject_id']+'">'+data['subject_section']+'</option>');
});
}
});
});
});
</script>
Here is the code for controller:
<?php class attendance extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('Attendance Data/attendance_model','attendance');
}
function index(){
//$this->load->view('Manage User Registration/user_login_view');
$data['meta_title'] = 'Attendance';
$data['content_heading'] = 'Attendance';
$data['main_content'] = 'Manage Student Attendance/attendance';
$data['user_id'] = $this->session->userdata('id');
if($this->session->userdata('user_type')==='lecturer'){
$data['user_type'] = 'lecturer';
$data['meta_user_level_title'] = 'Lecturer';
$data['id'] = $this->session->id;
$data['main_content'] = 'Manage Student Attendance/lecturer_attendance_view';
$this->load->view('template/template', $data);
}else{
echo "Access Denied";
}
}
public function create_attendance()
{
$data['meta_title'] = 'Add Subject Attendance';
$data['content_heading'] = 'Add Subject Attendance';
$data['main_content'] = 'Manage Student Attendance/attendance';
$data['user_id'] = $this->session->userdata('id');
$data['user_type'] = 'lecturer';
$data['heading'] = 'Lecturer';
if($this->session->userdata('user_type')==='lecturer'){
$data['user_type'] = 'lecturer';
$data['attendance'] = $this->attendance->get_subject_name();
$data['meta_user_level_title'] = 'Lecturer';
$data['id'] = $this->session->id;
$data['main_content'] = 'Manage Student Attendance/create_attendance';
$this->load->view('template/template', $data);
}else{
echo "Access Denied";
}
}
public function get_subject_section()
{
// POST data
$subject_id= $this->input->post('subject_id');
// get data
$data = $this->attendance->get_subject_section($subject_id);
echo json_encode($data);
}}
Here is my code for model:
<?php class attendance_model extends CI_Model{
//Get subject name
public function get_subject_name()
{
$user_id = $this->session->userdata("id");
$response = array();
// Select record
$this->db->select('*');
$this->db->where('lecturer_id', $user_id);
$this->db->group_by('subject_id');
$query = $this->db->get('lecturer_timetable');
$response = $query->result_array();
return $response;
}
//Get subject section
public function get_subject_section($subject_id){
$user_id = $this->session->userdata("id");
$response = array();
// Select record
$this->db->select('subject_id, subject_section');
$this->db->where('lecturer_id', $user_id);
$this->db->where('subject_id', $subject_id);
$query = $this->db->get('lecturer_timetable');
$response = $query->result_array();
return $response;
}}
Can someone help me to solve this problem? Thanks.
your url in ajax is unreadable because of quotation. Try to writer in proper quotation. Use either single quotes inside double quotes or use double inside single. Second is, you are using method as 'POST' but in lowercase. Write POST in uppercase.
$.ajax({
url : "<?php echo site_url('attendance/get_subject_section')?>",
method: 'POST',
data: {subject_name: subject_name},
dataType: 'json',
success: function(response){
console.log(response); // first check by console that you are getting records in response. once you get response then append it or do whatever you want
}
});
I am trying to make update function for my project.
I have a table of Client data,
Delete, Add functions are working but whenever I use update function
it empties data of the row within database to null
I tried other things but didn't work well.
It could be a small mistake but I seem cannot find the problem as I been working on other projects wholeday :<
Update details php file
<?php
// include Database connection file
include("db_connection.php");
// check request
if(isset($_POST))
{
// get values
$id = $_POST['id'];
$Surname = $_POST['update_Surname'];
$Name= $_POST['update_Name'];
$Address = $_POST['update_Address'];
$Telephone = $_POST['update_Telephone'];
$PurchaseDate = $_POST['update_PurchaseDate'];
$Model = $_POST['update_Model'];
$SerialNumber = $_POST['update_SerialNumber'];
$Notes = $_POST['update_Notes'];
// Update User details
$query = "UPDATE Clients SET Surname = '$Surname', Name = '$Name', Address = '$Address', Telephone = '$Telephone', PurchaseDate = '$PurchaseDate', Model = '$Model', SerialNumber = '$SerialNumber', Notes = '$Notes' WHERE id = '$id'";
if (!$result = mysql_query($query)) {
exit(mysql_error());
}
}
update function
function UpdateUserDetails() {
// get values
var update_Surname = $("#update_Surname").val();
var update_Name = $("#update_Name").val();
var update_Address = $("#update_Address").val();
var update_Telephone = $("#update_Telephone").val();
var update_PurchaseDate = $("#update_PurchaseDate").val();
var update_Model = $("#update_Model").val();
var update_SerialNumber = $("#update_SerialNumber").val();
var update_Notes = $("#update_Notes").val();
// get hidden field value
var id = $("#hidden_user_id").val();
// Update the details by requesting to the server using ajax
$.post("ajax/updateUserDetails.php", {
id: id,
Surname: update_Surname,
Name: update_Name,
Address: update_Address,
Telephone: update_Telephone,
PurchaseDate: update_PurchaseDate,
Model: update_Model,
SerialNumber: update_SerialNumber,
Notes: update_Notes
},
function (data, status) {
// hide modal popup
$("#update_user_modal").modal("hide");
// reload Users by using readRecords();
readRecords();
}
);
}
Modal form
<div class="modal fade" id="update_user_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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" id="myModalLabel">Update</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="update_Surname">Surname</label>
<input type="text" id="update_Surname" placeholder="Surname" class="form-control"/>
</div>
<div class="form-group">
<label for="update_Name">Name</label>
<input type="text" id="update_Name" placeholder="Name" class="form-control"/>
</div>
<div class="form-group">
<label for="update_Address">Address</label>
<input type="text" id="update_Address" placeholder="Address" class="form-control"/>
</div>
<div class="form-group">
<label for="update_Telephone">Telephone</label>
<input type="text" id="update_Telephone" placeholder="Telephone" class="form-control"/>
</div>
<div class="form-group">
<label for="update_PurchaseDate">Purchase Date</label>
<input type="date" id="update_PurchaseDate" placeholder="Purchase Date" class="form-control"/>
</div>
<div class="form-group">
<label for="update_Model">Model</label>
<input type="text" id="update_Model" placeholder="Model" class="form-control"/>
</div>
<div class="form-group">
<label for="update_SerialNumber">Serial Number</label>
<input type="text" id="update_SerialNumber" placeholder="Serial Number" class="form-control"/>
</div>
<div class="form-group">
<label for="update_Notes">Notes</label>
<input type="text" id="update_Notes" placeholder="Notes" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="UpdateUserDetails()" >Save Changes</button>
<input type="hidden" id="hidden_user_id">
</div>
</div>
</div>
</div>
$id = $_POST['id'];
$Surname = $_POST['update_Surname'];
$Name= $_POST['update_Name'];
$Address = $_POST['update_Address'];
$Telephone = $_POST['update_Telephone'];
$PurchaseDate = $_POST['update_PurchaseDate'];
$Model = $_POST['update_Model'];
$SerialNumber = $_POST['update_SerialNumber'];
$Notes = $_POST['update_Notes'];
you are using update_ as your post variables. But the actual keys are different which you have provided into the jQuery post function. actual keys are defined in following object at left side of each assignment.
{
id: id,
Surname: update_Surname,
Name: update_Name,
Address: update_Address,
Telephone: update_Telephone,
PurchaseDate: update_PurchaseDate,
Model: update_Model,
SerialNumber: update_SerialNumber,
Notes: update_Notes
}
use the following instead.
$id = $_POST['id'];
$Surname = $_POST['Surname'];
$Name= $_POST['Name'];
$Address = $_POST['Address'];
$Telephone = $_POST['Telephone'];
$PurchaseDate = $_POST['PurchaseDate'];
$Model = $_POST['Model'];
$SerialNumber = $_POST['SerialNumber'];
$Notes = $_POST['Notes'];
The code below auto fills the Full name and Email when the user enters their ID. I also want to display the user's image but i'm having issues.
<script type="text/javascript">
$(function() {
$( "#techid" ).on( 'blur' , function() {
searchString = $(this).val();
var data = 'telefoon='+searchString;
if(searchString) {
$.ajax({
type : "POST",
url : "query2.php",
data : data,
success : function(html){
result = String(html).split("|");
$("#name").val(result[0]);
$("#mail").val(result[1]);
$("#avatar").val(result[2]);
}
});
}
return false;
});
});
</script>
I know I can display the image like this but how do i integrate it with the AJAX?
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include_once("connection.php");
$result = mysql_query("SELECT * FROM players3");
while($res = mysql_fetch_array($result)) {
echo '<img height="80px" width="100px" src="data:image/jpeg; base64,'.base64_encode( $res['image'] ).'"/>';
?>
I tried this:
<div class="form-group">
<label for="telefoon" class="col-sm-2 control-label">Avatar</label>
<div class="col-sm-10">
<img height="80px" width="100px" id="avatar" src="data:image/jpeg;base64,'.base64_encode( )"/>
</div>
</div>
<div class="form-group">
<label for="telefoon" class="col-sm-2 control-label">Tech ID</label>
<div class="col-sm-10">
<input type="text" name="techid" class="form-control" id="techid" placeholder="TechID" >
</div>
</div>
<div class="form-group">
<label for="naam" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" name="name" class="form-control" id="name" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="mail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" name="mail" class="form-control" id="mail" placeholder="email">
</div>
</div>
Like this?
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include_once("connection-db2.php");
$result = mysql_query("SELECT * FROM TechID");
while($res = mysql_fetch_array($result)) {
echo '<li><img height="80px" width="100px" src="data:image/jpeg;base64,'.base64_encode( $res['image'] ).'"/>';
}
?>
JS
$("#image").attr('src', result[4]);
when upload the image, save the image path with image file name. like "images/image1.jpg"
like the name and email, query the path of the image.
make a empty
after ajax success you get the path of the image. right? use this path like this. $("#image_to_show").html("");
<img> tag doesn't have value attribute
You should probably echo just image url and set it as a src attribute of your img tag
PHP:
while($res = mysql_fetch_array($result)) {
echo $res['image'];
// ...
}
JS:
$("#avatar").attr('src', result[2]);
On a side note - it would be better to json_encode response and use it instead of .split("|"). Something like this:
PHP:
$response = array();
while($res = mysql_fetch_array($result)) {
$response['name'] = $res['name'];
$response['email'] = $res['email'];
$response['image'] = $res['image'];
}
echo json_encode($response);
JS:
$.ajax({
type : "POST",
url : "query2.php",
data : data,
dataType : "json",
success : function(result){
$("#name").val(result.name);
$("#mail").val(result.email);
$("#avatar").attr('src', result.image);
}
});
This question already has answers here:
PHP Redirect to another page after form submit
(6 answers)
Closed 8 years ago.
So after I used the new JavaScript. Here is all of the code. Just keep in mind their is still top body missing. Didn't put that in as it might not be relevant to my problem.
<?php
// define variables and set to empty values
$nameErr = $surnameErr = $emailErr = $contact_numberErr = "";
$name = $surname = $email = $comment = $contact_number = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["surname"])) {
$surnameErr = "Surname is required";
} else {
$surname = test_input($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["contact number"])) {
$contact_numberErr = "Please provide contact details";
} else {
$contact_number = test_input($_POST["contact number"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contact_number)) {
$contact_number = "Only numbers allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="container" align="center">
<div class="row featured-boxes login">
<div class="col-md-6">
<div class="featured-box featured-box-secundary default info-content">
<div class="box-content">
<h4 align="center">Customer Feedback</h4>
<p><span class="error">* required field.</span></p>
<form method="post" action="insert_customer_feedback.php" name="customer_feedback">
<div class="row">
<div class="form-group">
<div class="col-md-12">
<span class="error"><label>Name</label> *<?php echo $nameErr;?></span>
<input type="text" value="" class="form-control input-lg" id="txtName" name="txtName">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<span class="error"><label>Surname</label> *<?php echo $surnameErr;?></span>
<input type="text" value="" class="form-control input-lg" id="txtSurname" name="txtSurname">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<span class="error"><label>E-mail</label> *<?php echo $emailErr;?></span>
<input type="text" value="" class="form-control input-lg" id="txtEMail" name="txtEmail">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<span class="error"><label>Contact Number</label> *<?php echo $contact_numberErr;?></span>
<input type="text" value="" class="form-control input-lg" id="txtContact_number" name="txtContact_number">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Comment</label>
<input type="text" value="" class="form-control input-lg" id="txtComment" name="txtComment">
</div>
</div>
<input type="button" value="Submit" class="btn btn-primary pull-right push-bottom" onClick="Confirm(this.form)">
</div>
</div>
</form>
<script type="text/javascript">
function Confirm(form){
alert("Thank you for your feedback.");
form.submit();
window.location.href = "/index.php";
}
</script>
For some reason it does not want to load my data into MySQL when having this peace of JavaScript (window.location.href = "/index.php";) added.
you can simply do it using
function Confirm(form){alert("Thank you for your feedback.");form.submit();
window.location = "location";
}
If you want to do the redirect in JavaScript it would be:
window.location.replace("yourwebsite.com/index.php");
If you wanted to do it in PHP, then it would be:
header('Location:index.php');
When you do the form.submit() you tell the form to perform the action which is stated in the forms action attribute. Thus it will automatically be redirected to whatever is set there.
Example:
<form action="submit.php" method="POST">
You code will redirect the user to the submit.php after he dismisses the alert message. When redirected to the submit.php you will have to handle a redirect from there on.
This is of course unless you are using AJAX to post the form or something like that.
Then you can just add:
window.location.href = "/index.html";
Although, in that case, it would better be placed in the success-function of the AJAX call:
function Confirm(form){alert("Thank you for your feedback.");form.submit(); window.location.href = "/index.html";}
I am in the process of building a blog. My client wants the option of uploading a image when necessary, but not all the time. I wrote the code to do this but I think I missed something. Anybody willing to help me debug is greatly appreciated.
if (!in_array($file_ext,$allowed_ext)) {
$errors[] = strtoupper($file_ext).'\'s is not an approved file extension. Please try again. Approved extensions are '.implode(',', $allowed_ext).'.';
}
The snippet of code above is from the page below and is the error that keeps getting triggered.
if (empty($_POST) === false) {
$allowed_ext = array('jpg','jpeg','png');
if (isset($_FILES['image']) && !empty($_FILES['image'])) {
$file_name = $_FILES['image']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
if (!in_array($file_ext,$allowed_ext)) {
$errors[] = strtoupper($file_ext).'\'s is not an approved file extension. Please try again. Approved extensions are '.implode(',', $allowed_ext).'.';
} else if ($file_size > 655360) {
$errors[] = 'File Size to large. Please try a different image';
}
}
if (empty($errors) === true) {
if (isset($_FILES['image']) === true && empty($_FILES['image']) === false) {
$file_name = md5($file_name).'.'.$file_ext;
move_uploaded_file($file_tmp, '../assets/images/'.$file_name);
$image_location = 'assets/images/'.$file_name;
}
$data = array(
'title' => $_POST['title'],
'category_id' => $_POST['category_id'],
'author_id' => $session_user_id,
'author_name' => $user_data['admin_name'],
'summary' => $_POST['summary'],
'contents' => nl2br($_POST['content']),
'image' => $image_location,
'date' => date("F j, Y"),
'time' => date("h:i a e")
);
echo 'Something Cool';
insertPost($db, $data);
header('Location: new.php?success');
}
}
echo '<div id="page-wrapper">';
echo '<div class="row">';
?>
<div class="col-lg-12">
<h1>Write a new post <small></small></h1>
<ol class="breadcrumb">
<li> Dashboard</li>
<li>Write A New Post</li>
</ol>
</div>
</div>
<?php
if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
$success = '
<div class="alert alert-success">
<h4>Blog Post Successively Submitted</h4>
<p>Your blog post was successfully submitted to the database. Go check it out on the homepage!
</div>
';
echo $success;
} else {
if (empty($errors) === false) {
echo '<div class="alert alert-danger"><srong>After trying to process your request, the following errors occured:</strong>';
echo output_errors($errors);
echo '</div>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="col-lg-6 col-sm-12">
<div class="form-group">
<label for="title">Title</label><br>
<input name="title" type="text" class="form-control" placeholder="Title of Post" required/>
</div>
<div class="form-group">
<label for="category_id">Category</label><br>
<select name="category_id" class="form-control">
<option value=""> --Select a Category-- </option>
<?php
$query = $db->prepare("SELECT category_id, category_name FROM catagories");
$query->execute();
while ($result = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$result['category_id'].'">'.$result['category_name'].'</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="summary">Summary</label><br>
<textarea name="summary" class="form-control" rows="3" placeholder="Summary of your post. Keep it short and simple as this is what will be displayed on the homepage"></textarea>
</div>
<div class="form-group">
<label for="content">Content</label><br>
<textarea id="wysihtml5-textarea" class="textarea-wysiwyg form-control" rows="10" name="content" placeholder="Article Contents Go Here"></textarea>
</div>
<div class="form-group">
<label for="image">Image</label><br>
<input type="file" name="image" class="form-control" />
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Submit Post</button> <button class="btn btn-danger" type="reset">Reset Form</button>
</div>
<?php } ?>
</form>
</div>
<div class="col-lg-6 col-sm-12">
<h3>Posting Guidelines and Restrictions</h3>:
<strong>Restrictions</strong>
<ul>
<li>Images extensions are restricted to JPG's, JPEG's, & PNG's</li>
<li>Image file sizes are limited to 5mb</li>
</ul>
<strong>Guidelines</strong>
<ul>
<li>All the fields are required. Submiting the form with any of the fields left empty will result in errors.</li>
<li>The summary should be kept to less then a single paragraph. It is what is displayed on the homepage.</li>
<li>I'm not really sure what else to put here. Email me if you have any questions.</li>
</ul>
</div><!-- /#page-wrapper -->
<?php
include 'includes/footer.php'; ?>
If conditions are wrong. You are wrongly validating if image is uploaded or not.
Change
if (isset($_FILES['image']) && !empty($_FILES['image']))
To
if (isset($_FILES['image']) && $_FILES['image']['error'] == 0 && $_FILES['image']['size'] > 0)
Also change if condition in similar way, where you are moving/saving image.