php mysql update query gives an empty result - javascript

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'];

Related

No response when making POST request

I'm developing a CRUD application as part of a course I am studying.
I'm able to read data from my DB, however I am now trying to add data - a new employee in this case as I am developing a company directory and so far I'm unsuccessful.
I know the issue isn't the connection with the DB as I'm able to read data. However the function getEmployeeData(); function to refresh the display of current employee records after the new addition is never called in the $.post callback func so I suspect the error happens before this point. You'll see in my code below that I'm attempting to print the firstName variable to the console. The firstName does appear in the console when the form is submitted but only for less than a second then it disappears.
I'm really stumped as to what is causing this issue.
Please see my code below:
The form in index.html:
<!--Form to add employee-->
<div class="modal fade" id="addEmployeeModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Employee</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form id="addEmployeeForm" onsubmit="addEmployee()">
<div class="modal-body">
<div class="names">
<input type="text" class="form-control" style="width: 48% !important;" id="newFirstName" name="newFirstName" placeholder="First Name..." required>
<input type="text" class="form-control" style="width: 48% !important;" id="newLastName" name="newLastName" placeholder="Last Name..." required>
</div>
<div class="names">
<input type="email" class="form-control" id="newEmail" name="email" placeholder="E-mail">
</div>
<div id="location-dept">
<select id="add-employee-dept-list" class="form-select" aria-label="Default select example" name="newDepartment">
<option selected>Department</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
<!--End of add employee modal-->
The addEmployee() function:
function addEmployee() {
let firstName = $('#newFirstName').val();
let lastName = $('#newLastName').val();
let email = $('#newEmail').val();
let departmentID = $('#add-employee-dept-list').val();
console.log(firstName);
$.post(
"php/addNewEmployee.php",
{
fname: firstName,
lname: lastName,
email: email,
department: departmentID
},
function(data) {
getEmployeeData();
alert(data + "It worked");
}
)
}
addNewEmployee.php:
<?php
// example use from browser
// http://localhost/companydirectory/libs/php/insertDepartment.php?name=New%20Department&locationID=<id>
// remove next two lines for production
echo($_POST['$firstName']);
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true);
// this includes the login details
include("config.php");
header('Content-Type: application/json; charset=UTF-8');
$conn = new mysqli($cd_host, $cd_user, $cd_password, $cd_dbname, $cd_port, $cd_socket);
if (mysqli_connect_errno()) {
$output['status']['code'] = "300";
$output['status']['name'] = "failure";
$output['status']['description'] = "database unavailable";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
$output['data'] = [];
mysqli_close($conn);
echo json_encode($output);
exit;
}
// SQL statement accepts parameters and so is prepared to avoid SQL injection.
// $_REQUEST used for development / debugging. Remember to change to $_POST for production
$jobTitle = "";
$query = $conn->prepare('INSERT INTO personnel (firstName, lastName, jobTitle, email, departmentID) VALUES(?,?,?,?)');
$query->bind_param("si", $_REQUEST['fname'], $_REQUEST['lname'], $jobTitle, $_REQUEST['email'], $_REQUEST['department']);
$query->execute();
if (false === $query) {
$output['status']['code'] = "400";
$output['status']['name'] = "executed";
$output['status']['description'] = "query failed";
$output['data'] = [];
mysqli_close($conn);
echo json_encode($output);
exit;
}
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
$output['data'] = [];
mysqli_close($conn);
echo json_encode($output);
?>

populate 2nd drop down based on 1st drop down result by using ajax in codeigniter php

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
}
});

Show a modal with receipt after submit form (Codeigniter)

