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
}
Related
So i have this issue trying to pass data from bs modal to form inputs, the logic is when i type in first row and press enter a bs modal pops up and show data from database in a table every row has its respective select button so when i click select the chosen row fills up the input fields in the form but after cloning the next rows of inputs and repeat the steps to fill the form from bs modal this only updates all of the fields with same data
Here is an image of the issue
here's my code i've been stuck here for days..
<script>
$(document).ready(function() {
$(".card").on('keyup', '.live_search', function() {
var input = $(this).val();
if (input != "") {
$.ajax({
type: "POST",
url: "livesearch.php",
data: {
input: input
},
success: function(data) {
$(".searchresult").html(data);
$(".searchresult").css("display", "block");
}
});
} else {
$(".searchresult").css("display", "none");
}
});
$(".add-row").click(function(e) {
e.preventDefault();
$("#show-item").prepend(`<tr>
<input type="hidden" name="id[]">
<td class="col-2">
<div class="input-group input-group-sm">
<a href="#" class="btn btn-danger delete-row"> <i class="fa-solid fa-trash-can"></i>
</a>
<input type="text" class="form-control live_search" name="material_name[]" placeholder="Nombre Material">
</div>
</td>
<td class="col-1">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="measure_one[]">
</div>
</td>
<td class=" col-1">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="measure_two[]">
</div>
</td>
<td class=" col-2">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="unit_measure[]">
</div>
</td>
<td class=" col-1">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="length[]">
</div>
</td>
<td class=" col-1">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="width[]">
</div>
</td>
<td class=" col-1">
<div class="input-group input-group-sm">
<input type="text" class="form-control" name="price[]">
</div>
</td>
</tr>`);
});
// remove product row
$('.card').on('click', '.delete-row', function(evt) {
evt.preventDefault();
$(this).closest('tr').remove();
});
// modal pops up when pressing enter
$('.card').on('keyup', '.live_search', function(e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode == '13') {
// $('.modal').modal('show');
var product = $(this);
$('#insert').modal('show', {
backdrop: 'static',
keyboard: false
}).on('click', '#selected', function(e) {
var id = $(this).attr('data-material-id');
var material = $(this).attr('data-material-name');
var measure_one = $(this).attr('data-material-measure_one');
var measure_two = $(this).attr('data-material-measure_two');
var unit_measure = $(this).attr('data-material-unit_measure');
var length = $(this).attr('data-material-length');
var width = $(this).attr('data-material-width');
var price = $(this).attr('data-material-price');
$(product).closest('tr').find('[name="supplier_id[]"]').val(id);
$(product).closest('tr').find('[name="material_name[]"]').val(material);
$(product).closest('tr').find('[name="measure_one[]"]').val(measure_one);
$(product).closest('tr').find('[name="measure_two[]"]').val(measure_two);
$(product).closest('tr').find('[name="unit_measure[]"]').val(unit_measure);
$(product).closest('tr').find('[name="length[]"]').val(length);
$(product).closest('tr').find('[name="width[]"]').val(width);
$(product).closest('tr').find('[name="price[]"]').val(price);
$('#insert').modal('hide');
});
return false;
}
});
});
</script>
if (mysqli_num_rows($result) > 0) { ?>
<table class="table table-bordered table-striped table-hover table-sm text-center">
<thead class="table-primary">
<tr>
<th>ID</th>
<th>Proveedor</th>
<th>Material</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_assoc($result)) :
$id = $row['supplier_id'];
$supplier = $row['supplier'];
$material = $row['material'];
?>
<tr>
<td><?php echo $id ?></td>
<td><?php echo $supplier ?></td>
<td><?php echo $material ?></td>
<td>
<?php echo '<a href="#" class="btn btn-link" id="selected" datamaterial-id="' . $row['supplier_id'] . '"
data-material-name="' . $row['material'] . '" data-material-measure_one="' . $row['measure_one'] . '"
data-material-measure_two="' . $row['measure_two'] . '" data-material-unit_measure="' . $row['unit_measure'] . '"
data-material-length="' . $row['length'] . '" data-material-width="' . $row['width'] . '"
data-material-price="' . $row['price'] . '">Select</a>';
?>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
This row in the last keyup eventlistener
var product = $(this);
will select every row.
Try this instead:
var product = $(e.target);
Read more about event.target here.
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;
}
?>
Well, this is a crud application which contains add/edit/delete options and I wanted to implement in order to add an other button to view a selected row but my query doesn't work, I am sending an http request with Ajax and am getting the data but the query doesn't work.
Form_view.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" href="dist/bootstrap.min.css" type="text/css" media="all">
<link href="dist/jquery.bootgrid.css" rel="stylesheet" />
<script src="dist/jquery-1.11.1.min.js"></script>
<script src="dist/bootstrap.min.js"></script>
<script src="dist/jquery.bootgrid.min.js"></script>
</head>
<body>
<div class="container">
<div class="">
<h1></h1>
<div class="col-sm-8">
<div class="well clearfix">
<div class="pull-right"><button type="button" class="btn btn-xs btn-primary" id="command-add" data-row-id="0">
<span class="glyphicon glyphicon-plus"></span> Record</button></div></div>
<table id="employee_grid" class="table table-condensed table-hover table-striped" width="60%" cellspacing="0" data-toggle="bootgrid">
<thead>
<tr>
<th data-column-id="id" data-type="numeric" data-identifier="true">Empid</th>
<th data-column-id="employee_name">Name</th>
<th data-column-id="employee_salary">Salary</th>
<th data-column-id="employee_age">Age</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<div id="add_model" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add Employee</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_add">
<input type="hidden" value="add" name="action" id="action" >
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="name" name="name" required></input>
</div>
<div class="form-group">
<label for="salary" class="control-label">Salary:</label>
<input type="text" class="form-control" id="salary" name="salary" required></input>
</div>
<div class="form-group">
<label for="salary" class="control-label">Age:</label>
<input type="text" class="form-control" id="age" name="age" required></input>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_add" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
<div id="edit_model" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Edit Employee</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_edit">
<input type="hidden" value="edit" name="action" id="action">
<input type="hidden" value="0" name="edit_id" id="edit_id">
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="edit_name" name="edit_name">
</div>
<div class="form-group">
<label for="salary" class="control-label">Salary:</label>
<input type="text" class="form-control" id="edit_salary" name="edit_salary"/>
</div>
<div class="form-group">
<label for="salary" class="control-label">Age:</label>
<input type="text" class="form-control" id="edit_age" name="edit_age"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_edit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
<div id="view_model" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">View Employee</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_view">
<input type="hidden" value="view" name="action" id="action">
<input type="hidden" value="0" name="view_id" id="view_id">
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="view_name" name="view_name">
</div>
<div class="form-group">
<label for="salary" class="control-label">Salary:</label>
<input type="text" class="form-control" id="view_salary" name="view_salary"/>
</div>
<div class="form-group">
<label for="salary" class="control-label">Age:</label>
<input type="text" class="form-control" id="view_age" name="view_age"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_view" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$( document ).ready(function() {
var grid = $("#employee_grid").bootgrid({
ajax: true,
rowSelect: true,
post: function ()
{
/* To accumulate custom parameter with the request object */
return {
id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
};
},
url: "response.php",
formatters: {
"commands": function(column, row)
{
return "<button type=\"button\" class=\"btn-success btn-default command-edit\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-edit\"></span></button> " +
"<button type=\"button\" class=\"btn-danger btn-default command-delete\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-trash\"></span></button> " +
"<button type=\"button\" class=\"btn-warning btn-default command-view\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-eye-open\"></span></button>";
}
}
}).on("loaded.rs.jquery.bootgrid", function()
{
/* Executes after data is loaded and rendered */
grid.find(".command-edit").on("click", function(e)
{
//alert("You pressed edit on row: " + $(this).data("row-id"));
var ele =$(this).parent();
var g_id = $(this).parent().siblings(':first').html();
var g_name = $(this).parent().siblings(':nth-of-type(2)').html();
console.log(g_id);
console.log(g_name);
//console.log(grid.data());//
$('#edit_model').modal('show');
if($(this).data("row-id") >0) {
// collect the data
$('#edit_id').val(ele.siblings(':first').html()); // in case we're changing the key
$('#edit_name').val(ele.siblings(':nth-of-type(2)').html());
$('#edit_salary').val(ele.siblings(':nth-of-type(3)').html());
$('#edit_age').val(ele.siblings(':nth-of-type(4)').html());
} else {
alert('Now row selected! First select row, then click edit button');
}
}).end()
//View data
grid.find(".command-view").on("click", function(e)
{
//alert("You pressed edit on row: " + $(this).data("row-id"));
var ele =$(this).parent();
var g_id = $(this).parent().siblings(':first').html();
var g_name = $(this).parent().siblings(':nth-of-type(2)').html();
console.log(g_id);
console.log(g_name);
//console.log(grid.data());//
$('#view_model').modal('show');
if($(this).data("row-id") >0) {
// collect the data
$('#view_id').val(ele.siblings(':first').html()); // in case we're changing the key
$('#view_name').val(ele.siblings(':nth-of-type(2)').html());
$('#view_salary').val(ele.siblings(':nth-of-type(3)').html());
$('#view_age').val(ele.siblings(':nth-of-type(4)').html());
} else {
alert('error');
}
}).end()
//end view data
grid.find(".command-delete").on("click", function(e)
{
var conf = confirm('Delete ' + $(this).data("row-id") + ' items?');
alert(conf);
if(conf){
$.post('response.php', { id: $(this).data("row-id"), action:'delete'}
, function(){
// when ajax returns (callback),
$("#employee_grid").bootgrid('reload');
});
//$(this).parent('tr').remove();
//$("#employee_grid").bootgrid('remove', $(this).data("row-id"))
}
});
});
function ajaxAction(action) {
data = $("#frm_"+action).serializeArray();
$.ajax({
type: "POST",
url: "response.php",
data: data,
dataType: "json",
success: function(response)
{
$('#'+action+'_model').modal('hide');
$("#employee_grid").bootgrid('reload');
}
});
}
$( "#command-add" ).click(function() {
$('#add_model').modal('show');
});
$( "#btn_add" ).click(function() {
ajaxAction('add');
});
$( "#btn_edit" ).click(function() {
ajaxAction('edit');
});
$( "#btn_view" ).click(function() {
ajaxAction('view');
});
});
</script>
response.php
<?php
//include connection file
include_once("connection.php");
$db = new dbObj();
$connString = $db->getConnstring();
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$empCls = new Employee($connString);
switch($action) {
case 'add':
$empCls->insertEmployee($params);
break;
case 'view':
$empCls->viewEmployee($params);
break;
case 'edit':
$empCls->updateEmployee($params);
break;
case 'delete':
$empCls->deleteEmployee($params);
break;
default:
$empCls->getEmployees($params);
return;
}
class Employee {
protected $conn;
protected $data = array();
function __construct($connString) {
$this->conn = $connString;
}
public function getEmployees($params) {
$this->data = $this->getRecords($params);
echo json_encode($this->data);
}
function insertEmployee($params) {
$data = array();;
$sql = "INSERT INTO `employee` (employee_name, employee_salary, employee_age) VALUES('" . $params["name"] . "', '" . $params["salary"] . "','" . $params["age"] . "'); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert employee data");
}
function getRecords($params) {
$rp = isset($params['rowCount']) ? $params['rowCount'] : 10;
if (isset($params['current'])) { $page = $params['current']; } else { $page=1; };
$start_from = ($page-1) * $rp;
$sql = $sqlRec = $sqlTot = $where = '';
if( !empty($params['searchPhrase']) ) {
$where .=" WHERE ";
$where .=" ( employee_name LIKE '".$params['searchPhrase']."%' ";
$where .=" OR employee_salary LIKE '".$params['searchPhrase']."%' ";
$where .=" OR employee_age LIKE '".$params['searchPhrase']."%' )";
}
if( !empty($params['sort']) ) {
$where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." ";
}
// getting total number records without any search
$sql = "SELECT * FROM `employee` ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
if ($rp!=-1)
$sqlRec .= " LIMIT ". $start_from .",".$rp;
$qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot employees data");
$queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch employees data");
while( $row = mysqli_fetch_assoc($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"current" => intval($params['current']),
"rowCount" => 10,
"total" => intval($qtot->num_rows),
"rows" => $data // total data array
);
return $json_data;
}
function updateEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "Update `employee` set employee_name = '" . $params["edit_name"] . "', employee_salary='" . $params["edit_salary"]."', employee_age='" . $params["edit_age"] . "' WHERE id='".$_POST["edit_id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to update employee data");
}
function viewEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "Select employee_name FROM employee WHERE id='".$params["id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to view employee data");
}
function deleteEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "delete from `employee` WHERE id='".$params["id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
}
}
?>
My query to view the data is :
function viewEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "Select employee_name FROM employee WHERE id='".$params["id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to view employee data");
}
Any idea , what should I do to select data from database and print them in html form ?
You are using the wrong variable name from $_REQUEST, you are using ìd when you should use view_id as it is configured in the form hidden field.
Try
function viewEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "Select employee_name FROM employee WHERE id='".$params["view_id"]."'";
$result = mysqli_query($this->conn, $sql) or die("error to view employee data");
echo json_encode($result->fetch_all(MYSQLI_ASSOC));
}
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";
}
}