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')
Related
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
I have a basic web application that has been coded in php.
The app carries out CRUD operations by making use of an API made through PHP. When I try to use my update.php API endpoint, I get a successful response but no changes reflect in db.
Project Structure
Project_Structure
update.php in api/mailbox
<?php
// include database and object files
include_once '../config/database.php';
include_once '../objects/mailbox.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare mailbox object
$mailbox = new Mailbox($db);
//For diagnostics
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data[""];
// set ID property of product to be edited
$mailbox_id->mailbox_id = $data->mailbox_id;
// set mailbox property values
$mailbox->username = $_POST['username'];
$mailbox->password = base64_encode($_POST['password']);
$mailbox->name = $_POST['name'];
$mailbox->quota = $_POST['quota'];
$mailbox->modified = date('Y-m-d H:i:s');
$mailbox->active = $_POST['active'];
$mailbox->mailbox_id = $_POST['mailbox_id'];
// create the mailbox
if($mailbox->update()){
$mailbox_arr=array(
"status" => true,
"message" => "Successfully Updated Mailbox"
);
}
else{
$mailbox_arr=array(
"status" => false,
"message" => "Mailbox already exists!"
);
}
print_r(json_encode($mailbox_arr));
?>
mailbox.php(in objects folder)
// update mailbox
function update(){
$query = "UPDATE
". $this->table_name ."
SET
username='".$this->username."', password='".$this->password."', name='".$this->name."', quota='".$this->quota."', modified='".$this->modified."', active='".$this->active."'
WHERE
mailbox_id= '".$this->mailbox_id."'";
// prepare query
$stmt = $this->conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
update.php (The rendered page, on clicking update, the error is: **Mailbox already exists)**
<?php
$content = '<div class="container"
<div class="row">
<!-- left column -->
<div class="col-md-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Update Mailbox</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form">
<div class="box-body">
<div class="form-group">
<div class="form-group">
<label for="exampleMBID1">Mailbox ID</label>
<input type="text" class="form-control" id="mailbox_id" placeholder="Mailbox ID" disabled>
</div>
<label for="exampleInputUserName1">User Name</label>
<input type="text" class="form-control" id="username" placeholder="Enter Username e.g jsmith">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="password" placeholder="Enter Password">
</div>
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name of User">
</div>
<div class="form-group">
<label for="exampleInputMaildir1">Maildir</label>
<input type="text" class="form-control" id="maildir" placeholder="Enter Maildir" disabled>
</div>
<div class="form-group">
<label for="exampleInputQuota1">Quota (0=Unlimited)</label>
<input type="text" class="form-control" id="quota" placeholder="Enter Quota">
</div>
<div class="form-group">
<label for="examplelocalpart1">Local Part</label>
<input type="text" class="form-control" id="local_part" placeholder="localpart" disabled>
</div>
<div class="form-group">
<label for="exampledomain1">Domain</label>
<input type="text" class="form-control" id="domain" placeholder="domain" disabled>
</div>
<div class="form-group">
<label for="examplecreated1">Created</label>
<input type="text" class="form-control" id="created" placeholder="Created" disabled>
</div>
<div class="form-group">
<label for="examplemodified1">Modified</label>
<input type="text" class="form-control" id="modified" placeholder="Modified">
</div>
<div class="form-group">
<label for="exampleactive1">Active (0=Not Active, 1=Active)</label>
<input type="text" class="form-control" id="active" placeholder="Enter 0 or 1">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<input type="button" class="btn btn-primary" onClick="UpdateMailbox()" value="Update"></input>
</div>
</form>
</div>
<!-- /.box -->
</div>
</div>
</div>';
include('../master.php');
?>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "../api/mailbox/read_single.php?mailbox_id=<?php echo $_GET['mailbox_id']; ?>",
dataType: 'json',
success: function(data) {
$('#username').val(data['username']);
$('#password').val(data['password']);
$('#name').val(data['name']);
$('#maildir').val(data['maildir']);
$('#quota').val(data['quota']);
$('#local_part').val(data['local_part']);
$('#domain').val(data['domain']);
$('#created').val(data['created']);
$('#modified').val(data['modified']);
$('#active').val(data['active']);
$('#mailbox_id').val(data['mailbox_id']);
},
error: function (result) {
console.log(result);
},
});
});
function UpdateMailbox(){
$.ajax(
{
type: "POST",
url: '../api/mailbox/update.php',
dataType: 'json',
data: {
mailbox_id: <?php echo $_GET['mailbox_id']; ?>,
username: $("#username").val(),
password: $("#password").val(),
name: $("#name").val(),
maildir: $("#maildir").val(),
quota: $("#quota").val(),
domain: $("#domain").val(),
modified: $("#modified").val(),
active: $("#active").val()
},
error: function (result) {
alert(result.responseText);
},
success: function (result) {
if (result['status'] == true) {
alert("Successfully Updated Mailbox!");
window.location.href = '/MailEasy/mailbox/listAll.php';
}
else {
alert(result['message']);
}
}
});
}
</script>
1) Why is not updating when using web UI?
2) When using postman, it shows successful, why are requests not reaching the database?
Postman --> Successful response but no changes in db.
Php webpage --> Mailbox already exists.
Thank you
I can`t find a solution for this formular, so i am asking you guys how i can solve this: (1)I have this formular:
<form id="formRetur" action="" method="POST" novalidate="novalidate">
<div id="mail-status" style="color: black;text-align: center;"></div>
<h3><strong>
Detalii client
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nume_prenume" id="nume_prenume" placeholder="Nume Prenume">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_tlf" id="nr_tlf" placeholder="Numar telefon">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="adresa_email" id="adresa_email" placeholder="Adresa email">
</div>
</div>
</div>
<h3><strong>
Detalii comanda
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_comanda" id="nr_comanda" placeholder="Numar comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="data_comanda" id="data_comanda" placeholder="Data comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_factura" id="nr_factura" placeholder="Numar factura">
</div>
</div>
</div>
<h3><strong>
Detalii produse
</strong></h3>
<div class="row">
<i class="fa fa-plus" aria-hidden="true" style="position: absolute;z-index:999;"></i>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="den_prod" id="den_prod" placeholder="Denumire produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="culoare_prod" id="culoare_prod" placeholder="Culoare produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="cantitate" id="cantitate" placeholder="Cantitate">
</div>
</div>
</div>
<div class="maimulte">
</div>
<h3><strong>
Motiv retur
</strong></h3>
<div class="row">
<div class="col-md-12">
<textarea name="motiv" id="motiv" class="form-control" cols="30" rows="10"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-12" style="margin-top:10px;margin-bottom:10px;"><div class="g-recaptcha" data-sitekey="<?php echo SITE_KEY; ?>"></div> </div>
<div class="col-md-12">
<button type="submit" id="send-message" class="btn btn-default">Trimite </button>
</div>
<div id="loader-icon" style="display:none;"><img src="images/loader.gif"></div>
</div>
</form>
I use ajax to insert data in DB, but i have an option where you can add more products when user press + adding +1 row with 3 fields name,color, qty and i want to insert also these in db, here is my ajax:
<script>
$(document).ready(function (e){
$("#formRetur").on('submit',(function(e){
e.preventDefault();
$("#mail-status").hide();
$('#send-message').hide();
$('#loader-icon').show();
$.ajax({
url: "valid_retur.php",
type: "POST",
dataType:'json',
data: {
"nume_prenume":$('input[name="nume_prenume"]').val(),
"nr_tlf":$('input[name="nr_tlf"]').val(),
"adresa_email":$('input[name="adresa_email"]').val(),
"nr_comanda":$('input[name="nr_comanda"]').val(),
"data_comanda":$('input[name="data_comanda"]').val(),
"nr_factura":$('input[name="nr_factura"]').val(),
"den_prod":$('input[name="den_prod"]').val(),
"culoare_prod":$('input[name="culoare_prod"]').val(),
"cantitate":$('input[name="cantitate"]').val(),
"motiv":$('textarea[name="motiv"]').val(),
"g-recaptcha-response":$('textarea[id="g-recaptcha-response"]').val()},
success: function(response){
// $( '#frmContact' ).each(function(){
// this.reset();
// });
$("#mail-status").show();
$('#loader-icon').hide();
if(response.type == "error") {
$('#send-message').show();
$("#mail-status").attr("class","alert alert-danger");
} else if(response.type == "message"){
// grecaptcha.reset();
$('#send-message').show();
$("#mail-status").attr("class","alert alert-success");
}
$("#mail-status").html(response.text);
},
error: function(){}
});
}));
});
</script>
Here is my db:enter image description here
And there is my php file who insert in db with values from ajax:
<?php
if($_POST)
{
include('config.php');
$nume_prenume = filter_var($_POST["nume_prenume"], FILTER_SANITIZE_STRING);
$nr_tlf = filter_var($_POST["nr_tlf"], FILTER_SANITIZE_STRING);
$adresa_email = filter_var($_POST["adresa_email"], FILTER_SANITIZE_STRING);
$nr_comanda = filter_var($_POST["nr_comanda"], FILTER_SANITIZE_STRING);
$data_comanda = filter_var($_POST["data_comanda"], FILTER_SANITIZE_STRING);
$nr_factura = filter_var($_POST["nr_factura"], FILTER_SANITIZE_STRING);
$den_prod = filter_var($_POST["den_prod"], FILTER_SANITIZE_STRING);
$culoare_prod = filter_var($_POST["culoare_prod"], FILTER_SANITIZE_STRING);
$cantitate = filter_var($_POST["cantitate"], FILTER_SANITIZE_STRING);
$motiv = filter_var($_POST["motiv"], FILTER_SANITIZE_STRING);
if(empty($nume_prenume)) {
$empty[] = "<b>nume_prenume</b>";
}
if(empty($nr_tlf)) {
$empty[] = "<b>nr_tlf</b>";
}
if(empty($adresa_email)) {
$empty[] = "<b>adresa_email</b>";
}
if(empty($nr_comanda)) {
$empty[] = "<b>nr_comanda</b>";
}
if(empty($data_comanda)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($den_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($culoare_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(!empty($empty)) {
$output = json_encode(array('type'=>'error', 'text' => implode(", ",$empty) . ' obligatoriu!'));
die($output);
}
// if(!filter_var($email2, FILTER_VALIDATE_EMAIL)){ //email validation
// $output = json_encode(array('type'=>'error', 'text' => '<b>'.$email2.'</b> is an invalid Email, please correct it.'));
// die($output);
// }
//reCAPTCHA validation
if (isset($_POST['g-recaptcha-response'])) {
require('component/recaptcha/src/autoload.php');
$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$output = json_encode(array('type'=>'error', 'text' => '<b>Captcha</b> Validation Required!'));
die($output);
}
}
// bag in db
$sql0 = "INSERT INTO retur (nume_prenume, nr_tlf, email, nr_comanda, data_comanda, nr_factura, den_prod, culoare_prod, cantitate_prod, motiv_retur)
VALUES ('$nume_prenume', '$nr_tlf', '$adresa_email', '$nr_comanda', '$data_comanda', '$nr_factura', '$den_prod', '$culoare_prod', '$cantitate', '$motiv')";
mysqli_query($conn, $sql0);
}
So basically this is a formular for returns products and if he have more products to return i added that jquery to add more fields and i want to be inserted in databased then i will fetch data and display it in my CMS.
1.You don't have to write that much code in ajax. You can easily use serialize():
Reduce you ajax code with below code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#your_form_id");
$("#Your_submit_id").click(function(){
$.ajax({
type:"POST",
url:"URL",
data:form.serialize(),
success: function(response){
console.log(response);
}
});
});
});
</script>
2.To add multiple product:
-You have to create every input field as array for product info like:
<input type="text" name="prod_name[]">
This array statement store you every product info index wise. If you
used normal variable then it will post only you last product
details.
In Php code you have to take the count of posted
product title & use for loop to get the every product information.
for($i=0;$i<count($prod_name);$i++)
{
//Insert/fetch All Values like : $prod_name[$i]
}
-When you click on add, just create clone of the prev available div.
I have created one IMS System. In that i have to create bill on order page and in order page when i select customer name from drop down than customer_address,customer_phone and gst number should automatically fill in text box.In database i have created one table named partys in that all data are available(Customer_name,Customer_address,customer_phone and gst) If anybody knows solution than please help.
Below is my code
<?php
$dbc = mysqli_connect('localhost', 'root', '', 'stock')
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM partys";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['party_name'] ?>"><?php echo $row['party_name'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Address</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="customer_address" name="customer_address" placeholder="Enter Customer Address" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Phone</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="customer_phone" name="customer_phone" placeholder="Enter Customer Phone" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="gstin" class="col-sm-5 control-label" style="text-align:left;">GSTIN</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="gstin" name="gstin" placeholder="Enter GST Number" autocomplete="off">
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// On change of the dropdown do the ajax
$("#client").change(function() {
$.ajax({
// Change the link to the file you are using
url: '/create.php',
type: 'post',
// This just sends the value of the dropdown
data: {customer_name : party_name},
dataType: 'json',
success: function(response) {
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var Vals = JSON.parse(response);
// These are the inputs that will populate
$("#customer_address").val(response.customer_address);
$("#customer_phone").val(response.customer_phone);
$("#gstin").val(response.gstin);
}
});
});
});
</script>
I have two pages add_admin.php and ajax_admin.php when i select name in dropdown it display FIRSTNAME, MIDDLENAME and LASTNAME in TEXTBOXES.
HERE is My Code:
add_admin.php
<!-- Department -->
<div class="col-xs-12 col-sm-12 col-md-12" >
<div class="form-group">
<select id="faculty_name" name="faculty_name" class="form-control" onchange='fetch_select(this.value)' required>
<option selected="selected" disabled="disabled">Please Select Faculty</option>
<?php
$query = mysql_query("select * from faculty_details");
while($row = mysql_fetch_array($query))
{
?>
<option value="<?php echo $row['FACULTY_ID'];?>"><?php echo $row['FIRSTNAME']." ".$row['MIDDLENAME']." ".$row['LASTNAME'];?></option>
<?php
}
?>
</select>
</div>
</div>
<!-- First Name -->
<div class="col-xs-12 col-sm-4 col-md-4">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-fw fa-user"></i></div>
<input type="text" id="fname" name="fname" class="form-control input-md" placeholder="First Name" value="">
</div>
</div>
</div>
other text box are there contaisn middlename, lastname
Ajax Code
function fetch_select(val)
{
$.ajax
({
type: 'post',
url: 'ajax_admin.php',
data:
{
get_option:val
},
success: function (response)
{
$('#fname').val(response);
}
});
ajax_admin.php
<?php
if(isset($_POST['get_option']))
{
$state = $_POST['get_option'];
$find=mysql_query("select * from faculty_details where FACULTY_ID=$state");
while($row=mysql_fetch_array($find))
{
echo "$row[FIRSTNAME]";
}
}
?>
Get the result as json from the server so that you can easily use it in jQuery:
ajax-admin.php
if(isset($_POST['get_option']))
{
$state = $_POST['get_option'];
$row1=array();
$find=mysql_query("select firstname,middlename,lastname from faculty_details where FACULTY_ID=$state");
while($row=mysql_fetch_array($find))
{
$row1[]=$row;
}
die(json_encode($row1));
}
Ajax Code
function fetch_val(val) {
$.ajax({
url:"ajax-admin.php",
type:"POST",
data:{"get_option":val},
dataType:"JSON",
success:function(data){
$('#fname').val((data[0].firstname));
$('#mname').val((data[0].middlename));
$('#lname').val((data[0].lastname));
}
});
}