My target is, after I submit the form, there'll be a modal after reload that shows the transaction details. I have made a next page transaction details, however, it is much better to do the receipt php on onload modal after submission. But I don't know how to start. I provided a screenshot below of my current work. Any help will be appreciated. Thank you
View:
<button type="button" data-id="<?php echo $rows->userID; ?>" data-firstname="<?php echo $rows->firstname; ?>" class=" showmodal btn btn-success btn-sm text-bold " data-toggle="modal" data-target="#fundModal"><i class="fas fa-hand-holding-usd mr-1"></i> FUND </button> // This button shows modal when clicked
//This is my modal for transferring fund
<div class="modal fade" id="fundModal" tabindex="-1" role="dialog">
<div class="modal-dialog " role="document">
<div class="modal-content">
<div class="modal-header bg-green">
<h5 class="modal-title text-bold" id="exampleModalLabel">Fund</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body bg-white text-center">
<label><h3>Transfer fund:</h3></label>
<br>
<!-- FORM -->
<div id="errorMessage" style="color: red; display: none; font-size: 11px"></div>
<form method="POST" action="<?php echo site_url('network/form_validation');?>">
<div class="input-group input-group-sm" style="width: 100%" >
<input type="hidden" id="usertransferid" name="userID">
<input type="hidden" id="firstname" name="receiptname" value="<?php echo $rows->firstname; ?>">
<div class="col-lg-12" >
<input type="text" placeholder="Enter Amount" name="amount" autocomplete="new-amount" value="" class="form-control number" id="box" >
<br>
<?php echo $this->session->flashdata('warning'); ?>
<input type="password" placeholder="Enter Password" autocomplete="new-password" name="fundpass" class="form-control" id="password" required ">
<br>
<!-- buttons -->
<input type="submit" class="btn btn-success text-bold" name="save" id="insert" value="Transfer">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Controller:
public function form_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("amount","Amount", 'required|numeric');
$this->load->library('form_validation');
$this->form_validation->set_rules('fundpass', 'fundpass', 'callback_password_check');
if($this->form_validation->run() == false) {
echo '<script>alert("Invalid input of Password!");</script>';
redirect('network/agents', 'refresh');
}
else {
if($this->form_validation->run())
{
$ref= $this->session->userdata('uid') + time ();
$id = $this->input->post('userID');
$fname = $this->input->post('receiptname');
$pData = array(
'userID' => $id,
'transactionSource' => 'FR',
'refNumber' => 'FI' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"in",
);
$this->networks->fundin($pData);
$ref= $this->session->userdata('userID') + time ();
$data1 = array(
'userID' => $this->session->userdata('uid'),
"transactionSource" => 'FR',
"refNumber" => 'FO' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"out",
);
$this->networks->insert_data($data1);
// return json_encode($data1);
$_SESSION["amount"] = $this->input->post("amount");
$_SESSION["receivedID"] = $id;
$_SESSION["receiptFName"] = $fname;
$_SESSION["reference"] = $this->input->post("refNumber");
redirect(base_url() . "network/receipt");
}
else
{
$this->index();
}
}
}
public function password_check($fundpass)
{
$id = $this->session->userdata('uid');
if($this->session->userdata('password')!== md5($fundpass)) {
$this->form_validation->set_message('password_check', 'The {field} does not match');
return false;
}
return true;
}
Model:
function fundin($data)
{
// Fund in
$id = $this->input->post('userID');
$sqlInsertLedger = "INSERT INTO transaction_ledger (transactionSource, transType, refNumber, userID, amount, currentBalance, previousBalance, remarks, createdBy)
select '".$data['transactionSource']."', '".$data['transType']."', '".$data['refNumber']."', ".$data['userID'].", ".$data['amount'].", sum(TU.currentPoints + ".$data['amount'].") as totalPoints, TU.currentPoints,
'funded by agent', '".$this->session->userdata('uid')."'
from users TU where TU.userID=?";
$Q = $this->db->query($sqlInsertLedger, $data['userID']);
//update user table
$sqlUpdate = "update users set currentPoints = currentPoints + ? where userID = ?";
$Q = $this->db->query($sqlUpdate, array($data['amount'], $data['userID']));
}
function insert_data($data1)
{
// fund out
$sql1 = "select * from transaction_ledger where userID = ? order by ledgerID desc limit 0,1";
$Q1 = $this->db->query($sql1, $data1['userID']);
$R1 = $Q1->row_array();
$ref= $this->session->userdata('userID') + time ();
$idata1 = array(
'userID' => $data1['userID'],
'transactionSource' => 'FR',
'transType' => 'out',
'refNumber' => 'FO' . $ref,
'amount' => $data1['amount'],
'currentBalance' => $R1['currentBalance'] - $data1['amount'],
'previousBalance' => $R1['currentBalance'],
'remarks' => 'transfer fund to agent',
);
$this->db->insert('transaction_ledger', $idata1);
$sqlUpdate = "update users set currentPoints = '".$idata1['currentBalance']."', dateUpdated = '".date('Y-m-d h:i:s')."'where userID = ?";
$this->db->query($sqlUpdate, $idata1['userID'] );
}
You can programmatically open the bootstrap modal when document ready
Just like
$(document).ready(function(){
$("#fundModal").modal('show');
});
</script>
I would suggest to do with ajax call for better user experience.
$( "#formId" ).on('submit', function(e){
e.preventDefault();
let $form = $(this);
$.post( 'post-url-here', $form.serialize(), function(result) {
var result = JSON.parse(result);
if( result.status == 'success' ) {
$("#fundModal").modal('show');
}
});
});

