Upload photo alongside other form content in vue.js - javascript

I have a form that contains number of fields and i'm sending their content to the Database and all things goes smoothly.
Now i want to add another field to upload image/file and send it with the rest of the form fields but i'm confused on how it can be done.
I created a column in my table and i want to know what should i add in both my php file and my vue file.
the vue.js File:
<template>
<div class="book-table">
<h1 class="text-light text-center bg-dark py-3">CRUD operations using VUE.JS</h1>
<div class="container-fluid">
<div class="d-flex justify-content-between">
<h2 class="text-info">Books</h2>
<button class="btn btn-info" #click="showAddModal=true">
<i class="fas fa-user mr-2"></i>
<span>add book</span>
</button>
</div>
<hr class="bg-info">
<div class="alert alert-success" v-if="successMsg">
<span>{{ successMsg }}</span>
</div>
<div class="alert alert-danger" v-if="errorMsg">
<span>{{ errorMsg }}</span>
</div>
<div class="row">
<div class="col-lg-12">
<div class="table-responsive">
<table class="table table-bordered table-striped d-table ">
<thead>
<tr class="text-center text-light text-info bg-primary">
<th class="d-table-cell">ID</th>
<th>Cover</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr v-for="book in books" :key="book.id" class="text-center">
<td> {{ book.id }} </td>
<td>
<img :src="Cover">
</td>
<td> {{ book.Title }} </td>
<td> {{ book.Author }} </td>
<td> {{ book.Price}} </td>
<td>
<a href="#" class="text-success" #click="showEditModal=true; selectBook(book);">
<i class="fas fa-edit"></i>
</a>
</td>
<td>
<a href="#" class="text-danger" #click="showDeleteModal=true; selectBook(book);">
<i class="fas fa-trash"></i>
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- ADD NEW BOOK -->
<div id="overlay" v-show="showAddModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add new book</h5>
<button type="button" class="close" #click="showAddModal=false">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body p-4">
<form method="post" action="#">
<div class="form-group">
<span>Title :</span>
<input type="text" name="title" class="form-control mt-2" placeholder="name" v-model="newBook.Title">
</div>
<div class="form-group">
<span>Author :</span>
<input type="text" name="author" class="form-control mt-2" placeholder="author" v-model="newBook.Author">
</div>
<div class="form-group">
<span>Price :</span>
<input type="text" name="price" class="form-control mt-2" placeholder="price" v-model="newBook.Price">
</div>
<div class="form-group">
<span>Cover :</span>
<input type="file" ref="file" class="form-control mt-2" placeholder="cover">
</div>
<button class="btn btn-info btn-block" #click.prevent="showAddModal=false; addBook();">ADD</button>
</form>
</div>
</div>
</div>
</div>
<!-- EDIT BOOK -->
<div id="overlay" v-show="showEditModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit book</h5>
<button type="button" class="close" #click="showEditModal=false">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body p-4">
<form method="post" action="#">
<div class="form-group">
<span>Title :</span>
<input type="text" name="title" class="form-control mt-2" v-model="currentBook.Title">
</div>
<div class="form-group">
<span>Author :</span>
<input type="text" name="author" class="form-control mt-2" v-model="currentBook.Author">
</div>
<div class="form-group">
<span>Price :</span>
<input type="text" name="price" class="form-control mt-2" v-model="currentBook.Price">
</div>
<div class="form-group">
<span>Cover :</span>
<input type="file" ref="file" class="form-control mt-2" placeholder="cover">
</div>
<div class="form-group">
<button class="btn btn-info btn-block" #click.prevent="showEditModal=false; editBook();">EDIT</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- DELETE BOOK -->
<div id="overlay" v-show="showDeleteModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Delete book</h5>
<button type="button" class="close" #click="showDeleteModal=false">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body p-4">
<h4 class="text-danger">Are you sure you want to delete this book ?</h4>
<h6>You are deleting {{ currentBook.name }}</h6>
<hr class="bg-info">
<button class="btn btn-info btn-block" #click="showDeleteModal=false; deleteBook()">DELETE</button>
<button class="btn btn-danger btn-block" #click="showDeleteModal=false">CANCEL</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "Homepage",
data: function() {
return {
successMsg: false,
errorMsg: false,
showAddModal: false,
showEditModal: false,
showDeleteModal: false,
Cover: 'https://via.placeholder.com/150',
books: [],
newBook: { Title: "", Cover: "" , Author: "", Price: "" },
currentBook: {}
}
},
mounted: function() {
this.getAllBooks();
},
methods: {
getAllBooks() {
axios.get('http://localhost/VUEJS/src/Backend/api.php?action=read')
.then((res) => {
if (res.data.error) {
this.errorMsg = res.data.message;
} else {
this.books = res.data.books;
}
});
},
addBook() {
var formData = this.toFormData(this.newBook);
axios.post('http://localhost/VUEJS/src/Backend/api.php?action=create', formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then((res) => {
this.newBook = { Title: "", Cover: "", Author: "", Price: "" };
if (res.data.error) {
this.errorMsg = res.data.message;
} else {
this.successMsg = res.data.message;
this.getAllBooks();
}
});
},
editBook() {
var formData = this.toFormData(this.currentBook);
axios.post('http://localhost/VUEJS/src/Backend/api.php?action=update', formData)
.then((res) => {
this.currentBook = {};
if (res.data.error) {
this.errorMsg = res.data.message;
} else {
this.successMsg = res.data.message;
this.getAllBooks();
}
});
},
},
toFormData(obj) {
var fd = new FormData();
for (var i in obj) {
fd.append(i, obj[i]);
}
return fd;
},
selectBook(book) {
this.currentBook = book;
}
}
}
</script>
php file:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$server= "localhost";
$user= "root";
$password= "";
$dbname = "bookstore";
$port= "3308";
$conn = new mysqli($server,$user,$password,$dbname,$port);
if($conn->connect_error){
die("Connection Failed!, " .$conn->connect_error);
}
$result = array('error'=>false);
$action = '';
if(isset($_GET['action'])){
$action = $_GET['action'];
}
// FETCHING DATA FROM THE DB
if($action == "read"){
$sql = $conn->query("SELECT * FROM books");
$book = array();
while ($row = $sql->fetch_assoc()) {
array_push($book, $row);
}
$result['books'] = $book;
}
// ADDING DATA TO THE DB
if($action == "create"){
$Title = $_POST['Title'];
$Cover = $_POST['Cover'];
$Author = $_POST['Author'];
$Price = $_POST['Price'];
$sql = $conn->query("INSERT INTO books (Title,Cover,Author,Price) VALUES('$Title',$Cover,'$Author','$Price')");
if($sql){
$result['message'] = "Book was added successfully!";
}
else{
$result['error'] = true;
$result['message'] = "Cannot add book! Maybe it's already exist";
}
}
// UPDATING DATA
if($action == "update"){
$id = $_POST['id'];
$Title = $_POST['Title'];
$Cover = $_POST['Cover'];
$Author = $_POST['Author'];
$Price = $_POST['Price'];
$sql = $conn->query("UPDATE books SET Title='$Title',Cover='$Cover',Author='$Author',Price='$Price' WHERE id='$id'");
if($sql){
$result['message'] = "Book was updated successfully!";
}
else{
$result['error'] = true;
$result['message'] = "Cannot update the book info!";
}
}
// DELETING DATA
if($action == "delete"){
$id = $_POST['id'];
$sql = $conn->query("DELETE FROM books WHERE id='$id'");
if($sql){
$result['message'] = "Book was deleted successfully!";
}
else{
$result['error'] = true;
$result['message'] = "Cannot delete this book!";
}
}
echo json_encode($result);
$conn->close();
?>

