ive tried my codes to view the data from phpmyadmin database but its not working. the table wont show . but when i add the data in the add form, the data has been successfully added to my database. unfortunately it cant be viewed inside my data table.
this is my result saying that theres no data in data tables
service.php
<?php
include('database_connection.php');
include('function.php');
if(!isset($_SESSION['type']))
{
header('location:login.php');
}
include('header.php');
?>
<link rel="stylesheet" href="css/datepicker.css">
<script src="js/bootstrap-datepicker1.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
<script>
$(document).ready(function(){
$('#service_history_date').datepicker({
format: "yyyy-mm-dd",
autoclose: true
});
});
</script>
<span id="alert_action"></span>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<div class="col-md-10">
<h3 class="panel-title">Car List</h3>
</div>
<div class="col-md-2" align="right">
<button type="button" name="add" id="add_button" data-toggle="modal" data-target="#serviceModal" class="btn btn-success btn-xs">Add</button>
</div>
</div>
</div>
<div class="panel-body">
<table id="service_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Service ID</th>
<th>Car Plate No.</th>
<th>Car Mileage</th>
<th>Service Date</th>
<th>Service Type</th>
<th>Serviced By</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
<div id="serviceModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="service_form">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><i class="fa fa-plus"></i> Add New Service Record</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Choose Car Plate No</label>
<select name="carPlateNo" id="carPlateNo" class="form-control" required />
<option value="">Select Car Plate No</option>
<?php echo fill_carPlateNo_service($connect); ?>
</select>
</div>
<div class="form-group">
<label>Enter Current Mileage</label>
<input type="text" name="carOdometer" id="carOdometer" class="form-control" required />
</div>
<div class="form-group">
<label>Service Date</label>
<input type="text" name="service_history_date" id="service_history_date" class="form-control" required />
</div>
<div class="form-group">
<label>Service Type</label>
<select name="serviceType" id="serviceType" class="form-control" required>
<option value="">Select Service Type</option>
<?php echo fill_serviceType_service($connect); ?>
</select>
</div>
<div class="form-group">
<label>Serviced By</label>
<select name="staff_id" id="staff_id" class="form-control" required>
<option value="">Select Serviced By Staff Name</option>
<?php echo fill_staff_service($connect); ?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="service_history_id" id="service_history_id" />
<input type="hidden" name="btn_action" id="btn_action" />
<input type="submit" name="action" id="action" class="btn btn-info" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
<script>
$(document).ready(function(){
$('#add_button').click(function(){
$('#serviceModal').modal('show');
$('#service_form')[0].reset();
$('.modal-title').html("<i class='fa fa-plus'></i> Add car");
$('#action').val('Add');
$('#btn_action').val('Add');
});
$(document).on('submit','#service_form', function(event){
event.preventDefault();
$('#action').attr('disabled','disabled');
var form_data = $(this).serialize();
$.ajax({
url:"service_action.php",
method:"POST",
data:form_data,
success:function(data)
{
$('#service_form')[0].reset();
$('#serviceModal').modal('hide');
$('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
$('#action').attr('disabled', false);
servicedataTable.ajax.reload();
}
})
});
$(document).on('click', '.update', function(){
var car_id = $(this).attr("id");
var btn_action = 'fetch_single';
$.ajax({
url:'service_action.php',
method:"POST",
data:{service_history_id:service_history_id, btn_action:btn_action},
dataType:"json",
success:function(data)
{
$('#serviceModal').modal('show');
$('#service_history_id').val(data.service_history_id);
$('#car_name').val(data.car_name);
$('.modal-title').html("<i class='fa fa-pencil-square-o'></i> Edit car");
$('#car_id').val(car_id);
$('#action').val('Edit');
$('#btn_action').val('Edit');
}
})
});
$(document).on('click','.delete', function(){
var car_id = $(this).attr("id");
var status = $(this).data('status');
var btn_action = 'delete';
if(confirm("Are you sure you want to change status?"))
{
$.ajax({
url:"service_action.php",
method:"POST",
data:{car_id:car_id, status:status, btn_action:btn_action},
success:function(data)
{
$('#alert_action').fadeIn().html('<div class="alert alert-info">'+data+'</div>');
servicedataTable.ajax.reload();
}
})
}
else
{
return false;
}
});
var servicedataTable = $('#service_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"service_fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[4, 5],
"orderable":false,
},
],
"pageLength": 10
});
});
</script>
<?php
include('footer.php');
?>
service_fetch.php
<?php
//service_fetch.php
include('database_connection.php');
include('function.php');
$query = '';
$output = array();
$query .= "
SELECT * FROM service_history
INNER JOIN car ON car.car_id = service_history.carPlateNo
INNER JOIN serviceType ON serviceType.service_id = service_history.serviceType
INNER JOIN staff ON staff.staff_id = service_history.staff_id
";
if(isset($_POST["search"]["value"]))
{
$query .= '(service_history_id LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR serviceType LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR carPlateNo LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR staff_id LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR service_history_date LIKE "%'.$_POST["search"]["value"].'%") ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY service_history_id DESC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row['service_history_id'];
$sub_array[] = $row['carPlateNo'];
$sub_array[] = $row['carOdometer'];
$sub_array[] = $row['service_history_date'];
$sub_array[] = $row['serviceType'];
$sub_array[] = $row['staff_id'];
$data[] = $sub_array;
}
function get_total_all_records($connect)
{
$statement = $connect->prepare("SELECT * FROM service_history");
$statement->execute();
return $statement->rowCount();
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records($connect),
"data" => $data
);
echo json_encode($output);
?>
service_action.php
<?php
//brand_action.php
include('database_connection.php');
if(isset($_POST['btn_action']))
{
if($_POST['btn_action'] == 'Add')
{
$query = "
INSERT INTO service_history (carPlateNo, carOdometer,
service_history_date, serviceType, staff_id)
VALUES (:carPlateNo, :carOdometer, :service_history_date,
:serviceType, :staff_id)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':carPlateNo' => $_POST["carPlateNo"],
':carOdometer' => $_POST["carOdometer"],
':service_history_date' => date("Y-m-d"),
':serviceType' => $_POST["serviceType"],
':staff_id' => $_POST["staff_id"]
)
);
$result = $statement->fetchAll();
if(isset($result))
{
echo 'New Serviced Car Added';
}
}
if($_POST['btn_action'] == 'fetch_single')
{
$query = "
SELECT * FROM service_history WHERE service_history_id =
:service_history_id
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':service_history_id' => $_POST["service_history_id"]
)
);
$result = $statement->fetchAll();
foreach($result as $row)
{
$output['carPlateNo'] = $row['carPlateNo'];
$output['carOdometer'] = $row['carOdometer'];
$output['service_history_date'] = $row['service_history_date'];
$output['serviceType'] = $row['serviceType'];
$output['staff_id'] = $row['staff_id'];
}
echo json_encode($output);
}
if($_POST['btn_action'] == 'delete')
{
$status = 'active';
if($_POST['status'] == 'active')
{
$status = 'inactive';
}
$query = "
UPDATE car
SET car_status = :car_status
WHERE carPlateNo = :carPlateNo
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':carPlateNo' => $_POST["carPlateNo"],
':car_status' => $status
)
);
$result = $statement->fetchAll();
if(isset($result))
{
echo 'Car status changed to ' . $status;
}
}
}
?>
Related
tried to find any similar problems as I did, but no luck. what differs my problem from the other is that first, my update button doesn't work. every time I click on the update button no modal appears. 2nd is the delete I could click the delete button but the delete function won't work. tried to debug for a few days now but it just won't work. These 2 don't show any errors I tried to check within the browser's developer tools to check the network response if there's anything wrong but I couldn't find any problem at all. I hope anyone could help me, I'm still a beginner in AJAX and a bit fairly new to PHP.
here are my codes in case you might find something that I don't.
tables.php
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add User</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
<br />
<label>Enter Middle Name</label>
<input type="text" name="middle_name" id="middle_name" class="form-control" />
<br />
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
<br />
<label>Enter Address</label>
<input type="text" name="address" id="address" class="form-control" />
<br />
<label>Enter Contact Number</label>
<input type="text" name="contact_number" id="contact_number" class="form-control" />
<br />
<label>Enter Date of Birth</label>
<input type="text" name="birth_date" id="birth_date" class="form-control" />
<br />
</div>
<div class="modal-footer">
<input type="hidden" name="user_ID" id="user_ID" />
<input type="hidden" name="operation" id="operation" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- Page level custom scripts -->
<script type="text/javascript" language="javascript">
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
$('#operation').val("Add");
});
var dataTable = $('#userList').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"datatable.php",
type:"POST"
},
"columnDefs":[
{
"targets":[0,7,8],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var firstName = $('#first_name').val();
var middleName = $('#middle_name').val();
var lastName = $('#last_name').val();
var address = $('#address').val();
var contactNumber = $('#contact_number').val();
var birthDate = $('#birth_date').val();
if(firstName != '' && middleName != '' && lastName != '' && address != '' && contactNumber != '' && birthDate != '' )
{
$.ajax({
url:"insert.php",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Both Fields are Required");
}
});
$(document).on('click', '.update', function(){
var user_ID = $(this).attr("user_id");
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{user_ID:user_ID},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#first_name').val(data.first_name);
$('#middle_name').val(data.middle_name);
$('#last_name').val(data.last_name);
$('#address').val(data.address);
$('#contact_number').val(data.contact_number);
$('#birth_date').val(data.birth_date);
$('.modal-title').html("<i class='fa fa-plus'></i> Update User");
$('#user_ID').val(user_ID);
$('#action').val("Edit");
$('#operation').val("Edit");
}
})
});
$(document).on('click', '.delete', function(){
var user_ID = $(this).attr("user_id");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{user_ID:user_ID},
success:function(data)
{
alert(data);
dataTable.ajax.reload();
}
});
}
else
{
return false;
}
});
</script>
</body>
</html>
insert.php
<?php
include('db.php');
include('function.php');
if(isset($_POST["operation"]))
{
if($_POST["operation"] == "Edit")
{
$statement = $connection->prepare(
"UPDATE user
SET user_fname = :user_fname, user_mname = :user_mname, user_lname = :user_lname,
user_address = :user_address, user_contactnumber = :user_contactnumber, user_birthdate = :user_birthdate
WHERE user_id = :user_id
"
);
$result = $statement->execute(
array(
':first_name' => $_POST["user_fname"],
':last_name' => $_POST["user_mname"],
':last_name' => $_POST["user_lname"],
':address' => $_POST["user_address"],
':contact_number' => $_POST["user_contactnumber"],
':birth_date' => $_POST["user_birthdate"],
':user_id' => $_POST["user_id"]
)
);
if(!empty($result))
{
echo 'Data Updated';
}
}
}
?>
fetch_single.php
<?php
include('db.php');
include('function.php');
if(isset($_POST["user_ID"]))
{
$output = array();
$statement = $connection->prepare(
"SELECT * FROM user
WHERE user_id = '".$_POST["user_id"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output[] = $row['user_fname'];
$output[] = $row['user_mname'];
$output[] = $row['user_lname'];
$output[] = $row['user_address'];
$output[] = $row['user_contactnumber'];
$output[] = $row['user_birthdate'];
}
echo json_encode($output);
}
?>
delete.php
<?php
include('db.php');
include("function.php");
if(isset($_POST["user_ID"]))
{
$statement = $connection->prepare(
"DELETE FROM user WHERE user_id = :user_id"
);
$result = $statement->execute(
array(
':user_id' => $_POST["user_ID"]
)
);
if(!empty($result))
{
echo 'Data Deleted';
}
}
?>
EDIT: forgot to add the important code
datatable.php
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT user_id, user_fname, user_mname, user_lname, user_address, user_contactnumber,user_birthdate FROM user ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE user_id LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_fname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_mname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_lname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_address LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_contactnumber LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_birthdate LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY user_id DESC ';
}
if(isset($_POST["length"]) && $_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$userRows = array();
$userRows[] = $row['user_id'];
$userRows[] = $row['user_fname'];
$userRows[] = $row['user_mname'];
$userRows[] = $row['user_lname'];
$userRows[] = $row['user_address'];
$userRows[] = $row['user_contactnumber'];
$userRows[] = $row['user_birthdate'];
$userRows[] = '<button type="button" name="update" id="'.$row["user_id"].'" class="btn btn-warning btn-xs update">Update</button>';
$userRows[] = '<button type="button" name="delete" id="'.$row['user_id'].'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $userRows;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
I have created a form to display all records from my database with the ability to add a new user, edit, and delete. The delete works fine. However, the add and edit functions are supposed to show a bootstrap modal with either blank fields for the add user, or all the information to edit a user. The modal isn't appearing and I can't understand why. There are no errors displayed in the console. I know I have the correct database configuration since the delete function works.
Driving me crazy :)
I've attached my code to see if anyone knows what I'm missing.
Thanks!!
profile.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Staff Profile Form</title>
<meta charset="utf-8">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script src = "jquery/jquery-3.3.1.js"></script>
<script>
// Update the users data list
function getUsers(){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: 'action_type=view',
success:function(html){
$('#userData').html(html);
}
});
}
// Send CRUD requests to the server-side script
function userAction(type, id){
id = (typeof id == "undefined")?'':id;
var userData = '', frmElement = '';
if(type == 'add'){
frmElement = $("#modalUserAddEdit");
userData =
frmElement.find('form').serialize()+'&action_type='+type+'&id='+id;
}else if (type == 'edit'){
frmElement = $("#modalUserAddEdit");
userData = frmElement.find('form').serialize()+'&action_type='+type;
}else{
frmElement = $(".row");
userData = 'action_type='+type+'&id='+id;
}
frmElement.find('.statusMsg').html('');
$.ajax({
type: 'POST',
url: 'userAction.php',
dataType: 'JSON',
data: userData,
beforeSend: function(){
frmElement.find('form').css("opacity", "0.5");
},
success:function(resp){
frmElement.find('.statusMsg').html(resp.msg);
if(resp.status == 1){
if(type == 'add'){
frmElement.find('form')[0].reset();
}
getUsers();
}
frmElement.find('form').css("opacity", "");
}
});
}
// Fill the user's data in the edit form
function editUser(id){
$.ajax({
type: 'POST',
url: 'userAction.php',
dataType: 'JSON',
data: 'action_type=data&id='+id,
success:function(data){
$('#id').val(data.id);
$('#name').val(data.name);
$('#location').val(data.location);
$('#specialty').val(data.specialty);
}
});
}
// Actions on modal show and hidden events
$(function(){
$('#modalUserAddEdit').on('show.bs.modal', function(e){
var type = $(e.relatedTarget).attr('data-type');
var userFunc = "userAction('add');";
if(type == 'edit'){
userFunc = "userAction('edit');";
var rowId = $(e.relatedTarget).attr('rowID');
editUser(rowId);
}
$('#userSubmit').attr("onclick", userFunc);
});
$('#modalUserAddEdit').on('hidden.bs.modal', function(){
$('#userSubmit').attr("onclick", "");
$(this).find('form')[0].reset();
$(this).find('.statusMsg').html('');
});
});
</script>
</head>
<body>
<?php
// Include and initialize DB class
require_once 'db.php';
$db = new DB();
// Fetch the users data
$users = $db->getRows('monctonfir');
?>
<div class="container">
<div class="row">
<div class="col-md-12 head">
<h5>Users</h5>
<!-- Add link -->
<div class="float-right">
<a href="javascript:void(0);" class="btn btn-success" data-
type="add" data-toggle="modal" data-target="#modalUserAddEdit"><i
class="plus"></i> New User</a>
</div>
</div>
<div class="statusMsg"></div>
<!-- List the users -->
<table class="table table-striped table-bordered">
<thead class="thead-dark">
<tr>
<th>ID</th>
<th>Name</th>
<th>Location</th>
<th>Specialty</th>
<th>Profile Image</th>
<th>Action</th>
</tr>
</thead>
<tbody id="userData">
<?php if(!empty($users)){ foreach($users as $row){ ?>
<tr>
<td><?php echo '#'.$row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['location']; ?></td>
<td><?php echo $row['specialty']; ?></td>
<td><?php echo $row['file']; ?></td>
<td>
UPDATE
DELETE
</td>
</tr>
<?php } }else{ ?>
<tr><td colspan="5">No user(s) found...</td></tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<!-- Modal Add and Edit Form -->
<div class="modal fade" id="modalUserAddEdit" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add New User</h4>
<button type="button" class="close" data-dismiss="modal">×
</button>
</div>
<!-- Modal Body -->
<div class="modal-body">
<div class="statusMsg"></div>
<form role="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" name="location" id="location" placeholder="Enter your work site">
</div>
<div class="form-group">
<label for="specialty">Specialty</label>
<input type="text" class="form-control" name="specialty" id="specialty" placeholder="Enter your specialty">
</div>
<input type="hidden" class="form-control" name="id" id="id"/>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" id="userSubmit">SUBMIT</button>
</div>
</div>
</div>
</div>
</body>
</html>
userAction.php
<?php
// Include and initialize DB class
require_once 'DB.php';
$db = new DB();
// Database table name
$tblName = 'monctonfir';
// If the form is submitted
if(!empty($_POST['action_type'])){
if($_POST['action_type'] == 'data'){
// Fetch data based on row ID
$conditions['where'] = array('id' => $_POST['id']);
$conditions['return_type'] = 'single';
$user = $db->getRows($tblName, $conditions);
// Return data as JSON format
echo json_encode($user);
}elseif($_POST['action_type'] == 'view'){
// Fetch all records
$users = $db->getRows($tblName);
// Render data as HTML format
if(!empty($users)){
foreach($users as $row){
echo '<tr>';
echo '<td>#'.$row['id'].'</td>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['location'].'</td>';
echo '<td>'.$row['specialty'].'</td>';
echo '<td>edit
delete</td>';
echo '</tr>';
}
}else{
echo '<tr><td colspan="5">No user(s) found...</td></tr>';
}
}elseif($_POST['action_type'] == 'add'){
$msg = '';
$status = $verr = 0;
// Get user's input
$name = $_POST['name'];
$location = $_POST['location'];
$specialty = $_POST['specialty'];
// Validate form fields
if(empty($name)){
$verr = 1;
$msg .= 'Please enter your name.<br/>';
}
if(empty($location) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
$verr = 1;
$msg .= 'Please enter your work site.<br/>';
}
if(empty($specialty)){
$verr = 1;
$msg .= 'Please enter your specialty.<br/>';
}
if($verr == 0){
// Insert data in the database
$userData = array(
'name' => $name,
'location' => $location,
'specialty' => $specialty,
);
$insert = $db->insert($tblName, $userData);
if($insert){
$status = 1;
$msg .= 'User data has been inserted successfully.';
}else{
$msg .= 'Some problem occurred, please try again.';
}
}
// Return response as JSON format
$alertType = ($status == 1)?'alert-success':'alert-danger';
$statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
$response = array(
'status' => $status,
'msg' => $statusMsg
);
echo json_encode($response);
}elseif($_POST['action_type'] == 'edit'){
$msg = '';
$status = $verr = 0;
if(!empty($_POST['id'])){
// Get user's input
$name = $_POST['name'];
$location = $_POST['location'];
$specialty = $_POST['specialty'];
$location = $_POST['location'];
// Validate form fields
if(empty($name)){
$verr = 1;
$msg .= 'Please enter your name.<br/>';
}
if(empty($location)){
$verr = 1;
$msg .= 'Please enter a your work site.<br/>';
}
if(empty($specialty)){
$verr = 1;
$msg .= 'Please enter your specialty<br/>';
}
if($verr == 0){
// Update data in the database
$userData = array(
'name' => $name,
'location' => $location,
'specialty' => $specialty,
);
$condition = array('id' => $_POST['id']);
$update = $db->update($tblName, $userData, $condition);
if($update){
$status = 1;
$msg .= 'User data has been updated successfully.';
}else{
$msg .= 'Some problem occurred, please try again.';
}
}
}else{
$msg .= 'Some problem occurred, please try again.';
}
// Return response as JSON format
$alertType = ($status == 1)?'alert-success':'alert-danger';
$statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
$response = array(
'status' => $status,
'msg' => $statusMsg
);
echo json_encode($response);
}elseif($_POST['action_type'] == 'delete'){
$msg = '';
$status = 0;
if(!empty($_POST['id'])){
// Delate data from the database
$condition = array('id' => $_POST['id']);
$delete = $db->delete($tblName, $condition);
if($delete){
$status = 1;
$msg .= 'User data has been deleted successfully.';
}else{
$msg .= 'Some problem occurred, please try again.';
}
}else{
$msg .= 'Some problem occurred, please try again.';
}
// Return response as JSON format
$alertType = ($status == 1)?'alert-success':'alert-danger';
$statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
$response = array(
'status' => $status,
'msg' => $statusMsg
);
echo json_encode($response);
}
}
exit;
?>
Bootstrap lists modals under components requiring JavaScript (i.e. bootstrap.min.js)
take a look at the docs: https://getbootstrap.com/docs/4.0/getting-started/introduction/
Try adding this before the closing body tag:
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
I made a simple search with php and javascript but for some reason it returns the 'not found message'. I've checked the conection with the DB and the SELECT and everything is working fine. Anyone have an idea of which might be the problem?
obs: There are some word in portuguese but they have no function, they're just names and messages.
Here is the html code:
<form method="post" action="pesquisar" class="form-inline my-2 my-lg-0 mr-lg-2">
<div class="input-group">
<input class="form-control" type="text" name="busca" placeholder="Search for...">
<span class="input-group-btn">
<button class="btn btn-primary" name="btnBusca" type="submit">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
<div class="resultados">
</div>
Javascript code:
$(function() {
$('form[acao="pesquisar"]').submit(function() {
var req = $.post('busca.php',$(this).serialize());
$('button[type="submit"]').attr("value","buscando");
req.done(function(data) {
$('button[type="submit"]').attr("value","Buscar");
$('.resultados').empty();
$('.resultados').append(data);
});
return false;
});
});
PHP code:
<?php
$aVar = mysqli_connect('localhost','root','','u534499794_ehall');
if(isset($_POST['busca']) && trim($_POST['busca']) != "" ){
$busca = htmlspecialchars($_POST['busca']);
$qr = mysqli_query($aVar,"SELECT * FROM dados WHERE titulo LIKE '%busca%' || conteudo like '%busca%' ") or die(mysql_error());
if(mysqli_num_rows($qr) > 0) {
$dados = array();
while ($row = mysqli_fetch_assoc($qr)) {
array_push($dados,$row);
}
$dados1 = "";
foreach ($dados as $key => $value) {
foreach ($value as $key1 => $value1) {
$dados1 .= "$value1<br>";
}
$dados1 .= "<br>";
}
$m = array(
'status'=>'sucesso',
'msg'=>$dados1
);
echo $m['msg'];
}else{
$m = array(
'status'=>'erro',
'msg'=>'Nada encontrado'
);
echo $m['msg'];
}
}else{
$m = array(
'status'=>'erro',
'msg'=>'Digite algum texto'
);
echo $m['msg'];
}
?>
I would like to know how a multiple update in MySQL with checkbox because I'm not getting the id attribute checkbox someone could help me?
HTML code
<form method="post" action="../sys/fav.php">
<input type="hidden" id="id_photo" name="id" value="">
<div class="col-md-12">
<p align="right"><button class="btn btn-primary" id="final" name="final">Send</button></p>
</div>
<?php
require "../sys/connect.php";
$email = $_GET['email'];
$sql = mysqli_query($mysqli, "SELECT * FROM gallery WHERE email ='$email'");
while($row = mysqli_fetch_array($sql)){
$id = $row['id'];
$name = $row['nome_galeria'];
$emailcontact = $row['email_contact'];
$pass = $row['pass'];
$email = $row['email'];
$img = $row['img'];
print"<div class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12\">
<input type=\"hidden\" name=\"contact\" value=\"$emailcontact\">
<input type=\"hidden\" name=\"login\" value=\"$email\">
<input type=\"hidden\" name=\"pass\" value=\"$pass\">
<input type=\"hidden\" name=\"name\" value=\"$name\">
<div class=\"hovereffect\">
<img id=\"he\" class=\"img-responsive\" src=\"../images/images/gallery/big/$img\" alt=\"$name\">
<div class=\"overlay\">
<div class=\"btn-group\" data-toggle=\"buttons\">
<label class=\"btn btn-primary cke\">
<input type=\"checkbox\" name=\"ck[]\" class=\"ck\" value=\"not\" id=\"ck_$id\"><i class=\"fa fa-heart\"></i>
</label>
</div>
</div>
</div>
</div>";
}
mysqli_close($mysqli)
?>
</form>
PHP Code
require "conexao.php";
if(isset($_POST['final'])){
$id = $_POST['id'];
foreach($_POST['ck'] as $ck){
$check = $ck;
$sql = mysqli_query($mysqli,"UPDATE gallery SET fav = '$check' WHERE id = '$id'")or die(mysqli_error($mysqli));
}
if($sql)
echo "Success!";
else
echo "Fail!";
}
Code Js to get the id of the checkbox
$("#final").click(function(){
var str = "";
var boxes = $(".ck");
for(var i = 0; i< boxes.length; i++){
if(boxes[i].checked == true){
var tmp = boxes[i].id.split("_");
str+=(i ? "," : "")+tmp[1];
}
}
document.getElementById('id_fotos').value=str;
});
You can get values of checkbox using below code and pass through ajax
var ckArray = new Array();
$.each($('input[name="ck[]"]:checked'),
function(index, ele){
ckArray.push($(ele).val());
});
i'm create online shop, but i have a little problem in cart product.
if i add 2 products same and different product size
this products only show last add to cart.
example i want like this
product : ABC
size : XL
product : SKSD
size : L
i want like this.
this is my code
order.php
<?php
include "connection.php";
$link = $_REQUEST['link_goods'];
$data_pr = mysqli_query($con,"select * from goods where link_goods='".$link."' ");
$pr = mysqli_fetch_object($data_pr);
?>
<section class="main-container col1-layout">
<div class="main container">
<div class="col-main">
<div class="row">
<div class="product-view">
<div class="product-essential">
<form action="#" method="post" id="product_addtocart_form">
<div class="product-shop col-lg-12 col-sm-12 col-xs-12">
<div class="product-name">
<h4><?php echo $pr->goods ?></h4>
</div>
<p class="availability in-stock">Availability: <span><?php echo $pr->stock ?> stock</span></p>
<div class="price-block">
<div class="price-box">
<p class="special-price"> <span class="price-label">Special Price</span> <span class="price"> Rp <?php echo $pr->price ?> </span> </p>
</div>
</div>
<div class="add-to-box">
<div class="add-to-cart">
<label for="qty">Quantity & Size</label>
<div class="pull-left">
<div class="custom pull-left">
<button onClick="var result = document.getElementById('qty'); var qty = result.value; if( !isNaN( qty ) && qty > 1 ) result.value--;return false;" class="reduced items-count" type="button"><i class="icon-minus"> </i></button>
<input type="text" class="input-text qty" readonly style="color:black" value="1" maxlength="5" id="qty" name="qty">
<button onClick="var result = document.getElementById('qty'); var qty = result.value; if(qty>=<?php echo $pr->stock ?>) return false; else if( !isNaN( qty )) result.value++; return false;" class="increase items-count" type="button"><i class="icon-plus"> </i></button>
</div>
<div class="custom pull-left">
<select style="color:black" name="size" id="size" class="input-text qty">
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
</div>
<?php
echo "<input type='hidden' id='price' name='price' value='".$pr->price."'>";
echo "<input type='hidden' id='id_goods' name='id_goods' value='".$pr->id_goods."'>";
?>
</div>
<?php
if ($pr->stock=="0")
{
}
else
{
?>
<button class="button btn-cart" title="Add to Cart" type="submit"><span><i class="icon-basket"></i> Add to Cart</span></button>
<?php } ?>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("form").submit(function(e){
var form_data = $(this).serialize();
var button_content = $(this).find('button[type=submit]');
button_content.html(' ADDING...'); //Loading button text
$.ajax({
url: "proses.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
$("#myinfo").html(data.items);
button_content.html(' ADD TO CART');
if($(".shopping-cart-box").css("display") == "block"){
$(".mycart-box").trigger( "click" );
}
$(".mycart-box").trigger( "click" );
})
e.preventDefault();
});
});
</script>
proses.php
<?php
session_start(); //start session
$mysqli_conn = new mysqli("localhost", "root", "", "databaseshop");
if ($mysqli_conn->connect_error) {
die('Error : ('. $mysqli_conn->connect_errno .') '. $mysqli_conn->connect_error);
}
if(isset($_POST["id_goods"]))
{
// i think's using condtion in here when different size product
foreach($_POST as $key => $value){
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
}
$statement = $mysqli_conn->prepare("SELECT goods, images_goods, price FROM goods_table WHERE id_goods=? LIMIT 1");
$statement->bind_param('s', $new_product['id_goods']);
$statement->execute();
$statement->bind_result($goods, $images_goods, $price);
while($statement->fetch()){
$new_product["goods"] = $goods;
$new_product["images_goods"] = $images_goods;
$new_product["price"] = $price;
// i think's using condtion in here when different size product
$_SESSION["products"][$new_product['id_goods']] = $new_product;
}
$total_items = count($_SESSION["products"]);
die(json_encode(array('items'=>$total_items)));
}
//################## Loop Item Cart #####################################
if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
{
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){
$cart_box = ' <div class="top-cart-content arrow_box">';
$cart_box .= ' <ul id="cart-sidebar" class="mini-products-list">';
$total = 0;
foreach($_SESSION["products"] as $product)
{
$product_name = $product["goods"];
$product_cover = $product["images_goods"];
$product_price = $product["price"];
$product_code = $product["id_goods"];
$product_qty = $product["qty"];
$product_size = $product["size"];
$cart_box .= ' <li class="item even remove-item">';
$cart_box .= ' <a class="product-image" href="#" title="'.$product_name.'"><img alt="'.$product_name.'" src="images/barang_sampul/'.$product_cover.'" width="80"></a>';
$cart_box .= ' <div class="detail-item">';
$cart_box .= ' <div class="product-details"> ';
$cart_box .= ' <p class="product-name"> '.$product_name.' </p>';
$cart_box .= ' </div>';
$cart_box .= ' <div class="product-details-bottom"> <span class="price">'.$product_price.'</span> <span class="title-desc">Qty:</span> <strong>'.$product_qty.'</strong> </div>';
$cart_box .= ' <div class="product-details-bottom"> <span class="title-desc">Ukuran :</span> <strong>'.$product_size.'</strong> </div>';
$cart_box .= ' </div>';
$cart_box .= ' </li>';
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
$cart_box .= ' </ul>';
$cart_box .= ' <div class="top-subtotal">Subtotal: <span class="price">'.$total.'</span></div>';
$cart_box .= ' <div class="actions">';
$cart_box .= ' <center><button style="float:none" class="view-cart" type="button"><span>View Cart</span></button></center>';
$cart_box .= ' </div>';
$cart_box .= ' </div>';
die($cart_box);
}else{
// die("Null");
}
}
################# Delete Item From Cart ################
if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
{
$product_code = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING);
if(isset($_SESSION["products"][$product_code]))
{
unset($_SESSION["products"][$product_code]);
}
$total_items = count($_SESSION["products"]);
die(json_encode(array('items'=>$total_items)));
}
?>
Help me thank's