Codeigniter upload image file with array field name

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.

AJAX + phpmailer errors

Getting a 500 Internal Server error on the client side when trying to test with phpmailer.
Based on my knowledge, it's throwing the error due to a misplaced or nonexistent file, but the file is actually there.
Here's a screenshot of the file structure for the site and for the includes file
PHP
<?php
// $email and $message are the data that is being
// posted to this page from our html contact form
// $email = $_POST['email'] ;
// $message = $_POST['message'] ;
// When we unzipped PHPMailer, it unzipped to
// based on where this php file sites, i gave it the following path.
// But also tried, '../includes/phpmailer.class.phpmailer.php'
// and also tried, 'phpmailer.class.phpmailer.php'
require_once("includes/phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587;
$mail->Username = "patrick.johnson9#gmail.com";
$mail->Password = "corner09";
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddAddress("im#pbj.me","First Last")
$mail->Subject = "PHPMailer Test Subject via smtp (Gmail), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
JAVASCRIPT
// Form submission
$("#form-apply").submit(function(e){
e.preventDefault();
// get the form data
var formData = {
"name": $("input[name='name']").val(),
"email": $("input[name='email']").val(),
"message": $("input[name='message']").val(),
// "upload": $("textarea[name='upload']").val()
};
console.log(formData);
$.ajax({
type: "POST", //define the type of HTTP verb we want to use
url: "../includes/form-apply.php",
data: formData, //our data object
dataType: "json",
encode: true
}).done(function(data){ //using the done promise callback
// log the data to the console so we can see it
console.log(data);
if(! data.success){
if (data.errors.name){
$("#name").parent().addClass("has-error");
$(".name-group").append("<div class='help-block'>" + data.errors.name + "</div>");
// $("#name").attr("placeholder", data.errors.name);
}
if(data.errors.email){
$("#email").parent().addClass("has-error");
$(".email-group").append("<div class='help-block'>" + data.errors.email + "</div>");
}
if(data.errors.subject){
$("#subject").parent().addClass("has-error");
$(".subject-group").append("<div class='help-block'>" + data.errors.subject + "</div>");
}
if(data.errors.message){
$("#message").parent().addClass("has-error");
$(".message-group").append("<div class='help-block'>" + data.errors.message + "</div>");
}
} else {
$(".form-apply").prepend("<div class='alert alert-success'>" + data.message + "</div>")
$("input, textarea").val("");
}
}).fail(function(data){
$("#form-apply").prepend("<div class='alert alert-danger'>" + data.errors + "</div>");
console.log(data.errors);
});
});
HTML NOTE THIS MODULE IS A PHP INCLUDE CALLED 'CAREER-MODAL.PHP WHICH EXISTS IN THE 'INCLUDES' DIRECTORY.
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title center" id="myModalLabel">Career Application</h4>
</div>
<div class="modal-body">
<form id="form-apply" role="form" method="POST" action="includes/form-apply.php">
<div class="row">
<div class="col-md-6">
<div class="form-group name-group">
<label for="name">Full Name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Full Name" tabindex="1" required="required">
</div>
</div>
<div class="col-md-6">
<div class="form-group email-group">
<label for="name">Email</label>
<input type="text" name="email" id="email" class="form-control" placeholder="Email Address" tabindex="2" required="required">
</div>
</div>
</div>
<div class="form-group .message-group">
<label for="name">Summary of Background</label>
<textarea name="message" id="message" class="form-control" placeholder="Message" tabindex="3" required="required"></textarea>
</div>
<div class="form-group">
<label for="name">Upload Resume</label>
<input type="file" name="upload" id="upload" class="form-control" placeholder="No File Chosen" tabindex="4">
</div>
<div class="row center">
<button class="btn btn-secondary" tabindex="4">submit</button>
</div>
</form>
</div>
</div>
</div>
</div>

Categories