See if this helps:
working example of image upload
https://picupload.netlify.app/
VueJS code repo https://github.com/manojkmishra/dw_take5
File- https://github.com/manojkmishra/dw_take5/blob/master/src/components/ImageUploader.vue
PHP[Laravel] part might not be useful for your code, it is behind firewall so will not work. Here is how api is getting processed
public function imagesupload(Request $request){
if (count($request->images)) {
foreach ($request->images as $image) {
$image->store('images');
}
}
return response()->json(["message" => "Done"]);
}

Related

Join Multiple tables : Edit and Update an Item from a table list to a modal in asp.net mvc

I'm new to ASP.NET MVC and I'm having trouble editing an item and showing it in a modal form and updating it in the database. The data is not showing in a modal. The data is coming from different tables in the database.
Expected output: show the list in a single view(table) and edit a selected item from the list (modal) and update it.
Here's my code:
AdminController:
public JsonResult EditItem(int? itemID)
{
var id = db.Items.Where(i => i.ItemID == itemID).FirstOrDefault();
List<Item> itemList = db.Items.ToList();
List<ItemDetail> itemDetailList = db.ItemDetails.ToList();
List<ProductType> productTypeList = db.ProductTypes.ToList();
var details = from itm in itemList
join itmDetail in itemDetailList on itm.ItemID equals itmDetail.ItemID into ItemInfo
from itmDetail in ItemInfo.DefaultIfEmpty()
join product in productTypeList on itmDetail.ProductID equals product.ProductID into ProductInfo
from product in ProductInfo.DefaultIfEmpty()
where itm.ItemID.Equals(id)
select new TableCollection { Item = itm, ItemDetail = itmDetail, ProductType = product };
return Json(details, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult EditItem(Item item, ItemDetail details)
{
ItemDetail itmDetails = db.ItemDetails.Where(d => d.ItemID == item.ItemID).FirstOrDefault();
itmDetails.ItemID = details.ItemID;
db.SaveChanges();
return RedirectToAction("Inventory", "Admin");
}
InventoryList View:
#model IEnumerable<VetClinic.Models.Admin.TableCollection>
#if (Model != null)
{
<table id="inventory" class="table table-striped table-hover">
<thead class="thead-dark">
<tr>
<th>Product Type</th>
<th>Item Name</th>
<th># of Stock</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody class="bg-light">
#foreach (var item in Model)
{
<tr id="row_#item.ItemDetail.ItemID">
<td>#item.ProductType.Name #item.ProductType.Type</td>
<td>#item.ItemDetail.ItemName</td>
<td>#item.ItemDetail.NumOfStock</td>
<td>#item.ItemDetail.Price</td>
<td>
<i class="fa fa-pencil" data-toggle="tooltip" title="Edit" style="color: blue;"></i>
</td>
</tr>
}
</tbody>
</table>
<div class="modal fade" id="EditItem" tabindex="-1" role="dialog" aria-labelledby="EditItem" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Item</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#using (Html.BeginForm("EditItem", "Admin", FormMethod.Post))
{
<input type="hidden" id="hiddenItemID" />
<div class="form-group row">
<div class="col-lg-3">
<label>Product Type:</label>
</div>
<div class="col-lg-4">
<input type="text" id="productType"/>
</div>
</div>
<div class="form-group row">
<div class="col-lg-2">
<label>Item Name:</label>
</div>
<div class="col-lg-3">
<input type="text" id="itemName" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-lg-5">
<label>Number of Stocks</label>
</div>
<div class="col-lg-2">
<input type="text" id="numOfStocks" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-lg-2">
<label>Price:</label>
</div>
<div class="col-lg-3">
<input type="text" id="price" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary">Update</button>
</div>
}
</div>
</div>
</div>
</div>
}
else
{
<i class="fa fa-info-circle"> </i>#ViewBag.EmptyList;
}
<script>
function EditItem(id) {
$.ajax({
url: "/Admin/EditItem/" + id,
type: "GET",
dataType: "json",
success: function (response) {
$("#hiddenItemID").val(response.ItemID);
$("#EditItem").modal("show");
}
});
return false;
}
</script>

My Forms in Modal are not resetting - JQuery

So, First i open Add Data Modal, and my form was empty.
Then i close it, and try to open Edit Data Modal.
Because this is a Edit Data, so my form filled with data from database.
But when i close the Edit Data and open Add Data again, my Add Data was filled with data from database, which is it's must be empty form.
Add Data and Edit data are using the same Modal, but different button.
So, There's my js.
$(document).ready(function() {
$('#datetimepicker1').datetimepicker({
icons: {
time: "fa fa-clock-o",
date: "fa fa-calendar",
up: "fa fa-arrow-up",
down: "fa fa-arrow-down"
},
format: 'DD-MM-YYYY HH:mm',
showTodayButton:true
});
$('#datetimepicker2').datetimepicker({
icons: {
time: "fa fa-clock-o",
date: "fa fa-calendar",
up: "fa fa-arrow-up",
down: "fa fa-arrow-down"
},
format: 'DD-MM-YYYY HH:mm',
showTodayButton:true
});
//Button Tambah
$('#btn_tambah').click(function(){
clearForm('#modal_add_new');
$('#frm').find('input:text, input:password, select, textarea').val('');
$('#frm').find("input[type='hidden']", $(this)).val('');
$('#frm').find('input:radio, input:checkbox').prop('checked', false);
$('#frm')[0].reset();
return false;
});
//DataTable
var myTable =
$('#promo-table')
.DataTable({
"bAutoWidth": false,
"aaSorting": [],
"bScrollCollapse": true,
"stateSave": true,
"aoColumnDefs": [
{
"aTargets":[4],
"fnCreatedCell": function(c1){
$(c1).css("text-align", "right");
},
render: $.fn.dataTable.render.number( ',', '.', 0 )
},
{ "bVisible": false, "aTargets": [ 8 ] }
],
"sAjaxSource": base_url+'admin/c_promo/get_json_data',
"bPaginate": true,
select: {
style: 'single'
}
});
myTable.on('order.dt search.dt', function () {
myTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
}).draw();
myTable.on('dblclick', 'tr', function (){
var data = myTable.row( this ).data();
//alert(data[3]);
var s = '1';
update(s,data[8]);
$('#modal_add_new').modal('show');
});
$.fn.dataTable.Buttons.defaults.dom.container.className = 'dt-buttons btn-overlap btn-group btn-overlap';
new $.fn.dataTable.Buttons( myTable, {
buttons: [
{
"extend": "colvis",
"text": "<i class='fa fa-search bigger-110 blue'></i> <span class='hidden'>Show/hide columns</span>",
"className": "btn btn-white btn-primary btn-bold",
columns: ':not(:first):not(:last)'
},
{
"extend": "copy",
"text": "<i class='fa fa-copy bigger-110 pink'></i> <span class='hidden'>Copy to clipboard</span>",
"className": "btn btn-white btn-primary btn-bold"
},
{
"extend": "csv",
"text": "<i class='fa fa-database bigger-110 orange'></i> <span class='hidden'>Export to CSV</span>",
"className": "btn btn-white btn-primary btn-bold"
},
{
"extend": "excel",
"text": "<i class='fa fa-file-excel-o bigger-110 green'></i> <span class='hidden'>Export to Excel</span>",
"className": "btn btn-white btn-primary btn-bold"
},
{
"extend": "pdf",
"text": "<i class='fa fa-file-pdf-o bigger-110 red'></i> <span class='hidden'>Export to PDF</span>",
"className": "btn btn-white btn-primary btn-bold"
},
{
"extend": "print",
"text": "<i class='fa fa-print bigger-110 grey'></i> <span class='hidden'>Print</span>",
"className": "btn btn-white btn-primary btn-bold",
autoPrint: false,
message: 'This print was produced using the Print button for DataTables'
} ,
{
"text": "<i class='fa fa-refresh'></i> <span class='hidden'>Refreh</span>",
"className": "btn btn-white btn-primary btn-bold",
action: function ( e, dt, node, config ) {
dt.ajax.reload();
}
}
]
} );
myTable.buttons().container().appendTo( $('.tableTools-container') );
//style the message box
var defaultCopyAction = myTable.button(1).action();
myTable.button(1).action(function (e, dt, button, config) {
defaultCopyAction(e, dt, button, config);
$('.dt-button-info').addClass('gritter-item-wrapper gritter-info gritter-center white');
});
var defaultColvisAction = myTable.button(0).action();
myTable.button(0).action(function (e, dt, button, config) {
defaultColvisAction(e, dt, button, config);
if($('.dt-button-collection > .dropdown-menu').length == 0) {
$('.dt-button-collection')
.wrapInner('<ul class="dropdown-menu dropdown-light dropdown-caret dropdown-caret" />')
.find('a').attr('href', '#').wrap("<li />")
}
$('.dt-button-collection').appendTo('.tableTools-container .dt-buttons')
});
});
function rem(frm,id){
bootbox.confirm("Anda yakin akan menghapus data ini?", function(result) {
if(result) {
window.location.href='c_promo/delete_data/'+frm+'/'+id;
}
});
}
function clearForm($form) {
$form.find(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$form.find(':checkbox, :radio').prop('checked', false);
}
$('#btn_save_promo').on('click',function(){
var id = $('#fld1').val();
var name = $('#fld2').val();
var type = $('#fld3').val();
var size = $('#fld4').val();
var kategori = $('#fld5').val();
var mulai = $('#fld6').val();
//var mulai = date.split("-").reverse().join("-");
var akhir = $('#fld7').val();
//var akhir = date1.split("-").reverse().join("-");
var quantity = $('#fld8').val();
//console.log(mulai);
// console.log(akhir);
if(name !="" && type !='' && size !='' && kategori !='' && mulai !='' && akhir !='' && quantity !=''){
$.ajax({
type : "POST",
url : base_url+'admin/c_promo/add_data',
dataType : "JSON",
data : {id:id, name:name, type:type, size:size, kategori:kategori, mulai:mulai,
akhir:akhir, quantity:quantity},
success: function(data){
//console.log(data);
if(data.status == 'terdaftar'){
alert('promo sudah ada..!!');
}
$('#modal_add_new').modal('hide');
$('#promo-table').DataTable().ajax.reload(null, false);
}
});
return false;
}else{
alert("Lengkapi Form (*)");
}
});
function update(frm,id){
$.ajax({
url: base_url+'admin/c_promo/cari_rec',
method: 'GET',
data: {
id: id,
frm: frm
},
success:function(result) {
$("input[name='fld1']").val(id);
//console.log(result);
var res = JSON.parse(result);
res.forEach(addFill);
}
});
}
function addFill(item, index){
if(item.fld.substring(0,3) == "img"){
$(item.fld).load(item.fld);
$(item.fld).attr('src',item.val);
} else if(item.fld.substring(0,5) == "table"){
$(item.fld).html(item.val);
} else if(item.fld.substring(0,4) == "span"){
$(item.fld).html(item.val);
} else if(item.fld.substring(0,1) != ""){
$(item.fld).val(item.val);
}
}
And then this is my HTML
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<li class="active">Dashboard</li>
</li>
</ul><!-- /.breadcrumb -->
</div>
<div class="page-content">
<div class="row">
<div class="col-xs-12">
<h3 class="header smaller lighter blue"><?php echo $title;?></h3>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="tabbable">
<ul class="nav nav-tabs" id="myTab">
<li class="active">
<a data-toggle="tab" href="#home" aria-expanded="false">
<i class="green ace-icon fa fa-home bigger-120"></i>
Promo
</a>
</li>
<li class="">
<a data-toggle="tab" href="#bonus" aria-expanded="true">
Promo Bonus
<span class="badge badge-danger">4</span>
</a>
</li>
<li class="">
<a data-toggle="tab" href="#item" aria-expanded="true">
Promo Item
<span class="badge badge-danger">4</span>
</a>
</li>
</ul>
<div class="tab-content">
<div id="home" class="tab-pane fade active in">
<div class="clearfix">
<button class="btn btn-white btn-info btn-bold" data-toggle="modal" data-target="#modal_add_new" id="btn_tambah">
<i class="ace-icon fa fa-pencil-square-o bigger-120 blue"></i>
Tambah
</button>
<div class="pull-right tableTools-container"></div>
</div>
<br>
<div class="table-header">
Results for "Promo"
</div>
<div>
<table id="promo-table" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th style="text-align:center;">No</th>
<th>Nama Promo</th>
<th style="text-align:center;">Mulai</th>
<th style="text-align:center;">Sampai</th>
<th style="text-align:center;">Qty</th>
<th>Type</th>
<th>Kategori Produk</th>
<th style="text-align:center;">Aksi</th>
</tr>
</thead>
<tbody style="cursor: pointer;">
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
<div id="bonus" class="tab-pane fade">
<table id="bonus-table" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th style="text-align:center;">No</th>
<th>Nama Supplier</th>
<th style="text-align:center;">Aksi</th>
</tr>
</thead>
<tbody style="cursor: pointer;">
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
<div id="item" class="tab-pane fade">
<table id="item-table" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th style="text-align:center;">No</th>
<th>Nama Supplier</th>
<th style="text-align:center;">Aksi</th>
</tr>
</thead>
<tbody style="cursor: pointer;">
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="modal_add_new" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true">
<div class="modal-dialog" style="width:70%;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 class="modal-title" id="myModalLabel">Master Promo</h3>
</br><?php //echo $this->session->userdata('user_id');?>
</div>
<?php //echo form_open_multipart('', 'class="form-horizontal" id="frm_promo"'); ?>
<form id="frm_promo" class="form-horizontal">
<div class="modal-body">
<div class="row">
<div class="col-xs-12">
<div class="col-xs-6">
<div class="form-group">
<label class="control-label col-xs-4" >Nama Promo</label>
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash()?>" />
<input type="hidden" name="fld1" id="fld1" class="form-control text-uppercase" value="">
<div class="col-xs-8">
<textarea name="fld2" id="fld2" class="form-control" type="text" placeholder="Nama Promo..." required></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4" >Type Diskon</label>
<div class="col-xs-8">
<select class="form-control" name="fld3" id="fld3" style="width:200px;" required/>
<option value="">Please Select</option>
<?php
$options1 = array(
"Persentase" => "Percentage",
"FreeItem" => "FreeItem",
"Nominal" => "Nominal"
);
foreach ($options1 as $diskon => $val){
?>
<option value="<?php echo $val;?>"> <?php echo $diskon;?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4" >Ukuran Gambar</label>
<div class="col-xs-8">
<select class="form-control" name="fld4" id="fld4" style="width:200px;" required/>
<option value="">Please Select</option>
<?php
$options5 = array(
"Besar" => "Size366x500",
"Kecil" => "Size220x250"
);
foreach ($options5 as $ukuran => $val){
?>
<option value="<?php echo $val;?>"> <?php echo $ukuran;?> ( <?php echo $val;?> ) </option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4" >Kategori</label>
<div class="col-xs-8">
<select class="form-control" name="fld5" id="fld5" style="width:200px;" required/>
<option value="">Please Select</option>
<?php
$q = $this->db->query("SELECT id,name FROM productcategory ORDER BY name");
$r2 = $q->result_array();
foreach ($r2 as $row){
?>
<option value="<?php echo $row['id'];?>"><?php echo $row['name'];?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label class="control-label col-xs-4" >Mulai Promo</label>
<div class="col-xs-8">
<div class='input-group date' id='datetimepicker1' style="width:160px;">
<input type='text' name="fld6" id="fld6" class="form-control" placeholder="Mulai Promo..." required/>
<span class="input-group-addon">
<span class="fa fa-calendar">
</span>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4" >Akhir Promo</label>
<div class="col-xs-8">
<div class='input-group date' id='datetimepicker2' style="width:160px;">
<input type='text' name="fld7" id="fld7" class="form-control" placeholder="Akhir Promo..." required/>
<span class="input-group-addon">
<span class="fa fa-calendar">
</span>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4" >Minimum Quantity</label>
<div class="col-xs-8">
<input name="fld8" id="fld8" style="width:40px;" class="form-control" type="text" placeholder="Qty..." required/>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group" style="margin-left:10px;">
<button class="btn btn-info" id="btn_add">Add</button>
</div>
<table id="promo-produk" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th style="text-align:center;">No</th>
<th>ID</th>
<th>Nama</th>
<th>Kategori</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr class="odd gradeX">
<td style="width:10px"></td>
<td></td>
<td></td>
<td></td>
<td style="width:20px"><a class="edit" href="">Edit</a></td>
<td style="width:20px"><a class="delete" href="">Delete</a></td>
</tr>
</tbody>
<!--<tbody style="cursor: pointer;">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>-->
</table>
</div>
</div>
</div>
</form>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Tutup</button>
<button class="btn btn-info" id="btn_save_promo">Simpan</button>
</div>
</div>
</div>
</div>
<!-- <div class="modal fade" id="modal_add_item" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true">
<div class="modal-dialog" style="width:70%;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 class="modal-title" id="myModalLabel">Item Promo</h3>
</div>
<form id="frm_item" class="form-horizontal">
<div class="modal-body">
<div class="row">
<div class="col-xs-12">
<div class="col-xs-6">
<div class="form-group">
<label class="control-label col-xs-4" >Nama Promo</label>
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash()?>" />
<input type="hidden" name="fld1" class="form-control text-uppercase" value="">
<div class="col-xs-8">
<input name="fld2" id="fld2" class="form-control" type="text" placeholder="Nama Promo..." required>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4" >Tipe Diskon</label>
<div class="col-xs-8">
<select class="form-control" name="fld3" id="fld3" style="width:200px;" required/>
<option value="">Please Select</option>
<?php
$options1 = array(
"Persentase" => "Percentage",
"FreeItem" => "FreeItem",
"Nominal" => "Nominal"
);
foreach ($options1 as $diskon => $val){
?>
<option value="<?php echo $val;?>"> <?php echo $diskon;?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4" >Diskon</label>
<div class="col-xs-8">
<input name="fld3a" style="width:40px;" class="form-control" type="text" placeholder="Nilai..." required/>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4" >Ukuran Gambar</label>
<div class="col-xs-8">
<select class="form-control" name="fld6" id="ukuran" style="width:200px;" required/>
<option value="">Please Select</option>
<?php
$options5 = array(
"Besar" => "Size366x500",
"Kecil" => "Size220x250"
);
foreach ($options5 as $ukuran => $val){
?>
<option value="<?php echo $val;?>"> <?php echo $ukuran;?> ( <?php echo $val;?> ) </option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4" >Kategori</label>
<div class="col-xs-8">
<select class="form-control" name="fld7" id="kategori" style="width:200px;" required/>
<option value="">Please Select</option>
<?php
$q = $this->db->query("SELECT id,name FROM productcategory ORDER BY name");
$r2 = $q->result_array();
foreach ($r2 as $row){
?>
<option value="<?php echo $row['id'];?>"><?php echo $row['name'];?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label class="control-label col-xs-4" >Mulai Promo</label>
<div class="col-xs-8">
<div class='input-group date' id='datetimepicker1' style="width:160px;">
<input type='text' name="fld3" class="form-control" placeholder="Mulai Promo..." required/>
<span class="input-group-addon">
<span class="fa fa-calendar">
</span>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4" >Akhir Promo</label>
<div class="col-xs-8">
<div class='input-group date' id='datetimepicker2' style="width:160px;">
<input type='text' name="fld4" class="form-control" placeholder="Akhir Promo..." required/>
<span class="input-group-addon">
<span class="fa fa-calendar">
</span>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4" >Quantity</label>
<div class="col-xs-8">
<input name="fld5" style="width:40px;" class="form-control" type="text" placeholder="Qty..." required/>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Tutup</button>
<button class="btn btn-info" id="simpan">Simpan</button>
</div>
</div>
</div>
</div> -->
You need to empty the form when you open the modal again or you will always have the all data because when you open/close a modal the only thing you are doing is showing/hiding a div. You could create a function like this one to clear all the inputs of the form:
function clearForm($form) {
$form.find(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$form.find(':checkbox, :radio').prop('checked', false);
}
And call like:
myTable.on('dblclick', 'tr', function (){
clearForm('#modal_add_new');
var data = myTable.row( this ).data();
//alert(data[3]);
var s = '1';
update(s,data[8]);
$('#modal_add_new').modal('show');
});

Insert data to my CRUD table

I have this AJAX code that will insert data to my CRUD table. But when I click the button that will save/insert the data to my table it will not show. All I want here is to insert my data using AJAX to my table without refreshing or using the form element in html.
Here is my code with my modal and the body of my table:
$(document).ready(function() {
// Add
$('#btn_add').click(function() {
var id = $('#brand_id').val();
var bname = $('#bname').val();
var bstatus = $('#bstatus').val();
$.ajax({
url: 'add_brand.php',
method: 'POST',
data: {
bname: bname,
bstatus: bstatus
},
success: function(data) {
$('#' + id).children('td[data-target=brand_name]').text(bname);
$('#' + id).children('td[data-target=brand_status]').text(bstatus);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal fade" id="modal-default">
<div class="modal-dialog">
<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">Add a brand</h4>
</div>
<div class="modal-body">
<input type="hidden" id="brand_id" />
<div class="form-group">
<label for="bname">Brand Name</label>
<input type="text" class="form-control" id="bname" name="bname" placeholder="Brand Name" />
</div>
<div class="form-group">
<label for="bstatus">Status</label>
<select class="form-control select2" style="width: 100%;" id="bstatus" name="bstatus">
<option>Available</option>
<option>Not Available</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="btn_add">Save Changes</button>
</div>
</div>
</div>
</div>
<tbody>
<?php
include("db_connect/connect.php");
$query = mysqli_query($con, "SELECT * FROM brand");
while ($row = mysqli_fetch_array($query)) { ?>
<tr id="<?php echo $row['brand_id']; ?>">
<td data-target="brand_name"><?php echo $row["brand_name"]; ?></td>
<td data-target="brand_status"><?php echo $row["brand_status"]; ?></td>
<td>
<a data-role="edit" data-id="<?php echo $row['brand_id']; ?>" class="btn btn-success"><i class="fa fa-edit"></i> Edit</a>
<i class="fa fa-trash-o"></i> Delete
</td>
</tr>
<?php
}
?>
</tbody>

PHP Login not working

I have been working on a ban management system for a little bit but I encountered a error with the login system where it does not work
Live example:
http://lotus.pe.hu/lbans/index.php/
username: admin
pass: anmol123
Their is no error or anything with the code from where I can tell if you need the code I will post it
index.php
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.min.css"/>
<title>LotusBans [BETA] [V 1.0] ~ Home</title>
</head>
<body>
<?php
require("api/api.php");
require("header.php");
?>
<div class="jumbotron">
<div class="container">
<h2>LotusBans [BETA] [v1.0]</h2>
<p>View the players banned on the LotusNetwork Here</p>
</div>
</div>
<?php if (isset($_SESSION["username"])) { ?>
<div class="container">
<input type="button" value="+" data-toggle="modal" data-target="#modal" class="btn btn-primary pull-right"/>
<br/><br/>
</div>
<?php } ?>
<div class="container">
<table class="table table-bordered">
<tr>
<th>ID</th>
<th>UUID</th>
<th>Date</th>
<th>Reason</th>
</tr>
<?php
$bans = get_bans();
while ($ban = $bans->fetch_assoc()) {
?>
<tr>
<td><?php echo $ban["id"] ?></td>
<td><?php echo $ban["uuid"] ?></td>
<td><?php echo $ban["date"] ?></td>
<td><?php echo $ban["reason"] ?></td>
</tr>
<?php } ?>
</table>
</div>
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<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">Add Ban</h4>
</div>
<form id="form">
<div class="modal-body">
<div class="form-group">
<input type="text" id="uuid" name="uuid" placeholder="UUID" class="form-control"/>
</div>
<div class="form-group">
<input type="text" id="reason" name="reason" placeholder="Reason" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
var uuid = $("#uuid").val();
var reason = $("#reason").val();
$.post("api/add.php", { uuid: uuid, reason: reason }, function(data) {
location.href = "ban.php?id=" + data;
});
});
});
</script>
</body>
header.php
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">LotusBans</a>
</div>
<?php session_start(); if (!isset($_SESSION["username"])) { ?>
<form method="post" action="login.php" class="navbar-form navbar-right">
<div class="form-group">
<input type="text" name="username" placeholder="Username" class="form-control">
<input type="password" name="password" placeholder="Password" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Log In</button>
</form>
<?php } else { ?>
<div class="navbar-right">
<p class="navbar-text">Welcome, <?php echo $_SESSION["username"]; ?></p>
</div>
<?php } ?>
</div><!-- /.container-fluid -->
api.php
<?php
define("key", file_get_contents("http://lotus.pe.hu/lbans/can'tenterthis as this is a key"));
function get_mysql() {
$mysql = new mysqli("", "", "", "");
if ($mysql->connect_error) {
die($mysql->connect_error);
}
return $mysql;
}
function add($uuid, $reason) {
$date = date("Y-m-d H:i:s");
get_mysql()->query("insert into bans (uuid, date, reason) values ('$uuid', '$date', '$reason')");
return get_mysql()->query("select id from bans where uuid = '$uuid' and date = '$date' and reason = '$reason'")->fetch_assoc()["id"];
}
function update($id, $uuid, $reason) {
get_mysql()->query("update bans set uuid = '$uuid', reason = '$reason' where id = $id");
}
function remove($uuid) {
get_mysql()->query("delete from bans where uuid = '$uuid'");
}
function remove_by_id($id) {
get_mysql()->query("delete from bans where id = $id");
}
function get($uuid) {
return get_mysql()->query("select * from bans where uuid = '$uuid'")->fetch_assoc();
}
function get_by_id($id) {
return get_mysql()->query("select * from bans where id = $id")->fetch_assoc();
}
function get_bans() {
return get_mysql()->query("select * from bans");
}
function login($username, $password) {
$password = hash("sha256", $password);
return get_mysql()->query("select count(*) from users where username = '$username' and password = '$password'")->fetch_assoc()["count(*)"] > 0;
}
function register($username, $password) {
$password = hash("sha256", $password);
get_mysql()->query("insert into users (username, password) values ('$username', '$password')");
}
?>
Try to add this to this..
<?php
session_start(); //Transfer the session_start() here ..
require("api/api.php");
if( isset($_POST['username']) )
{
if( login( $_POST['username'], $_POST['password'] ) )
{
$_SESSION['username'] = $_POST['username'];
}
else
{
echo 'Invalid username/password';
}
}
require("header.php");
?>

Creating a CRUD using PHP + Bootstrap Modal + Mysql + JS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need a page with a button to insert a new user, with fields "country","name" and "company". Then, in the same page, I need to list those datas and in front each item it'll appear two buttons, "edit" and "delete". At edit button, I need to display a Modal window (bootstrap), so I could update this data.
I hope someone could help me.
Thanks
Sorry, I've forgot to paste the code.
This is my index.php:
<form action="inserir.php" method="post" name="visitas" id="visitas">
<table class="table_geral" align="center" width="350" border="0" cellspacing="0" cellpadding="3">
<tr>
<td width="200">Pais:</td>
<td>
<?
$array_pais = array('Selecione...','Alemanha','Angola','Argentina','Bolívia','Brasil','Camarões','Canadá','Chile','China','Colombia',
'Costa Rica','Cuba','Dinamarca','Equador','Espanha','Estados Unidos','França','Holanda','Inglaterra','Itália','Japão',
'México','Nigéria','Panamá','Paraguai','Peru','Porto Rico','Portugal','Rússia','Senegal','Taiwan','Uruguai','Venezuela'
);
echo '<select class="form-control" style="width:330px" name="pais" id="pais">';
foreach($array_pais as $valor){
echo '<option>'.$valor.'</option>';
}
echo '</select>';
?>
</td>
<td height="29" valign="center" align="center" rowspan="3">&nbsp </td>
<td height="29" valign="center" align="center" rowspan="3">
<input type="submit" name="Submit" class="btn btn-success btn-lg" value=" + ">
</td>
</tr>
<tr>
<td width="411">Nome:</td>
<td width="339">
<input class="form-control" name="nome" type="text" id="nome" size="50">
</td>
</tr>
<tr>
<td width="411">Empresa:</td>
<td width="339">
<input class="form-control" name="empresa" type="text" id="empresa" size="50" style="text-transform:uppercase;">
</td>
</tr>
</table>
</form>
$sql = "SELECT * FROM tb_visitas ORDER BY empresa";
$limite = mysql_query("$sql"); ?>
<table data-toggle="table" data-cache="false">
<thead align="center">
<tr height="35px" valign="center" bgcolor="#B0E2FF" >
<th style="text-align:center; vertical-align:middle; width="100px">PAÍS</th>
<th style="text-align:center; vertical-align:middle; width="250px">NOME</th>
<th style="text-align:center; vertical-align:middle; width="300px">EMPRESA</th>
<th style="text-align:center; vertical-align:middle; width="5px" colspan="2">AÇÕES</th>
</tr>
</thead>
<? while($result = mysql_fetch_array($limite)){ ?>
<tbody>
<tr>
<td style="display:none" align="center"><?=$result['id']; $_SESSION=$result['id'];?></td>
<td style="vertical-align:middle;"> <?=$result['pais']?></td>
<td style="vertical-align:middle;"> <?=$result['nome']?></td>
<td style="text-transform:uppercase; vertical-align:middle;"><?=$result['empresa']?></td>
<td style="width:20px">
<form action="editar.php" method="post">
<a class="btn btn-primary glyphicon glyphicon-pencil" title="Editar" href="editar.php?id=<?=$result['id'];?>"></a>
</form>
</td>
<td style="width:20px">
<a class="btn btn-danger glyphicon glyphicon-trash" title="Deletar" href="deletar.php?id=<?=$result['id'];?>"></a>
</td>
</tr>
</tbody>
<?}?>
</table>
<div class="container">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">
<span class="glyphicon glyphicon-pencil"></span> Novo registro</h4>
</div>
<div class="modal-body">
<p></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>
</div>
</div>
</div>
</div>
<script>
$('form').submit(function () {
var postdata = {
pais: $(this)[0].pais.value,
nome: $(this)[0].nome.value,
empresa: $(this)[0].empresa.value
}
$.post("inserir.php", postdata, function (d) {
$('#myModal').find(".modal-body").html(d);
$('#myModal').modal('show');
});
return false;
});
</script>
And it's my inserir.php:
<?
require("conexao.php");
$pais = $_POST['pais'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
if (($pais == "") || ($pais == "Selecione...") || ($nome == "") || ($empresa == "")) {
echo "Favor preencha todos os campos!";
} else {
$sql = mysql_query("SELECT nome FROM tb_visitas WHERE nome='$nome'");
if (mysql_num_rows($sql) > 0) {
echo "O nome <b>$nome</b> ja foi inserido na lista!";
} else {
$sqlinsert = "INSERT INTO tb_visitas VALUES (null, '$pais', '$nome', UPPER('$empresa'))";
mysql_query($sqlinsert) or die (mysql_error());
echo "Gravado com sucesso!";
}
}
?>
With assist from CodeGodie now I have this code, but I need to open a Modal window (bootstrap) to edit some register. However I don't know how to make it with AJAX. I feel sorry for my bad explanation and my English. Thanks
Sorry, but I'm beginner in php and ajax. There are much code that I've never seen :( ....Then, I'm having some difficulty to make it work out. I thought it was simplest. However I tried to make the files:
editar.php
$con = mysql_connect("localhost", "root", "", "visitas");
// Check connection
if (mysql_error()) {
echo "Failed to connect to MySQL: " . mysql_error();
}
$id = $_POST['id'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
$pais = $_POST['pais'];
$query = "UPDATE tb_visitas SET nome = '$nome', empresa = '$empresa', pais= '$pais' WHERE id = $id ";
if (mysql_query($con, $query)) {
$res['response'] = true;
$res['message'] = "Record has been updated";
} else {
$res['response'] = false;
$res['message'] = "Error: " . $query . "<br>" . mysql_error($con);
}
echo json_encode($res);
deletar.php
<?php
require("conexao.php");
$id = $_POST['id'];
if (isset($_POST['id'])) {
$sql = "DELETE FROM tb_visitas WHERE id = $id";
$deletar = mysql_query($sql) or die (mysql_error());
}
?>
get_list.php
$con = mysql_connect("localhost", "root", "", "visitas");
if (mysql_error()) {
echo "Failed to connect to MySQL: " . mysql_error();
}
$id = $_POST['id'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
$pais = $_POST['pais'];
$query = "SELECT * FROM tb_visitas";
?>
conexão.php
<?
error_reporting(E_ALL ^ E_DEPRECATED);
$hostname = 'localhost';
$username = 'root';
$senha = '';
$banco = 'visitas';
$db = mysql_connect($hostname, $username, $senha);
mysql_set_charset('latin1',$db);
mysql_select_db($banco, $db) or die ("Não foi possível conectar ao banco MySQL");
?>
I see what you have now. Thanks for adding the code. I would first focus on design. It sounds like you want some sort of CRUD(Create Retrieve Update Delete) system. In that case, what I would do, is place the initial submission form on top (like what you have), and use modals to show any alert messages and the Edit form.
The design would look like this:
+-------------------------------------+
| Submit Form |
| - input |
| - input |
+-------------------------------------+
| List showing DB info |
| - result 1 (with Edit/Delete links) |
| - result 2 (with Edit/Delete links) |
| ... |
+-------------------------------------+
At page load, you will run an JS function, we can call it update_list(), that will use AJAX to fetch all the database info and parse it in the List container.
Then you will delegate Edit/Delete Click events to call the desired AJAX calls.
Keep in mind, this design structure separates everything in functions and uses AJAX to call on PHP scripts. The data will be sent via JSON.
Now, when you Submit the submission form, this will also use AJAX to send POST requests to PHP, then once submitted, JS will use Bootstrap's modal to show messages.
When the edit link is clicked, JS will again open a Bootstrap modal to show the edit form.
With that said, this is how I would do it :
<html>
<title>Modal</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<style>
#wrapper {
padding: 10px;
}
.modal-header, h4, .close {
background-color: #5cb85c;
color: white !important;
text-align: center;
font-size: 30px;
}
.modal-footer {
background-color: #f9f9f9;
}
</style>
</head>
<body>
<div id="wrapper">
<form id="submit_form" role="form" style="width: 300px;">
<div class="form-group">
<label for="pais">Pais:</label>
<?php
$array_pais = array('Selecione...', 'Alemanha', 'Angola', 'Argentina', 'Bolívia', 'Brasil', 'Camarões', 'Canadá', 'Chile', 'China', 'Colombia',
'Costa Rica', 'Cuba', 'Dinamarca', 'Equador', 'Espanha', 'Estados Unidos', 'França', 'Holanda', 'Inglaterra', 'Itália', 'Japão',
'México', 'Nigéria', 'Panamá', 'Paraguai', 'Peru', 'Porto Rico', 'Portugal', 'Rússia', 'Senegal', 'Taiwan', 'Uruguai', 'Venezuela'
);
echo '<select class="form-control" name="pais" id="pais">';
foreach ($array_pais as $valor) {
echo '<option>' . $valor . '</option>';
}
echo '</select>';
?>
</div>
<div class="form-group">
<label for="nome">Nome:</label>
<input class="form-control" name="nome" type="text" id="nome" size="50">
</div>
<div class="form-group">
<label for="empresa">Empresa:</label>
<input class="form-control" name="empresa" type="text" id="empresa" size="50" style="text-transform:uppercase;">
</div>
<input type="submit" name="Submit" class="btn btn-success btn-lg" value="+">
</form>
<table id="list" class="table">
<thead align="center">
<tr bgcolor="#B0E2FF">
<th>PAÍS</th>
<th>NOME</th>
<th>EMPRESA</th>
<th>AÇÕES</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="modals_container">
<div class="modal fade" id="message_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Message</h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit_modal" role="dialog">
<div class="modal-dialog">
<form id="edit_form" class="form">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit</h4>
</div>
<div class="modal-body">
<div class="form-group">
Country: <input id="country_input" type="text" name="country">
</div>
<div class="form-group">
Nome: <input id="username_input" type="text" name="username">
</div>
<div class="form-group">
Company: <input id="company_input" type="text" name="company">
</div>
<input id="id_input" type="hidden" name="id">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default">submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
function update_list() {
$.getJSON("get_list.php", function (data) {
if (data.response) {
$("#list").find("tbody").empty();
data.results.forEach(function (i) {
console.log(i);
$("#list").find("tbody").append(
"<tr>" +
"<td>" + i.country + "</td>" +
"<td>" + i.username + "</td>" +
"<td>" + i.company + "</td>" +
"<td><a class='edit_link' href='" + JSON.stringify(i) + "'>edit</a> | <a class='delete_link' href='" + i.id + "'>delete</a></td>" +
"</tr>"
);
});
}
});
}
update_list();
$('#submit_form').submit(function () {
$.ajax({
url: "main.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
if (data.response) {
var $modal = $('#message_modal');
$modal.find(".modal-body").html(data.message);
$modal.modal('show');
update_list();
} else {
alert(data.message);
}
}
});
return false;
});
$("#list").delegate('.edit_link', 'click', function (e) {
e.preventDefault();
var info = JSON.parse($(this).attr("href"));
var $modal = $("#edit_modal");
$modal.find("#country_input").val(info.country);
$modal.find("#company_input").val(info.company);
$modal.find("#username_input").val(info.username);
$modal.find("#id_input").val(info.id);
$modal.modal('show');
});
$('#edit_form').submit(function () {
$.ajax({
url: "edit.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
if (data.response) {
var $modal = $('#message_modal');
$("#edit_modal").modal('hide');
$modal.find(".modal-body").html(data.message);
$modal.modal('show');
update_list();
} else {
alert(data.message);
}
}
});
return false;
});
</script>
</body>
</html>
edit.php should be something like this:
$con = mysqli_connect("localhost", "root", "", "test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];
$nome = $_POST['username'];
$company = $_POST['company'];
$country = $_POST['country'];
$query = "UPDATE table SET username = '$nome', company = '$company', country= '$country' WHERE id = $id ";
if (mysqli_query($con, $query)) {
$res['response'] = true;
$res['message'] = "Record has been updated";
} else {
$res['response'] = false;
$res['message'] = "Error: " . $query . "<br>" . mysqli_error($con);
}
echo json_encode($res);
Try this out, and let me know what you think.
I've not changed much php code of yours. I added little code to it.
In , i added code to call editar.php modal. In that script tag.. more code were there.. I don't know what is that.
index.php
//
Your original code here(No changes). From down, it started changing
//
<table data-toggle="table" data-cache="false">
<thead align="center">
<tr height="35px" valign="center" bgcolor="#B0E2FF" >
<th style="text-align:center; vertical-align:middle; width="100px">PAÍS</th>
<th style="text-align:center; vertical-align:middle; width="250px">NOME</th>
<th style="text-align:center; vertical-align:middle; width="300px">EMPRESA</th>
<th style="text-align:center; vertical-align:middle; width="5px" colspan="2">AÇÕES</th>
</tr>
</thead>
<? while($result = mysql_fetch_array($limite)){ ?>
<tbody>
<tr>
<td style="display:none" align="center"><?=$result['id']; $_SESSION=$result['id'];?></td>
<td style="vertical-align:middle;"> <?=$result['pais']?></td>
<td style="vertical-align:middle;"> <?=$result['nome']?></td>
<td style="text-transform:uppercase; vertical-align:middle;"><?=$result['empresa']?></td>
<td style="width:20px">
//Some Changes Here.. check it
<a class='btnEdit' href="#form_modal" data-toggle="modal" data-EditID="<?echo $result['id'];?>">
<span class='glyphicon glyphicon-pencil'></span>
<a>
</td>
<td style="width:20px">
<a class="btn btn-danger glyphicon glyphicon-trash" title="Deletar" href="deletar.php?id=<?=$result['id'];?>"></a>
</td>
</tr>
</tbody>
<?}?>
</table>
//Add this code.
<div id="form_modal" class="modal fade" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
//Added few codes in script for calling modal.
<script>
$('form').submit(function () {
var postdata = {
pais: $(this)[0].pais.value,
nome: $(this)[0].nome.value,
empresa: $(this)[0].empresa.value
}
$.post("inserir.php", postdata, function (d) {
$('#myModal').find(".modal-body").html(d);
$('#myModal').modal('show');
});
return false;
});
$('.btnEdit').click(function(){
var id=$(this).attr('data-EditID');
$.ajax({url:"editar.php?id="+id,cache:false,success:function(result){
$(".modal-content").html(result);
}});
});
</script>
Make One editar.php. Paste this below code in that page.
editar.php
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">
<span class="glyphicon glyphicon-pencil"></span> Novo registro
</h4>
</div>
<div class="modal-body" style='text-align:justify;'>
<?echo $_GET['id'];?>
//Show Details Here.
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>

Categories

Resources