I have a php file I would like to require Wordpress authentication, so you can only access the page when you're logged in. I don't want people to be able to find the file by typing in the path.
Currently I'm running WAMP and using local host. I have the file inside a "template" folder that's inside the Wordpress folder.
What would I need to add to this code to make it login protected using Wordpress?
<?php
include("connection.php");
$query = "SELECT * FROM category";
$result = mysqli_query($connection, $query);
$output = '';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["category_id"].'">'.$row["category_name"].'</option>';
}
?>
<html>
<head>
<title>Mankato State University - Inquriy Tools</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-bootgrid/1.3.1/jquery.bootgrid.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-bootgrid/1.3.1/jquery.bootgrid.js"></script>
<style>
body
{
margin:0;
padding:0;
background-color:#f1f1f1;
}
.box
{
width:1270px;
padding:20px;
background-color:#fff;
border:1px solid #ccc;
border-radius:5px;
margin-top:25px;
}
</style>
</head>
<body>
<div class="container box">
<h1 align="center"><img src="msu-logo-large.jpg" align="center"></h1>
<br />
<br />
<div align="right">
<button type="button" id="add_button" data-toggle="modal" data-target="#productModal" class="btn btn-info btn-lg">Add</button>
<button onclick="location.href='http://localhost/wordpress/wp-login.php?loggedout=true'" class="btn btn-info btn-lg type="button">Logout</button>
<button onclick="location.href='http://localhost/wordpress/wp-admin/about.php'" class="btn btn-info btn-lg type="button">Settings</button>
</div>
<div class="table-responsive">
<table id="product_data" class="table table-bordered table-striped">
<thead>
<tr>
<th data-column-id="FORM_ID" data-type="numeric">ID</th>
<th data-column-id="worker_name">Worker</th>
<th data-column-id="category_name">Category</th>
<th data-column-id="student_name">Student</th>
<th data-column-id="tech_id">TechID</th>
<th data-column-id="course_wanted">Course</th>
<th data-column-id="email">Email</th>
<th data-column-id="phone">Phone</th>
<th data-column-id="date">Date</th>
<th data-column-id="comments">Comments</th>
<th data-column-id="status">Status</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('#add_button').click(function(){
$('#product_form')[0].reset();
$('.modal-title').text("Add Student");
$('#action').val("Add");
$('#operation').val("Add");
});
var productTable = $('#product_data').bootgrid({
ajax: true,
rowSelect: true,
post: function()
{
return{
id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
};
},
url: "fetch.php",
formatters: {
"commands": function(column, row)
{
return "<button type='button' class='btn btn-warning btn-xs update' data-row-id='"+row.FORM_ID+"'>Edit</button>" +
" <button type='button' class='btn btn-danger btn-xs delete' data-row-id='"+row.FORM_ID+"'>Delete</button>";
}
}
});
$(document).on('submit', '#product_form', function(event){
event.preventDefault();
var category_id = $('#category_id').val();
var worker_name = $('#worker_name').val();
var student_name = $('#student_name').val();
var tech_id = $('#tech_id').val();
var course_wanted = $('#course_wanted').val();
var email = $('#email').val();
var phone = $('#phone').val();
var comments = $('#comments').val();
var form_data = $(this).serialize();
if(category_id != '' && worker_name != '' && student_name != '' && tech_id != '' && course_wanted != '' && email != '' && phone != '' && comments != '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
alert(data);
$('#product_form')[0].reset();
$('#productModal').modal('hide');
$('#product_data').bootgrid('reload');
}
});
}
else
{
alert("All Fields are Required");
}
});
$(document).on("loaded.rs.jquery.bootgrid", function()
{
productTable.find(".update").on("click", function(event)
{
var FORM_ID = $(this).data("row-id");
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{FORM_ID:FORM_ID},
dataType:"json",
success:function(data)
{
$('#productModal').modal('show');
$('#category_id').val(data.category_id);
$('#worker_name').val(data.worker_name);
$('#student_name').val(data.student_name);
$('#tech_id').val(data.tech_id);
$('#course_wanted').val(data.course_wanted);
$('#email').val(data.email);
$('#phone').val(data.phone);
$('#comments').val(data.comments);
$('#status').val(data.status);
$('.modal-title').text("Edit Product");
$('#FORM_ID').val(FORM_ID);
$('#action').val("Edit");
$('#operation').val("Edit");
}
});
});
});
$(document).on("loaded.rs.jquery.bootgrid", function()
{
productTable.find(".delete").on("click", function(event)
{
if(confirm("Are you sure you want to delete this?"))
{
var FORM_ID = $(this).data("row-id");
$.ajax({
url:"delete.php",
method:"POST",
data:{FORM_ID:FORM_ID},
success:function(data)
{
alert(data);
$('#product_data').bootgrid('reload');
}
})
}
else{
return false;
}
});
});
});
</script>
<div id="productModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="product_form">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Student</h4>
</div>
<div class="modal-body">
<label>Select Request Type</label>
<select name="category_id" id="category_id" class="form-control" required>
<option value="">Select Request Type</option>
<?php echo $output; ?>
</select>
<br />
<label>Enter Worker Name</label>
<input type="text" name="worker_name" id="worker_name" class="form-control" placeholder="Worker first and last name" required/>
<br />
<label>Enter Student Name</label>
<input type="text" name="student_name" id="student_name" class="form-control" placeholder="Student first and last name" required/>
<br />
<label>Enter TechID</label>
<input type="number" name="tech_id" id="tech_id" class="form-control" placeholder="Tech id" required/>
<br />
<label>Enter Course</label>
<input type="text" name="course_wanted" id="course_wanted" class="form-control" placeholder="Section and course id" required/>
<br />
<label>Enter Email</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Email" required/>
<br />
<label>Enter Phone</label>
<input type="text" name="phone" id="phone" class="form-control" placeholder="Phone" required/>
<br />
<label>Enter Comment</label>
<input type="text" name="comments" id="comments" class="form-control" placeholder="Put N/A for blank"/>
<br />
<label>Enter Status</label>
<input type="text" name="status" id="status" class="form-control" placeholder="Auto added"/>
<br />
</div>
<div class="modal-footer">
<input type="hidden" name="FORM_ID" id="FORM_ID" />
<input type="hidden" name="operation" id="operation" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
</div>
</div>
</form>
</div>
</div>
Please check this solution - Click Here
Set Your Defines
define( 'WP_USE_THEMES', false );
define( 'COOKIE_DOMAIN', false );
define( 'DISABLE_WP_CRON', true );
Load the WordPress Core
require("/var/www/yourdomain.com/htdocs/wp-load.php");
Verify, Authenticate, Set Cookie
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
} else {
$creds = array();
// If you're not logged in, you should display a form or something
// Use the submited information to populate the user_login & user_password
$creds['user_login'] = "";
$creds['user_password'] = "";
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error( $user ) ) {
echo $user->get_error_message();
} else {
wp_set_auth_cookie( $user->ID, true );
}
}
Last Check & Using the Session
if ( !is_wp_error( $user ) ) {
// Success! We're logged in! Now let's test against EDD's purchase of my "service."
if ( edd_has_user_purchased( $user->ID, '294', NULL ) ) {
echo "Purchased the Services and is active.";
} else {
echo "Not Purchased";
}
}
Related
I have problem with my ajax,
here my index:
<form name="add_name" id="add_name">
<div class="col-lg-12">
<div class="form-row mb-2">
ID Kurir :
<div class="col">
<input type="text" id="idkurir" name="idkurir" placeholder="Input ID Kurir" class="idkurir" autofocus />
</div>
Nama Kurir :
<div class="col">
<input type="text" id="namakurir" name="namakurir" value="Nama Kurir" class="namakurir" readonly />
</div>
No Laporan :
<div class="col">
<input type="text" id="nolaporan" name="nolaporan" value="No Laporan" readonly />
</div>
Date :
<div class="col">
<?php $now=date('d-m-Y H:i'); ?>
<input type="text" name="date" value=<?php echo "'$now'"; ?> readonly />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<table class="table table-bordered" id="dynamic_field1">
<tr>
<td colspan=2 align=center><strong>Antar Ulang</strong></td>
</tr>
<tr>
<td><input type="text" name="awbau[]" placeholder="Enter AWB" class="form-control name_listau" /></td>
<td><button type="button" name="addau" id="addau" class="btn btn-success">Add More</button></td>
</tr>
</table>
</div>
<div class="col-lg-6">
<table class="table table-bordered" id="dynamic_field2">
<tr>
<td colspan=2 align=center><strong>Undelivery</strong></td>
</tr>
<tr>
<td><input type="text" name="awbundel[]" placeholder="Enter AWB" class="form-control name_listundel" /></td>
<td><button type="button" name="addundel" id="addundel" class="btn btn-success">Add More</button></td>
</tr>
</table>
</div>
</div>
<center><input type="button" name="submit" id="submit" class="btn btn-info btn-block mb-4 mr-2" value="Submit Data" /></center>
</form>
here my ajax script :
$(document).on("keypress", ".idkurir", function(e) {
var idkurir = $('#idkurir').val();
if (e.which == 13) {
$.ajax({
type: "POST",
url: "checkdata.php",
data: {
idkurir: idkurir
},
success: function(response) {
if (response == 1) {
alert("Kurir sudah laporan");
} else {
if (response == "ID Kurir tidak di temukan") {
alert(response);
} else {
var d = new Date();
var today_date = ("0" + d.getDate()).slice(-2) + ("0" + (d.getMonth() + 1)).slice(-2);
$('#nolaporan').val(idkurir + today_date);
$('#namakurir').val(response);
}
}
}
});
}
});
and here my checkdata to check if data exist :
session_start();
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("reportchecker", $connect);
$idkurir = $_POST["idkurir"];
$nolaporan = $idkurir . date("dm");
$sql = "SELECT * FROM jampulang WHERE nolaporan = '$nolaporan'";
$result = mysql_query($sql, $connect);
$count = mysql_num_rows($result);
$response = [];
$sql2 = "SELECT * FROM kurir WHERE idkurir = '$idkurir'";
$result2 = mysql_query($sql2, $connect) or die(mysql_error());
$count2 = mysql_num_rows($result2);
if ($count == 1) {
echo "1";
} else if ($count2 == 1) {
$row = mysql_fetch_array($result2) or die(mysql_error());
echo $row['nama'];
} else {
echo "ID Kurir tidak di temukan";
}
my problem is when response from checkdata = "ID Kurir tidak di temukan", ajax not showing alert and stop update field nolaporan and nama kurir
$('#nolaporan').val(idkurir + today_date);
$('#namakurir').val(response);
in my script above when reponse "ID Kurir tidak di temukan" still update field nolaporan and namakurir.
You can fix it on the client side using $.trim() like below:
if($.trim(response) == 'ID Kurir tidak di temukan') {
//do your code
}
I'm trying to figure it out why I can't get the alert warning or success from the form validation in a modal. all I want at first is to update the data in the database and it work. now I can't see the alert whether it is wrong or correct, the modal close after I submit and how can I transfer the echo json_encode to alert in modal
view: layout view
$('#login_form').on('submit', function( event ){
event.preventDefault();
var Admin_id = $('#Admin_id').val();
var username = $('#username').val();
var email = $('#email').val();
var contact = $('#contact').val();
var hoax = $('#hoax').val();
var confirm = $('#confirm').val();
var date = $('#date').val();
$.ajax({
url: "<?php echo base_url('profile/profile_update'); ?>",
method: "POST",
data: {Admin_id:Admin_id, username:username, email:email,
contact:contact, confirm:confirm, date:date, hoax:hoax},
dataType: "json",
success: function(data){
if (data.result){
$('#result').html('<p class="alert-success"> The inputs are insufficient </p>');
}else{
$('#result').html('<p class="alert-warning"> The profile successfully updated</p>');
}
//return false;
//event.preventDefault();
}
});
return false;
//event.preventDefault();
});
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="profile" id="1" href="#Profile_modal" data-toggle="modal">Profile</a>
<div class="modal" id="Profile_modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg modal-dialog-scrollable" >
<div class="modal-content">
<div class="modal-header bg-secondary">
<h5 class="modal-title text-white">Profile</h5>
<button type="button " class="close" data-dismiss="modal" aria-label="Close">
<span class="text-white" aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" >
<div class="text-center" id="result"> </div>
<div id="data_profile"> </div>
</div>
</div>
</div>
</div>
Controller: profile/profile_update
public function profile_update(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[3]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[13]');
$this->form_validation->set_rules('contact', 'Contact', 'trim|required|min_length[11]');
$this->form_validation->set_rules('hoax', 'Password',
'trim|required|min_length[6]|matches[confirm]');
$this->form_validation->set_rules('confirm', 'ConfirmPassword', 'trim|required|min_length[6]');
if ($this->form_validation->run() == FALSE) {
$data = array('profile_errors' => validation_errors());
echo json_encode(array("result"=>false));
}else{
$this->load->model('admin_model');
$data=$this->profile_model->update_data();
//$data = 'Your Profile Data has been Updated Successfully';
echo json_encode(array("result"=>true));
}
}
profile/get_fetchdata()
public function get_fetchdata(){
$Admin_id = $this->input->post('Admin_id');
if(isset($Admin_id) and !empty($Admin_id)){
$records = $this->profile_model->fetch_data($Admin_id);
$output = '';
foreach ($records->result_array() as $row) {
$attributes = array('id'=>'login_form', 'class'=>'form');
$output = '<div class="text-center" id="result"> </div>';
echo form_open('profile/profile_update', $attributes);
$output = '
<div class="form-group text-left">
<label> Username </label>
<input type="text" id="username" class="form-control" value='. $row["username"] .' placeholder="Enter Username" name="username" maxlength="10" required>
</div>
<div class="form-group text-left">
<label> Email </label>
<input type="Email" id="email" class="form-control" value='. $row["email"] .' placeholder="Enter Email" name="email" maxlength="20" required>
</div>
<div class="form-group text-left">
<label> Phone Number</label>
<input type="number" id="contact" class="form-control" value='.$row["contact"].' placeholder="Enter Phone Number" name="contact" maxlength="11" required>
</div>
<div class="form-group text-left">
<label> Password </label>
<input type="password" id="hoax" class="form-control" value='. $row["hoax"].' placeholder="Enter Password" name="hoax" maxlength="15" required>
</div>
<div class="form-group text-left">
<label> Confirm Password </label>
<input type="password" id="confirm" class="form-control" value='.$row["hoax"].' placeholder="Confirm Password" name="confirm" maxlength="15" required>
</div>
<input type="hidden" id="Admin_id" class="form-control" value='. $row["Admin_id"] .' name="Admin_id">
<input type="hidden" id="date" class="form-control" value='. $row["date_modified"] .' name="date">
<button class="btn btn-primary float-right new_profile" id="1" name="submit" type="submit" >Save</button>
<button class="btn btn-danger mx-2 float-right" data-dismiss="modal" type="button"> Cancel </button>';
echo form_close();
}
echo $output;
}else {
echo "Nothing to show";
}
}
if you use json as dataType, the browser will wait always for a JSON response, so the best thing to do here is the following:
if($this->form_validation->run() == FALSE){
echo json_encode(array("result" => false, "message" => "Failed"));
}else{
echo json_encode(array("result" => true, "message" => "Success!"));
}
and you can check the results on ajax side by using:
$('#login_form').on('submit', function( event ){
event.preventDefault();
var Admin_id = $('#Admin_id').val();
var username = $('#username').val();
var email = $('#email').val();
var contact = $('#contact').val();
var hoax = $('#hoax').val();
var confirm = $('#confirm').val();
var date = $('#date').val();
$.ajax({
url: "<?php echo base_url('profile/profile_update'); ?>",
method: "POST",
data: {Admin_id:Admin_id, username:username, email:email,
contact:contact, confirm:confirm, date:date, hoax:hoax},
dataType: "json",
success: function(data){
if(data.result){
$('#adminId').val("");
$('#username').val("");
$('#email').val("");
$('#contact').val("");
$('#hoax').val("");
$('#confirm').val("");
$('#date').val("");
$('#result').html('<p class="alert-success"> ' + data.message + ' </p>');
}else{
$('#result').html('<p class="alert-warning"> ' + data.message + ' </p>');
}
//return false;
//event.preventDefault();
}
});
return false;
//event.preventDefault();
});
I was trying to convert a form of ajax insert, delete , edit system to my own . Its working nicely in localhost . But whenever I am trying to run these code in my website server , insertion is not working ( delete and edit is working ) . My codes are :
<div class="container box">
<h1 align="center">PHP PDO Ajax CRUD </h1>
<br />
<div class="table-responsive">
<br />
<div align="right">
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal"
class="btn btn-info btn-lg">Add</button>
</div>
<br /><br />
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th width="10%">Image</th>
<th width="30%"> Name</th>
<th width="30%">Education</th>
<th width="10%">age</th>
<th width="10%">Edit</th>
<th width="10%">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<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">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<label>Enter First Name</label>
<input type="text" name="name" id="name" class="form-control" />
<br />
<label>Enter Last Name</label>
<input type="text" name="education" id="education" class="form-control" />
<br />
<label>Enter Last Name</label>
<input type="text" name="age" id="age" class="form-control" />
<br />
<label>Select User Image</label>
<input type="file" name="user_image" id="user_image" />
<span id="user_uploaded_image"></span>
</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>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
$('#operation').val("Add");
$('#user_uploaded_image').html('');
});
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 4],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var name= $('#name').val();
var education= $('#education').val();
var age= $('#age').val();
var extension = $('#user_image').val().split('.').pop().toLowerCase();
if(extension != '')
{
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
$('#user_image').val('');
return false;
}
}
if(name!= '' && education!= '' && age!= '')
{
$.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");
}
});
the code in insert.php are : (I am just showing the code instead maintaining proper way of using brackets , so that we can be right at the point )
<?php
include('db.php');
include('function.php');
if(isset($_POST["operation"]))
{
if($_POST["operation"] == "Add")
{
$image = '';
if($_FILES["user_image"]["name"] != '')
{
$image = upload_image();
}
$statement = $connection->prepare("
INSERT INTO new_table (name, education, age, image)
VALUES (:name, :education, :age, :image)
");
$result = $statement->execute(
array(
':name' => $_POST["name"],
':education' => $_POST["education"],
':age' => $_POST["age"],
':image' => $image
)
);
if(!empty($result))
{
echo 'Data Inserted';
}
}
?>
The result after submission appears as bellow :
enter image description here
You're refering to $_POST['operation'] in your AJAX code but is has no value defined in HTML, try replacing :
<input type="hidden" name="operation" id="operation" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
by
<input type="hidden" name="operation" id="operation" value="Add" />
<input type="submit" name="action" id="action" class="btn btn-success" />
This is my first ever database with AJAX. I'm really lost now, I don't know what to do next.
I already done in the part I can insert data in database and viewing it in website as well. Updating the data is not done yet and it can only fetch data from database in the fill up form but it won't able to insert it in database. Deleting data by row is also my problem.
<?php
$connect = mysqli_connect("localhost", "root", "", "test");
$query = "SELECT * FROM tbl_users ORDER BY id DESC";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<h3 class="jumbotron jumbotron-fluid" align="center">Registration Database</h3>
<div class="container" style="width:900px;">
<div class="table-responsive">
<div align="right">
<input type="button" data-toggle="modal" data-target="#add_data_Modal" value="Add User" class="btn btn-primary">
</input>
</div>
<br />
<div id="employee_table">
<br />
<table class="table table-bordered table-hover">
<tr class = thead-dark>
<th width="40%">First Name</th>
<th width="40%">Last Name</th>
<th width="5%">View</th>
<th width="5%">Update</th>
<th width="5">Delete</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr id="<?php echo $row['id'] ?>" >
<td data-target="firstname"><?php echo $row["firstname"]; ?></td>
<td data-target="lastname"><?php echo $row["lastname"]; ?></td>
<td>
<input type="button" name="view" value="View" id="<?php echo $row["id"]; ?>" class="btn btn-info btn-sm view_data" >
</td>
<td>
<input type="button" name="update" value="Update" id="<?php echo $row["id"]; ?>" class="btn btn-success btn-sm update_data" >
<td>
<input type="button" name="delete" value="Delete" id="<?php echo $row["id"]; ?>" class="btn btn-danger btn-sm delete_data" >
</td>
<?php
}
?>
</table>
</div>
</div>
</div>
<br />
<button onclick="topFunction()" id="myBtn" title="Go to top" class="btn btn-block btn-secondary mx-auto d-block">Back to Top</button>
</body>
</html>
<div id="add_data_Modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add User to Database</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form" >
<label>Full Name</label>
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="Enter First Name" />
<br />
<input type="text" name="middlename" id="middlename" class="form-control" placeholder="Enter Middle Name" />
<br />
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Enter Last Name" />
<br />
<label>Address</label>
<input type="text" name="street" id="street" class="form-control" placeholder="Street">
<br />
<input type="text" name="barangay" id="barangay" class="form-control" placeholder="Barangay">
<br />
<select name="city" class="form-control">
<option value="Caloocan">Caloocan</option>
<option value="Las Piñas">Las Piñas</option>
<option value="Makati">Makati</option>
<option value="Malabon">Malabon</option>
<option value="Mandaluyong">Mandaluyong</option>
<option value="Manila">Manila</option>
<option value="Marikina">Marikina</option>
<option value="Muntinlupa">Muntinlupa</option>
<option value="Navotas">Navotas</option>
<option value="Parañaque">Parañaque</option>
<option value="Pasay">Pasay</option>
<option value="Pasig">Pasig</option>
<option value="Quezon City">Quezon City</option>
<option value="San Juan">San Juan</option>
<option value="Taguig">Taguig</option>
<option value="Valenzuela">Valenzuela</option>
</select>
<br />
<input type="text" name="zipcode" id="zipcode" class="form-control" placeholder="Zip Code">
<br />
<label>Birth Date</label><br />
<input type="date" value="date" id="date" name="birthday" class="form-control" locked onblur="getAge();" placeholder="YYYY-MM-DD" />
<br />
<label for="age">Age</label><br />
<input type="text" id="age" name="age" value="" class="form-control" placeholder="Your Age" readonly>
<br />
<label>Gender</label><br />
<input type="radio" name="gender" value="male" > Male<br />
<input type="radio" name="gender" value="female"> Female<br />
<br />
<label>Contact Number</label>
<br />
<div class="input-group-append">
<span class="input-group-text">+63</span>
<input type="text" name="contactnumber" id="contactnumber" class="form-control" placeholder="919 123 4567 - sample pattern" maxlength="12">
<br />
</div>
<label>Parents Name</label>
<input type="text" name="fathername" id="fathername" class="form-control" placeholder="Father Name" />
<br />
<input type="text" name="mothername" id="mothername" class="form-control" placeholder="Mother Name" />
<br />
<input type="submit" name="insertbutton" id="insertbutton" value="SAVE" class="btn btn-success" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="update_data_Modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Update User to Database</h4>
</div>
<div class="modal-body " id="update_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="dataModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">User Details</h4>
</div>
<div class="modal-body" id="employee_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('#insert_form',).on("submit", function(event){
event.preventDefault();
if($('#firstname').val() == "")
{
alert("First Name is required");
}
else if($('#middlename').val() == '')
{
alert("Middle Name is required");
}
else if($('#lastname').val() == '')
{
alert("Last Name is required");
}
else if($('#street').val() == '')
{
alert("Street is required");
}
else if($('#barangay').val() == '')
{
alert("Barangay is required");
}
else if($('#city').val() == '')
{
alert("City is required");
}
else if($('#zipcode').val() == '')
{
alert("Zip Code is required");
}
else if($('#birthday').val() == '')
{
alert("Birthday is required");
}
else if($('#age').val() == '')
{
alert("Age is required");
}
else if($('#gender').val() == '')
{
alert("Gender is required");
}
else if($('#contactnumber').val() == '')
{
alert("Contact Number is required");
}
else if($('#fathername').val() == '')
{
alert("Father Name is required");
}
else if($('#mothername').val() == '')
{
alert("Mother Name is required");
}
else
{
$.ajax({
url:"insert.php",
method:"POST",
data:$('#insert_form').serialize(),
beforeSend:function(){
$('#insertbutton').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});
}
});
$(document).on('click', '.view_data', function(){
//$('#dataModal').modal();
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
method:"POST",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#dataModal').modal('show');
}
});
});
});
$(document).on('click', '.update_data', function(){
//$('#dataModal').modal();
var employee_id = $(this).attr("id");
$.ajax({
url:"update.php",
method:"POST",
data:{employee_id:employee_id},
success:function(data){
$('#update_detail').html(data);
$('#update_data_Modal').modal('show');
}
});
});
function getAge(){
var birthday = document.getElementById('date').value;
birthday = new Date(birthday);
var today = new Date();
var age = Math.floor((today-birthday) / (365.25 * 24 * 60 * 60 * 1000));
document.getElementById('age').value=age;
}
var mybutton = document.getElementById("myBtn");
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
</script>
INSERT
<?php
$connect = mysqli_connect("localhost", "root", "", "test");
if(!empty($_POST))
{
$output = '';
$firstname = mysqli_real_escape_string($connect, $_POST["firstname"]);
$middlename = mysqli_real_escape_string($connect, $_POST["middlename"]);
$lastname = mysqli_real_escape_string($connect, $_POST["lastname"]);
$street = mysqli_real_escape_string($connect, $_POST["street"]);
$barangay = mysqli_real_escape_string($connect, $_POST["barangay"]);
$city = mysqli_real_escape_string($connect, $_POST["city"]);
$zipcode = mysqli_real_escape_string($connect, $_POST["zipcode"]);
$birthday = mysqli_real_escape_string($connect, $_POST["birthday"]);
$age = mysqli_real_escape_string($connect, $_POST["age"]);
$gender = mysqli_real_escape_string($connect, $_POST["gender"]);
$contactnumber = mysqli_real_escape_string($connect, $_POST["contactnumber"]);
$fathername = mysqli_real_escape_string($connect, $_POST["fathername"]);
$mothername = mysqli_real_escape_string($connect, $_POST["mothername"]);
$query = "INSERT INTO tbl_users(firstname, middlename, lastname, street, barangay, city, zipcode, birthday, age, gender, contactnumber, fathername, mothername) VALUES ('$firstname', '$middlename', '$lastname', '$street', '$barangay', '$city', '$zipcode','$birthday','$age','$gender','$contactnumber','$fathername','$mothername')";
if(mysqli_query($connect, $query))
{
$output .= '<div class="alert alert-success alert-dismissible fade show">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Success!</strong> User is added in the database.
</div>';
$select_query = "SELECT * FROM tbl_users ORDER BY id DESC";
$result = mysqli_query($connect, $select_query);
$output .= '
<table class="table table-bordered table-hover">
<tr class = thead-dark>
<th width="40%">First Name</th>
<th width="40%">Last Name</th>
<th width="5%">View</th>
<th width="5%">Update</th>
<th width="5">Delete</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>' . $row["firstname"] . '</td>
<td>' . $row["lastname"] . '</td>
<td><input type="button" name="view" value="View" id="' . $row["id"] . '" class="btn btn-info btn-sm view_data" /></td>
<td><input type="button" name="update" value="Update" id="' . $row["id"] . '" class="btn btn-success btn-sm update_data" ></td>
<td><input type="button" name="delete" value="Delete" id="' . $row["id"] . '" class="btn btn-danger btn-sm delete_data" ></td>
</tr>
';
}
$output .= '</table>';
}
echo $output;
}
?>
UPDATE
<?php
if(isset($_POST["employee_id"]))
{
$output = '';
$connect = mysqli_connect("localhost", "root", "", "test");
$query = "SELECT * FROM tbl_users WHERE id = '".$_POST["employee_id"]."'";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$output .= '
<form method="post" id="edit_form" >
<label>Full Name</label>
<input type="text" value='.$row["firstname"].' class="form-control" placeholder="First Name" readonly /> <br />
<input type="text" value='.$row["middlename"].' class="form-control" placeholder="Middle Name" readonly /> <br />
<input type="text" value='.$row["lastname"].' class="form-control" placeholder="Last Name" readonly /> <br />
<label>Address</label>
<input type="text" id="street" value='.$row["street"].' class="form-control" placeholder="Street" /> <br />
<input type="text" id="barangay" value='.$row["barangay"].' class="form-control" placeholder="Barangay" /> <br />
<select name="city" class="form-control">
<option value="Caloocan">Caloocan</option>
<option value="Las Piñas">Las Piñas</option>
<option value="Makati">Makati</option>
<option value="Malabon">Malabon</option>
<option value="Mandaluyong">Mandaluyong</option>
<option value="Manila">Manila</option>
<option value="Marikina">Marikina</option>
<option value="Muntinlupa">Muntinlupa</option>
<option value="Navotas">Navotas</option>
<option value="Parañaque">Parañaque</option>
<option value="Pasay">Pasay</option>
<option value="Pasig">Pasig</option>
<option value="Quezon City">Quezon City</option>
<option value="San Juan">San Juan</option>
<option value="Taguig">Taguig</option>
<option value="Valenzuela">Valenzuela</option>
</select><br />
<input type="text" value='.$row["zipcode"].' class="form-control" placeholder="Zip Code" /> <br />
<label>Birth Date</label>
<br />
<input type="date" value='.$row["birthday"].' class="form-control" readonly />
<br />
<label>Age</label>
<input type="text" value='.$row["age"].' class="form-control" readonly />
<label>Gender</label>
<input type="text" value='.$row["gender"].' class="form-control" readonly />
<br />
<label>Contact Number</label>
<input type="text" value='.$row["contactnumber"].' class="form-control" placeholder="919 123 4567 - sample pattern" maxlength="12"><br />
<label>Parents Name</label>
<input type="text" value='.$row["fathername"].' class="form-control" readonly />
<br />
<input type="text" value='.$row["mothername"].' class="form-control" readonly />
<br />
<button type="submit" id="update" class="btn btn-success">UPDATE1</button>
</form>
';
}
echo $output;
}
?>
I have this problem to put a form validation in the modal form before dismiss-modal or before submitting the data.
In my modal-body I have no form-group instead put the input tags into table td.
So now I am wondering how can I put a form validation in this modal.
I have this html modal:
<div class="modal fade" id="myModalAdd" tabindex="-1" role="dialog" aria-labelledby="myModalLabelAdd" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="false">
×
</button>
<h3 class="modal-title" id="myModalLabelAdd">Add User</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" id="search-form" role="form" method="post">
<table class="table table-bordered" id="edit_table">
<tbody>
<tr>
<td><b>First Name</b></td>
<td><input type="text" required class="typeahead form-control" id="first_name" placeholder="First Name" name="first_name"></td>
</tr>
<tr>
<td><b>Last Name</b></td>
<td><input type="text" required class="typeahead form-control" id="last_name" placeholder="Last Name" name="last_name"></td>
</tr>
<tr>
<td><b>Department</b></td>
<td><input type="text" required class="typeahead form-control" id="department" placeholder="Department" name="department"></td>
</tr>
<tr>
<td><b>Status</b></td>
<td>
<select required class="form-control" id="status">
<option value=""> </option>
<option value="Regular">Regular</option>
<option value="Probationary">Probationary </option>
<option value="Contractual">Contractual</option>
<option value="Trainee">Trainee</option>
</select>
</td>
</tr>
</tbody>
</table>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="close_add_button">
Close
</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" id="create_employee"/>
Create
</button>
</div>
</div>
</div>
</div>
And I have this Jquery:
$(document).ready(function(
{
$( "#create_employee" ).click(function()
{
$.ajax({
url : '<?php echo base_url()?>employee/add_employee',
type: 'POST',
data: {
first_name: $('#first_name').val(),
last_name: $('#last_name').val(),
department: $('#department').val(),
status: $('#status').val()
},
success: function(msg){
var msg = $.parseJSON(msg);
employee_number = msg.EmployeeNo;
employee_first_name = msg.FirstName;
employee_last_name = msg.LastName;
$('#show_employee_number').append(employee_number);
$('#show_employee_first_name').append(employee_first_name);
$('#show_employee_last_name').append(employee_last_name);
$('#alert_success_show').modal('show');
}
});
});
});
Firstly, do not skip the server-side validation!
The following code is just checking for length but you could check for specific values etc.
$( function() {
$( '#search-form' ).on( 'submit', function(e) {
e.preventDefault();
var first = $( '#first_name' ).val();
var last = $( '#last_name' ).val();
if( first.length && last.length ) {
$( this ).submit();
} else {
alert( 'error' );
}
} );
} );
As of your edit:
$(document).ready(function(
{
$( "#create_employee" ).click(function()
{
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var department = $('#department').val();
var status = $('#status').val();
// Validate here
if( !first_name.length ) {
$( '#first_name' ).attr( 'style', 'border:1px solid red;' );
// The "right" way to do it would be
// $( '#first_name' ).addClass( 'error' );
// in css: .error{border:1px solid red;}
}
// etc etc
$.ajax({
url : '<?php echo base_url()?>employee/add_employee',
type: 'POST',
data: {
first_name: first_name,
last_name: last_name,
department: department,
status: status
},
success: function(msg){
var msg = $.parseJSON(msg);
employee_number = msg.EmployeeNo;
employee_first_name = msg.FirstName;
employee_last_name = msg.LastName;
// You are already using json so it would be simple to implement a error-handling-mechanism (pass {"status":"error"} or something equivalent.
$('#show_employee_number').append(employee_number);
$('#show_employee_first_name').append(employee_first_name);
$('#show_employee_last_name').append(employee_last_name);
$('#alert_success_show').modal('show');
}
});
});
});