PHP mySQL query doesn't work - why? - javascript

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'];
}
?>

Related

php server request method is not changing

im following a video to creat JSON CRUD project, after watching the tuto i download the project file, started a server and put the files in it, but it was not working as i expect, after while i found out the problem could be the server quest method, in the vid, teacher click the submit button the method change to POST, but in my script it still apearing GET, how can i fix it ,
<?php
include 'partials/header.php';
function getUsers()
{
return json_decode(file_get_contents(__DIR__ . '/users/part.json'), true);
}
function getUserById($id)
{
$users = getUsers();
foreach ($users as $user) {
if ($user['id'] == $id) {
return $user;
}
}
return null;
}
function createUser($data)
{
$users = getUsers();
$data['id'] = rand(1000000, 2000000);
$users[] = $data;
putJson($users);
return $data;
}
function updateUser($data, $id)
{
$updateUser = [];
$users = getUsers();
foreach ($users as $i => $user) {
if ($user['id'] == $id) {
$users[$i] = $updateUser = array_merge($user, $data);
}
}
putJson($users);
return $updateUser;
}
$userId = 2;
$user = getUserById($userId);
if (!$user) {
include "partials/not_found.php";
exit;
}
$errors = [
'time' => "",
'part' => "",
];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user = array_merge($user, $_POST);
$isValid = validateUser($user, $errors);
if ($isValid) {
$user = updateUser($_POST, $userId);
uploadImage($_FILES['picture'], $user);
header("Location: index.php");
}
}
?>
<div class="container">
<div class="card">
<div class="card-header">
<h3>
<?php if ($user['id']): ?>
Update user <b><?php echo $user['id'] ?></b>
<?php else: ?>
Create new User
<?php endif ?>
</h3>
</div>
<div class="card-body">
<form method="POST" enctype="multipart/form-data"
action="">
<div class="form-group">
<label>Time</label>
<input name="name" value="<?php echo $user['time'] ?>"
class="form-control <?php echo $errors['time'] ? 'is-invalid' : '' ?>">
<div class="invalid-feedback">
<?php echo $errors['time'] ?>
</div>
</div>
<div class="form-group">
<label>part</label>
<input name="username" value="<?php echo $user['part'] ?>"
class="form-control <?php echo $errors['part'] ? 'is-invalid' : '' ?>">
<div class="invalid-feedback">
<?php echo $errors['part'] ?>
</div>
</div>
<button class="btn btn-success">Submit</button>
</form>
</div>
</div>
</div>
the original youtube link the submit part is at 26:00 ish
and my online version is here

AJAX/PHP update function and delete doesn't work

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);
?>

Button click not returning data or initializing modal

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>

cannot view ajax json data tables in php

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;
}
}
}
?>

HTML/JS Contact Form Not Sending or Showing Error Message

I have a contact form that I can't seem to send to my Gmail account. It's different from all the contact forms I've seen because the error message is within the HTML. Nothing happens when the submit button is pressed (no email, no error or success message). Please be gentle for I am somewhat new to PHP. I just need some help please.
The HTML
<div class="contactForm">
<div class="successMessage alert alert-success alert-dismissable" style="display: none">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Thank You! E-mail was sent.
</div>
<div class="errorMessage alert alert-danger alert-dismissable" style="display: none">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Oops! An error occured. Please try again later.
</div>
<form class="liveForm" role="form" action="form/send.php" method="post" data-email-subject="Contact Form" data-show-errors="true" data-hide-form="false">
<fieldset>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Name <span>(Required)</span></label>
<input type="text" required name="field[]" class="form-control">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Email <span>(Required)</span></label>
<input type="email" required name="field[]" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Subject</label>
<input type="text" name="field[]" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Message <span>(Required)</span></label>
<textarea name="field[]" required class="form-control" rows="5"></textarea>
</div>
</div>
</div>
<input type="submit" class="btn btn-primary" value="Send Message">
</fieldset>
</form>
</div>
</div>
The JS
/**
* Contact Form
*/
jQuery(document).ready(function ($) {
"use strict";
$ = jQuery.noConflict();
var debug = false; //show system errors
$('.liveForm').submit(function () {
var $f = $(this);
var showErrors = $f.attr('data-show-errors') == 'true';
var hideForm = $f.attr('data-hide-form') == 'true';
var emailSubject = $f.attr('data-email-subject');
var $submit = $f.find('[type="submit"]');
//prevent double click
if ($submit.hasClass('disabled')) {
return false;
}
$('[name="field[]"]', $f).each(function (key, e) {
var $e = $(e);
var p = $e.parent().find("label").text();
if (p) {
var t = $e.attr('required') ? '[required]' : '[optional]';
var type = $e.attr('type') ? $e.attr('type') : 'unknown';
t = t + '[' + type + ']';
var n = $e.attr('name').replace('[]', '[' + p + ']');
n = n + t;
$e.attr('data-previous-name', $e.attr('name'));
$e.attr('name', n);
}
});
$submit.addClass('disabled');
$f.append('<input class="temp" type="hidden" name="email_subject" value="' + emailSubject + '">');
$.ajax({
url: $f.attr('action'),
method: 'post',
data: $f.serialize(),
dataType: 'json',
success: function (data) {
$('span.error', $f).remove();
$('.error', $f).removeClass('error');
$('.form-group', $f).removeClass('has-error');
if (data.errors) {
$.each(data.errors, function (i, k) {
var input = $('[name^="' + i + '"]', $f).addClass('error');
if (showErrors) {
input.after('<span class="error help-block">' + k + '</span>');
}
if (input.parent('.form-group')) {
input.parent('.form-group').addClass('has-error');
}
});
} else {
var item = data.success ? '.successMessage' : '.errorMessage';
if (hideForm) {
$f.fadeOut(function () {
$f.parent().find(item).show();
});
} else {
$f.parent().find(item).fadeIn();
$f[0].reset();
}
}
$submit.removeClass('disabled');
cleanupForm($f);
},
error: function (data) {
if (debug) {
alert(data.responseText);
}
$submit.removeClass('disabled');
cleanupForm($f);
}
});
return false;
});
function cleanupForm($f) {
$f.find('.temp').remove();
$f.find('[data-previous-name]').each(function () {
var $e = jQuery(this);
$e.attr('name', $e.attr('data-previous-name'));
$e.removeAttr('data-previous-name');
});
}
});
The PHP
<?php
// Contact subject
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Enter your email address
$to ='divagraphicsinc#gmail.com';
$send_contact=mail($to,$subject,$message,$header);
?>
<?php
$ajax = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
$ajax = true;
//we do not allow direct script access
if (!$ajax) {
//redirect to contact form
echo "Please enable Javascript";
exit;
}
require_once "config.php";
//we set up subject
$mail->Subject = isset($_REQUEST['email_subject']) ? $_REQUEST['email_subject'] : "Message from site";
//let's validate and return errors if required
$data = $mail->validateDynamic(array('required_error' => $requiredMessage, 'email_error' => $invalidEmail), $_REQUEST);
if ($data['errors']) {
echo json_encode(array('errors' => $data['errors']));
exit;
}
$html = '<div style="width: 640px; font-size: 11px;">
<h2>' . $mail->Subject . '</h2><ul>
';
foreach ($data['fields'] as $label => $val) {
$html .= '<li>' . $label . ': ' . $val . '</li>';
}
$html .= '</ul></div>';
$mail->setup($html, $_REQUEST, array());
$result = array('success' => 1);
if (!$mail->Send()) {
$result['success'] = 0;
}
echo json_encode($result);
exit;

Categories