first of all, sorry for my english.
Well, I'm new to OOP PHP. I tried to develope a simple project and I would like to load data with Ajax to view changes without reloading pages.
I don't post models because they work fine and I can get all data I need.
But I have problems sending Controller errors and displaying them to the client.
I have a view called "viewUser.php" = main view.
In the main view is loaded "listUsers.php" in a div by an ajax call to display all the users, than each user has a button to send to another ajax call the id so this last ajax call can populate modal body with all the user informations in a form so they could be modified.
In this way all changes to user informations are displayed without reload the page but only with a ajax call in realtime.
I have this controller:
public function editUsers()
{
$data = [
'id' => '',
'name' => '',
'surname' => '',
'privilege' => '',
'position' => '',
'verified' => '',
'email' => ''
];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT);
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$surname = filter_var($_POST['surname'], FILTER_SANITIZE_STRING);
$privilege = filter_var($_POST['privilege'], FILTER_SANITIZE_STRING);
$position = filter_var($_POST['position'], FILTER_SANITIZE_NUMBER_INT);
$verified = filter_var($_POST['verified'], FILTER_SANITIZE_NUMBER_INT);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$data = [
'id' => trim($id),
'name' => trim($name),
'surname' => trim($surname),
'privilege' => trim($privilege),
'position' => trim($position),
'verified' => trim($verified),
'email' => trim($email),
];
$nameValidation = "/^[a-zA-Z]*$/";
//Valida il nome
if (empty($name)) {
$error['nameError'] = 'Perfavore, inserisci il tuo nome!';
} elseif (!preg_match($nameValidation, $name)) {
$error['nameError'] = 'Il nome può contenere solo lettere!';
}
//Controlla che gli errori siano vuoti
if (empty($error['nameError'])) {
$this->userManagementModel->editUser($data);
}
}}
called by ajax
function ajaxEditUser() {
$(document).on("click", "#editUser", function (event) {
event.preventDefault();
var id = $.trim($('#floatingInputId').val());
var name = $.trim($('#floatingInputName').val());
var surname = $.trim($('#floatingInputSurname').val());
var email = $.trim($('#floatingInputEmail').val());
var password = $.trim($('#floatingInputPassword').val());
var confirmPassword = $.trim($('#floatingInputConfirmPassword').val());
var privilege = $.trim($('#floatingSelectPrivileges').val());
var position = $.trim($('#floatingSelectPositions').val());
var verified = $.trim($('#floatingSelectVerified').val());
$.ajax({
url: URLROOT + '/usersManagement/editUsers',
type: 'post',
data: {
id: id,
name: name,
surname: surname,
email: email,
password: password,
confirmPassword: confirmPassword,
privilege: privilege,
position: position,
verified: verified
},
success: function (response) {
// Riaggiorna gli utenti
$(".loadAjax").load(URLROOT + '/usersManagement/listUsers');
$('#closeExampleModal').trigger('click');
}
});
});}
Data is sent from a form in a modal populated by another Ajax request that populates a view loaded into those modal
I would like to view the error generated by controls (if they exist) in editUsers function, into modal
This is ajax call that populates modal:
function ajaxModalUser() {
$(document).on("click", ".btnEditUser", function () {
var userid = $(this).data('id');
// Richiesta AJAX
$.ajax({
url: URLROOT + '/usersManagement/modalUserInfo',
type: 'post',
data: {userid: userid},
success: function (response) {
// Aggiunge il response nel body del modal
$('.modal-body').html(response);
// Apre il modal
$('#exampleModal').modal('show');
}
});
});
}.
here the controller for ajax request for modal:
public function modalUserInfo()
{
$data = [
'users' => '',
'privileges' => '',
'positions' => '',
'noResults' => ''
];
if (isset($_POST['userid'])){
$users = $this->userManagementModel->userInfo($_POST['userid']);
$privileges = $this->userManagementModel->selectPrivileges();
$positions = $this->userManagementModel->selectPositions();
$data = [
'users' => $users,
'privileges' => $privileges,
'positions' => $positions,
'noResults' => 'Nessun risultato'
];
}
$this->view('usersManagement/modalUserInfo', $data);
}
and here the page of the view loaded into modal
<?php
require APPROOT . '/views/includes/head.php';
?>
<div class="container">
<?php if (!empty($data)) {
foreach ($data['users'] as $user) :?>
<form method="post">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputId" name="id" value="<?php echo $user->id;?>" placeholder="id" hidden>
<label for="floatingInputId">Id</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="floatingSelectVerified" name="verified" value="" aria-label="Floating label select example">
<option <?php if ($user->verified == 2){ echo 'selected';} ?> value="2">VERIFICATO</option>
<option <?php if ($user->verified == 1){ echo 'selected';} ?> value="1">NON VERIFICATO</option>
</select>
<label for="floatingSelectVerified">Verifica</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputName" name="name" value="<?php echo $user->name;?>" placeholder="nome">
<label for="floatingInputName">Nome</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputSurname" name="surname" value="<?php echo $user->surname;?>" placeholder="cognome">
<label for="floatingInputSurname">Cognome</label>
</div>
<div class="form-floating mb-3">
<input type="email" class="form-control" id="floatingInputEmail" name="email" value="<?php echo $user->email;?>" placeholder="email">
<label for="floatingInputEmail">Email</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="floatingInputPassword" name="password" value="" placeholder="password">
<label for="floatingInputPassword">Password</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="floatingInputConfirmPassword" name="confirmPassword" value="" placeholder="confirm password">
<label for="floatingInputConfirmPassword">Conferma Password</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="floatingSelectPrivileges" name="privileges" value="" aria-label="Floating label select example">
<?php foreach ($data['privileges'] as $privilege) :?>
<option <?php if ($user->privilege_code == $privilege->privilege_code){ echo 'selected';} ?> value="<?php echo $privilege->privilege_code;?>"><?php echo $privilege->privilege;?></option>
<?php endforeach; ?>
</select>
<label for="floatingSelectPrivileges">Privilegi</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="floatingSelectPositions" name="positions" value="" aria-label="Floating label select example">
<?php foreach ($data['positions'] as $position) :?>
<option <?php if ($user->position_id == $position->id){ echo 'selected';} ?> value="<?php echo $position->id;?>"><?php echo $position->user_position;?></option>
<?php endforeach; ?>
</select>
<label for="floatingSelectPositions">Carica</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputCreationDate" name="creationDate" value="<?php if(!is_null($user->creation_date)){echo date("d/m/Y H:i:s", strtotime($user->creation_date));} else { echo "--";} ?>" placeholder="creato il" disabled>
<label for="floatingInputLastUpdate">Data registrazione :</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputLastUpdate" name="lastUpdate" value="<?php if(!is_null($user->last_update)){echo date("d/m/Y H:i:s", strtotime($user->last_update));} else { echo "--";} ?>" placeholder="ultimo aggiornamento" disabled>
<label for="floatingInputLastUpdate">Ultima modifica :</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputLastLogin" name="lastLogin" value="<?php if(!is_null($user->last_login)){echo date("d/m/Y H:i:s", strtotime($user->last_login));} else { echo "--";} ?>" placeholder="ultimo login" disabled>
<label for="floatingInputLastLogin">Ultimo login :</label>
</div>
</form>
<?php endforeach;
}?>
</div>
I tried many solutions, but I can't understand how send the error to the view of the modal and reloading it into modal.
Thanks to everybody
Related
My Ajax script is not going to controller and data is not uploading.
Script is:
$("#update").click(function(event) {
/* Act on the event */
var chango = $("#update_form").serialize();
alert(chango);
$.ajax({
type:"POST",
url:"<?php echo base_url() ?>home/update_profile",
data:{id:id}
},
function(data) {
console.log(data);
list_user();
});
event.preventDefault();
});
and my controller is:
public function update_profile()
{
try {
$this->load->library('form_validation');
$this->form_validation->set_rules("fname", "First Name", 'required|alpha');
$this->form_validation->set_rules("lname", "Last Name", 'required|alpha');
$this->form_validation->set_rules("mobile", "Mobile", 'required');
$this->form_validation->set_rules("dob", "Date of Birth", 'required');
$this->form_validation->set_rules("gender", "Gender", 'required');
if ($this->form_validation->run()){
$this->load->model("user");
$data=array(
'fname' => $this->input->post('fname'),
'lname' => $this->input->post('lname'),
'mobile' => $this->input->post('mobile'),
'dob' => $this->input->post('dob'),
'gender' => $this->input->post('gender')
);
if ($this->input->post("update")) {
$this->user->update_data($data, $this->input->post("id"));
redirect(base_url() . "home/list_user");
}
}
else
{
}
}
catch(Exception $e) {
}
$this->load->view('middlepage/update_profile.php');
}
public function update()
{
$user_id = $this->uri->segment(3);
$this->load->model("user");
$data["user_data"] = $this->user->fetch_single_data($user_id);
$data["fetch_data"] = $this->user->fetch_data1();
$this->load->view("middlepage/update_profile", $data);
}
And my model is:
public function fetch_single_data($id)
{
$this->db->where("id", $id);
$query = $this->db->get("user");
return $query;
}
public function update_data($data, $id)
{
$this->db->where("id", $id);
return $this->db->update("user", $data);
}
And my view is:
<form method="post" id="update_form" enctype="multipart/form-data" novalidate="true">
<?php if(isset($user_data))
{
foreach ($user_data->result() as $row) {
?>
<div class="form-group valid-form">
<h4>First Name:</h4>
<input type="text" class="form-control" id="fname" name="fname" value="<?php echo $row->fname ; ?>">
<span class="text-danger"><?php echo form_error("fname");?></span>
</div><br>
<div class="form-group valid-form">
<h4>Last Name:</h4>
<input type="text" class="form-control" id="lname" name="lname" value="<?php echo $row->lname ; ?>">
<span class="text-danger"><?php echo form_error("lname");?></span>
</div><br>
<div class="form-group valid-form">
<h4>Mobile:</h4>
<input type="text" class="form-control" id="mobile" name="mobile" value="<?php echo $row->mobile ; ?>">
<span class="text-danger"><?php echo form_error("mobile");?></span>
</div><br>
<div class="form-group valid-form">
<h4>Date of Birth:</h4>
<input type="date" class="form-control" min="1984-01-01" max="2005-12-31" id="dob" name="dob" value="<?php echo $row->dob ; ?>">
<span class="text-danger"><?php echo form_error("dob");?></span>
</div><br>
<div class="form-group">
<h4>Gender</h4>
<div class="radio">
<label>
<input type="radio" name="gender" id="male" value="male"<?php if($row->gender == 'male') echo "checked"; ?>><span style="font-weight: bolder; font-size: 15px;">Male</span>
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="gender" id="female" value="female"<?php if($row->gender == 'female') echo "checked"; ?>><span style="font-weight: bolder; font-size: 15px;">Female</span>
</label>
</div>
<span class="text-danger"><?php echo form_error("gender");?></span>
</div><br>
<div class="form-group">
<input type="hidden" name="id" value="<?php echo $row->id ?>">
<input type="submit" name="update" id="update" value="Update" class="btn btn-primary">
</div>
<?php
}
}
?>
</form>
i can't update data in database and it is not going to list table
ajax function is not working and not going to codeigniter's controller
while is try this type of similar code to submit it is work perfectly
From where you get id which you pass as data in id field
$.ajax({
type:"POST",
url:"<?php echo base_url() ?>home/update_profile",
data:{id:id} <--
},
I was about to update my existing data in sql.
I am updating the data using ajax with validation error
ajax validation works on my account creation and change password
below are my ajax code
$('#form-battery-update').submit(function(e) {
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
// url: me.attr('action'),
url: '<?php echo base_url(); ?>msasset/update_battery_form_validation',
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response) {
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' UPS Battery has been created' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
// close the message after seconds
$('.alert-success').delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
})
}
else {
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value);
});
}
}
});
});
below are my code from my views folder
<div class="card-body p-0">
<?php echo form_open("msasset/update_battery_form_validation", array("id" => "form-battery-update", "class" => "form-horizontal")) ?>
<div class="row">
<div class="col-lg-5 d-none d-lg-block bg-register-image"></div>
<div class="col-lg-7">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4"><?php echo $title; ?></h1>
<div id="the-message"></div>
</div>
<?php
if(isset($fetch_single_battery))
{
foreach($fetch_single_battery->result() as $row)
{
?>
<div class="form-group">
<label>Battery SerialNumber</label> </br>
<p class="form-control"> <?php echo $row->SerialNumber; ?></p>
</div>
<div class="form-group">
<label>PO Number</label> </br>
<input type="text" name="PONumber" value="<?php echo $row->PONumber; ?>" class="form-control"/>
</div>
<div class="form-group">
</div>
<div class="form-group">
<label>Ticket</label>
<input type="text" name="ticketid" value="<?php echo $row->TicketNumber; ?>" class="form-control" />
<span class="text-danger"><?php echo form_error("ticketid"); ?></span>
</div>
<div class="form-group">
</div>
<div class="form-group">
<label>Data Port</label>
<select class="form-control" name="select_port">
<option class="form-control" selected><?php echo $row->DataPort; ?></option>
<?php foreach ($GetPortLocation as $Port) { ?>
<option value="<?php echo $Port['DataPort']; ?>"><?php echo $Port['DataPort']; ?></option>
<?php } ?>
</select>
<span class="text-danger"><?php echo form_error("select_port"); ?></span>
<span class="text-danger"></span>
</div>
<div class="form-group">
<label>UPS Asset Tag</label>
<input type="text" name="ups_asset_tag" value="<?php echo $row->UPS_AssetTag; ?>" class="form-control" />
<span class="text-danger"></span>
</div>
<div class="form-group">
<label>Date Installed</label>
<input type="date" name="date_installed" value="<?php echo $row->DateInstalled; ?>" class="form-control" />
<span class="text-danger"></span>
</div>
<div class="form-group">
<label>Status</label>
<select class="form-control" name="select_status">
<option class="form-control" selected><?php echo $row->Status; ?></option>
<?php foreach($get_AssetStatus as $AssetStatus){?>
<option value="<?php echo $AssetStatus['AssetStatus']; ?>"><?php echo $AssetStatus['AssetStatus']; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<input type="hidden" name="hidden_id" value="<?php echo $row->ID; ?>" />
<input type="submit" name="update" id="update" value="Update" class="btn btn-info" />
<input type="submit" name="insert" id="insert" value="Update" class="btn btn-primary">
</div>
<?php
}
}
?>
</form>
</div>
</div>
</div>
</div>
below codes from my controller
function update_battery_form_validation()
{
$data = array('success' => false, 'messages' => array());
$this->load->library('form_validation');
$this->form_validation->set_rules('PONumber','po number','required');
// $this->form_validation->set_rules('ticketid','ticket id','required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('assets_model');
$data = array(
'PONumber' => $this->input->post('PONumber'),
'TicketNumber' => $this->input->post('ticketid'),
'DataPort' => $this->input->post('select_port'),
'UPS_AssetTag' => $this->input->post('ups_asset_tag'),
'DateInstalled' => $this->input->post('date_installed'),
'Status' => $this->input->post('select_status'),
'PerformedBy' => $this->session->userdata('user_name')
);
if($this->input->post('update'))
{
$this->assets_model->update_battery($data,$this->input->post('hidden_id'));
$this->session->set_flashdata('batteries_updated','New battery has been updated successfully');
redirect('msasset/ups_batteries');
}
}
else
{
// echo validation_errors();
foreach ($_POST as $key => $value)
{
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
I was expecting that every time there is an empty fields it should give me an a this fields required messages and also if all the fields fill with data it also does not load the page or save the data
I am working on a simple CRUD application using Codeigniter, and this section of code was working perfectly well until I added more functions.
Here is the problem:
I was adding 3 items to the database from user inputs, and it had no error. But when I added more input fields to get more inputs from the user, I ended up getting an Internal Server Error when I click on the "Add Item" button.
Below is the View Code:
<?php
if ($_SESSION[AppStrings::$NOMENCLATURE] != AppStrings::$SERVICE) {
if ($_SESSION[AppStrings::$SIZE] != AppStrings::$MICRO) {
?>
<form data-toggle="validator" class="form-horizontal form-material" method="post" action="#" onsubmit="addProduct(); return false;">
<div class="form-group m-t-40">
<div class="col-xs-12">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-barcode-scan"></i></div>
<input class="form-control" type="text" required="" placeholder=" <?= $nomenclature ?> Code" id="product_code" required/>
</div>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<input class="form-control" type="text" required="" placeholder="<?= $nomenclature ?> Name" id="product_name" required/>
</div>
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-currency-ngn"></i></div>
<input class="form-control" type="number" required="" placeholder=" <?= $nomenclature ?> Cost Price" name="product_cp" id="product_cp" required/>
</div>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-currency-ngn"></i></div>
<input class="form-control" type="number" required="" placeholder=" <?= $nomenclature ?> Selling Price" name="product_sp" id="product_sp" required/>
</div>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<textarea class="form-control" type="text" required="" placeholder=" <?= $nomenclature ?> Description" id="product_des" required/></textarea>
</div>
<div class="col-md-6">
<input class="form-control" type="text" required="" placeholder=" <?= $nomenclature ?> Expiry Date" id="product_exp" onfocus="(this.type = 'date')" onblur="if (this.value == '') {
this.type = 'text'
}" required/>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-clipboard-account"></i></div>
<select name="supplier" class="form-control form-control-line" type="text" id="supplier" placeholder="<?= $nomenclature ?> Supplier">
<option value="">Supplier</option>
<?php
foreach ($suppliers as $supplier) {
?>
<option value='<?= $supplier[DbStrings::$SUPPLIER_NAME] ?>'><?= $supplier[DbStrings::$SUPPLIER_NAME] ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-chevron-double-up"></i></div>
<select name="department" class="form-control form-control-line" type="text" id="department" placeholder="<?= $nomenclature ?> Department">
<option value="">Department</option>
<?php
foreach ($departments as $department) {
?>
<option value='<?= $department[DbStrings::$DEPARTMENT_NAME] ?>'><?= $department[DbStrings::$DEPARTMENT_NAME] ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-chevron-up"></i></div>
<select name="sub_departments" class="form-control form-control-line" type="text" id="sub_department" placeholder="<?= $nomenclature ?> Department">
<option value="">Sub-Department</option>
<?php
foreach ($sub_departments as $sub_department) {
?>
<option value='<?= $sub_department[DbStrings::$SUB_DEPARTMENT_NAME] ?>'><?= $sub_department[DbStrings::$SUB_DEPARTMENT_NAME] ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-cash"></i></div>
<input class="form-control" type="number" placeholder=" <?= $nomenclature ?> Vat" id="vat"/>
</div>
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12">
<button class="btn btn-primary btn-login btn-lg btn-block text-uppercase waves-effect waves-light" type="submit" name="product-btn">Add <?= $nomenclature ?></button>
</div>
</div>
</div> <!-- added in the edit -->
</div> <!-- added in the edit -->
</form>
<?php
}
}
?>
Here is the AJAX code:
function addProduct() {
var product_code = $("#product_code").val();
var product_name = $("#product_name").val();
var product_cp = $("#product_cp").val();
var product_sp = $("#product_sp").val();
var product_des = $("#product_des").val();
var product_exp = $("#product_exp").val();
var supplier = $("#supplier").val();
var department = $("#department").val();
var sub_department = $("#sub_department").val();
var vat = $("#vat").val();
var addUrl = "home/addproduct";
addUrl += "/" + product_code;
addUrl += "/" + product_name;
addUrl += "/" + product_cp;
addUrl += "/" + product_sp;
addUrl += "/" + product_des;
addUrl += "/" + product_exp;
addUrl += "/" + supplier;
addUrl += "/" + department;
addUrl += "/" + sub_department;
addUrl += "/" + vat;
$.ajax({type: 'GET', url: addUrl, data: {},
success: function (result) {
$.alert({
content: result
});
$("#product_code").val("");
$("#product_name").val("");
$("#product_cp").val("");
$("#product_sp").val("");
$("#product_des").val("");
$("#product_exp").val("");
$("#supplier").val("");
$("#department").val("");
$("#sub_department").val("");
$("#vat").val("");
location.reload();
},
error: function (xhr, status, error) {
$.alert({
content: 'Could not complete the process. ' + error
});
}
});
}
Here is the Controller Function:
private function addproduct($product_code = null, $product_name = null, $product_cp = null, $product_sp = null, $product_des = null, $product_exp = null, $supplier = null, $department = null, $sub_department = null, $vat = null) {
if (isset($product_code, $product_name, $product_cp, $product_sp, $product_des, $product_exp, $supplier, $department, $sub_department, $vat)) {
$email = $_SESSION[DbStrings::$EMAIL];
$product_code = $this->test_input($product_code);
$product_name = $this->test_input($product_name);
$product_cp = $this->test_input($product_cp);
$product_sp = $this->test_input($product_sp);
$product_des = $this->test_input($product_des);
$supplier = $this->test_input($supplier);
$department = $this->test_input($department);
$sub_department = $this->test_input($sub_department);
$vat = $this->test_input($vat);
$product_exp = strtotime($product_exp);
$insertedProduct = $this->member->insertProduct($email, $product_code, $product_name, $product_cp, $product_sp, $product_des, $supplier, $department, $sub_department, $vat, $product_exp);
if ($insertedProduct) {
echo "Your " . $_SESSION[AppStrings::$NOMENCLATURE] . " has been added succesfully";
} else {
echo "There was a problem inserting your " . $_SESSION[AppStrings::$NOMENCLATURE] . ". Please try again.";
}
} else {
echo 'Please fill all fields';
}
}
And this is the Model that does the insertion before sending back a result:
public function insertProduct($email, $product_code, $product_name, $product_cp, $product_sp, $product_des, $supplier, $department, $sub_department, $vat, $product_exp) {
$data = array(
DbStrings::$PRODUCTID => "",
DbStrings::$EMAIL => $email,
DbStrings::$PRODUCT_CODE => $product_code,
DbStrings::$PRODUCT_NAME => $product_name,
DbStrings::$PRODUCT_COST => $product_cp,
DbStrings::$PRODUCT_SELLING => $product_sp,
DbStrings::$PRODUCT_MARKUP => 9,
DbStrings::$PRODUCT_DESCRIPTION => $product_des,
DbStrings::$SUPPLIER => $supplier,
DbStrings::$DEPARTMENT => $department,
DbStrings::$SUB_DEPARTMENT => $sub_department,
DbStrings::$VAT => $vat,
DbStrings::$STOCK_BALANCE => 1,
DbStrings::$MIN_LEVEL => 1,
DbStrings::$MAX_QUANTITY => 1,
DbStrings::$QUANTITY_SOLD => 1,
DbStrings::$EXPIRY_DATE => $product_exp,
DbStrings::$DATE_CREATED => time(),
DbStrings::$DATE_STOCKED => time()
);
return $this->db->insert(DbStrings::$PRODUCTS_TABLE_NAME, $data);
}
I still get an error from the server, and don't know what else to do.
Correcting the above issue, the code works fine. I used: $this->output->enable_profiler(TRUE); and i was able to see the MySQL query sent by the model to the server, and when i copied the query and pasted it in my localhost:phpmyadmin, i got flagged for errors and there seem to be no syntax error.
Now this is creeping me out, as i can't fix it.
I want to update my table using bootstrap dialog , but I when I retrieve my datatable from server side and embed php code into my modal to show the table data into the modal, and choose what the user wants to update in that form. it is showing the data from every row of my table into the modal , how can I fix it?
form_modal
<form id="product_update">
<div class="row">
<div class="form-group">
<?php foreach ($product as $value): ?>
<div class="col-xs-12">
<label for="description">Name: </label>
<input type="text" class="form-control" id="description" name="description" title="product description" value="<?php echo $value['descripcion']; ?>" required>
<div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-8 col-sm-6">
<label for="cost_price">Cost Price:</label>
<div class="input-group"> <span class="input-group-addon">$</span>
<input type="text" class="form-control input-group-lg reg_name" id="cost_price" name="cost_price" title="cost_price" placeholder="Last name" value="<?php echo $value['precio_compra']; ?>" required>
</div>
</div>
<div class="col-xs-8 col-sm-6">
<label for="selling_price">Selling price: </label>
<input type="text" class="form-control input-group-lg reg_name" id="selling_price" name="selling_price" title="selling_price" placeholder="Last name" value="<?php echo $value['precio_venta']; ?>" required>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-8 col-sm-6">
<label for="wprice">Wholeprice: </label>
<input type="text" class="form-control" id="wprice" name="wprice" title="wprice" value="<?php echo $value['precio_mayoreo']; ?>" required>
</div>
<div class="col-xs-8 col-sm-6">
<label for="min_stock">Min stock: </label>
<input type="text" class="form-control" id="min_stock" name="min_stock" title="min_stock" value="<?php echo $value['existencia_minima']; ?>" required>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-8 col-sm-6">
<label for="stock">Stock: </label>
<input type="text" class="form-control" id="stock" name="stock" title="stock" value="<?php echo $value['existencia']; ?>" required>
</div>
<div class="col-xs-8 col-sm-6">
<label for="max_stock">Max stock: </label>
<input type="text" class="form-control" id="max_stock" name="max_stock" title="max_stock" value="<?php echo $value['existencia_maxima']; ?>" required>
</div>
</div>
</div>
<?php endforeach ?>
<div class="row">
<div class="form-group">
<div class="col-xs-8 col-sm-6">
<label for="provider">Provider: </label>
<select name="select-provider" id="select-provider">
<option value="0">Select a provider</option>
<?php foreach ($data as $value): ?>
<option value="<?php echo $value['id']; ?>"><?php echo $value['first_name'].' '.$value['last_name'] ?></option>
<?php endforeach ?>
</select>
</div>
</div>
</div>
</form>
modal js
$('#example tbody').on('click', 'a', function(event) {
event.preventDefault();
var data = table.row($(this).parents('tr')).data();
hash = data[0];
$("#product_update").validate();
BootstrapDialog.show({
type: BootstrapDialog.TYPE_WARNING,
message: function(dialog) {
var $message = $('<div></div>');
var pageToLoad = dialog.getData('pageToLoad');
$message.load(pageToLoad);
return $message;
},
data: {
'pageToLoad': URL_GET_VIEW_PRODUCT_UPDATE
},
closable: false,
buttons: [{
id: 'btn-ok',
cssClass: 'btn-primary',
icon: 'glyphicon glyphicon-send',
label: ' Save',
action: function(e) {
var description = $('#description').val();
var description = $('#description').val();
var cost_price = $('#cost_price').val();
var selling_price = $('#selling_price').val();
var wprice = $('#wprice').val();
var min_stock = $('#min_stock').val();
var stock = $('#stock').val();
var max_stock = $('#max_stock').val();
var provider_id = $('#select_provider').val();
if ($("#product_update").valid()) {
$.ajax({
url: URL_GET_UPDATE_PRODUCT,
type: 'POST',
data: { hash: hash, provider_id: provider_id, description: description, cost_price: cost_price, selling_price: selling_price, wprice: wprice, min_stock: min_stock, stock: stock, max_stock: max_stock },
success: function(data) {
console.log(data);
if (data.msg == 'successfully updated') {
$('#product_update')[0].reset();
table.ajax.reload();
} else if (data.min_stock == 'el stock no puede ser mayor al min') {
BootstrapDialog.show({
type: BootstrapDialog.TYPE_DANGER,
message: 'el stock no puede ser mayor al min'
});
}
}
});
}
}
},{
id: 'btn-cancel',
cssClass: 'btn-danger',
icon: 'glyphicon glyphicon-remove',
label: ' Cancel',
action: function(e) {
e.close();
}
}]
});
});
model product
public function datatable(){
$this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status');
$this->db->from('storelte_articulos');
$query = $this->db->get();
return $query->result_array();
}
public function isExistsProduct($data){
$this->db->select('descripcion');
$this->db->from('storelte_articulos');
$this->db->where('descripcion',$data['descripcion']);
$query = $this->db->get();
return $query->num_rows() == 0 ? false : true;
}
public function addProduct($data){
$query = 'UPDATE storelte_articulos SET hash_id = MD5(id) WHERE id = LAST_INSERT_ID()';
$this->db->insert('storelte_articulos',$data);
$this->db->query($query);
}
public function updateProduct($data) {
$this->db->where('md5(id)',$this->input->post('hash'));
$this->db->update('storelte_articulos',$data);
}
public function get_product() {
$this->db->select('codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia_maxima,existencia');
$this->db->from('storelte_articulos');
$this->db->where('md5(id)', $this->input->post('hash'));
$query = $this->db->get();
return $query->result_array();
}
modal img
I suspect your query is not targeting the single row that you intend to access.
If you are not querying on your table Primary/Unique Key, you should add LIMIT 1 --but really you should be using the PK.
Also, you seem to be looping through all of the results from the query.
You'll need to post more of your code, because I can only make assumptions from what you've provided.
Why are you putting the Warning element at the top?
Where did you copy/paste your scripts from?
public function datatable(){
$this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status');
You will need some sort of $this->db->where() statement here that references the appropriate row id.
like: $this->db->where('id',$this->input->post('id'));
$this->db->from('storelte_articulos');
$query = $this->db->get();
return $query->result_array();
}
$this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status');
You should add WHERE clause here. Basically you are selecting all rows if you don't add any kind of filtering in that clause. For example:
$this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status' WHERE hash_id='YOURHASHID')
I like to upload image using codeigniter Framework in PHP with JQuery AJAX without redirecting the page. When i upload the image it redirecting to controller area and the values are not insert to database , ajax response also not coming ,
can any one pls solve my issue.... Thanks in advance...
This is my view area.
<form action="<?php echo site_url("Admin_Creator/do_upload")?>" enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="frm_imageuupload" method="post">
<div class="form-group">
<label for="menu">Select Menu</label>
<select class="form-control" id="selectmenuid">
<option value="">-- Select Menu --</option>
<?php foreach($showData as $show):?>
<option value="<?php echo $show->menu_id?>"><?php echo $show->menu_name?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="menu">Select Sub Menu</label>
<select class="form-control" id="selectsubmenu">
<option>--Select Sub Menu--</option>
</select>
</div>
<div class="form-group">
<label for="imagetitle">Image Title</label>
<input type="text" class="form-control" name="imagetitle" id="imagetitle" placeholder="Enter Image Title" required="required">
</div>
<div class="control-group form-group">
<div class="controls">
<label>Upload Photo:</label>
<input name="file" type="file" id="image_file" required>
<p class="help-block"></p>
</div>
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
This is my Ajax coding
$('#submit').on('click',function(){
var inputFile=$('input[name=file]');
var fileToUpload=inputFile[0].files[0];
var other_data = $('#frm_imageuupload').serializeArray();
var formdata=new FormData();
formdata.append(fileToUpload);
formdata.append(other_data);
//now upload the file using ajax
$.ajax({
url:"<?php echo base_url('Admin_Creator/do_upload') ?>",
type:"post",
data:formdata,
processData:false,
contentType:false,
success: function(data){
if (data== 'true'){
window.location.reload();
}
else{
alert("Pls Try Again");
}
}
});
This is my controller Coding...
public function do_upload(){
$config['upload_path']="./upload";
$config['allowed_types']='gif|jpg|png';
$this->load->library('upload',$config);
if($this->upload->do_upload()){
$data = array('upload_data' => $this->upload->data());
$data1 = array(
'menu_id' => $this->input->post('selectmenuid'),
'submenu_id' => $this->input->post('selectsubmenu'),
'imagetitle' => $this->input->post('imagetitle'),
'imgpath' => $data['upload_data']['file_name']
);
$result= $this->Admin_model->save_imagepath($data1);
if ($result == TRUE) {
echo "true";
}
}
}
This is my model coding
public function save_imagepath($data1)
{
$this->db->insert('images', $data1);
return $this->db->insert_id();
}
Try This. It's working-
HTML Form-
<form enctype="multipart/form-data" id="submit">
<div class="form-group">
<label for="menu">Select Menu</label>
<select class="form-control" name="selectmenuid" id="selectmenuid">
<option value="">-- Select Menu --</option>
<?php foreach($showData as $show):?>
<option value="<?php echo $show->menu_id?>"><?php echo $show->menu_name?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="menu">Select Sub Menu</label>
<select class="form-control" name="selectsubmenu" id="selectsubmenu">
<option>--Select Sub Menu--</option>
</select>
</div>
<div class="form-group">
<label for="imagetitle">Image Title</label>
<input type="text" class="form-control" name="imagetitle" id="imagetitle" placeholder="Enter Image Title" required="required">
</div>
<div class="control-group form-group">
<div class="controls">
<label>Upload Photo:</label>
<input name="file" type="file" id="image_file" required>
<p class="help-block"></p>
</div>
</div>
<button type="submit" class="btn btn-primary" id="sub">Submit</button>
</form>
Ajax -
$('#submit').submit(function(e){
e.preventDefault();
$.ajax({
url:'Your path',
type:"post",
data:new FormData(this),
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
alert(data);
}
});
});
Just set url in ajax, It would work perfectly.
Controller function-
public function do_upload(){
$config['upload_path']="./upload";
$config['allowed_types']='gif|jpg|png';
$this->load->library('upload',$config);
if($this->upload->do_upload("file")){
$data = array('upload_data' => $this->upload->data());
$data1 = array(
'menu_id' => $this->input->post('selectmenuid'),
'submenu_id' => $this->input->post('selectsubmenu'),
'imagetitle' => $this->input->post('imagetitle'),
'imgpath' => $data['upload_data']['file_name']
);
$result= $this->Admin_model->save_imagepath($data1);
if ($result == TRUE) {
echo "true";
}
}
}
this is simple.
problem is the ajax
you should stop the form submit first
$('form').on('submit',function(e){//bind event on form submit.
e.preventDefault();//stop submit
......... //your other codes
This what i did to solve that problem
HTML
<div class="form-group">
<label for="logo">Service Provider Logo / Icon</label>
<input type="file" class="form-control" name="file" id="file" required="required">
<img src="#" id="img-logo" alt="image" class="img-responsive" style="height: 200px !important;">
<input type="hidden" class="" id="returned-sp-id">
</div>
<div class="form-group">
<label for="caption">Service Provider Name</label>
<input type="text" class="form-control" id="caption" required="required">
</div>
<div class="form-group">
<label for="details">Service Provider Details</label>
<textarea type="text" class="form-control" id="details" required="required"></textarea>
</div>
</form>
Jquery Ajax
$(function() {
$('#service-provider-details').on('submit', function(e){
var caption = $('#caption').val();
var details = $('#details').val();
var data = new FormData(this);
data.append('caption', caption);
data.append('details', details);
$.ajax({
url:'<?= base_url(), 'create_profile_sp/upload' ?>',
type:"post",
data: data,
processData:false,
contentType:false,
cache:false,
async:true,
success: function(data){
console.log(data);
}
});
e.preventDefault();
});
});
The controller
class Create_profile_sp extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('profile_sp_m');
}
public function upload($data) {
$data = $_POST;
$this->profile_sp_m->upload_logo($data);
}
}
The model
class profile_sp_m extends CI_Model
{
public $_tablename = 'profiles';
function __construct()
{
// Call the Model constructor
parent::__construct();
}
public function upload_logo($data) {
$caption = $data['caption'];
$details = $data['details'];
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") ||($_FILES["file"]["type"] == "image/jpg") ||
($_FILES["file"]["type"] == "image/jpeg") ) &&
($_FILES["file"]["size"] < 100000) &&
in_array($file_extension, $validextensions)){
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
$sourcePath = $_FILES['file']['tmp_name']; Store source path in a variable
$targetPath = "uploads/profiles/" . $_FILES['file']['name']; // The Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath); // Moving Uploaded file
// The Image Data
$imageData = [
'caption' => $caption,
'description' => $details,
];
// Insert the data
$this->db->insert($this->_tablename, $imageData);
}
}
}
}
}