Download .js file with php - javascript

I got following files:
index.php:
<html>
<head>
<title>Admin Panel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<h2 align="center">Admin Panel</a></h2>
<br />
<div align="right">
<button type="button" name="create_folder" id="create_folder" class="btn btn-success">Get current file</button>
</div>
<br />
<div class="table-responsive" id="folder_table">
</div>
</div>
</body>
</html>
<div id="uploadModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Upload File</h4>
</div>
<div class="modal-body">
<form method="post" id="upload_form" enctype='multipart/form-data' action="upfile.php">
<p>Select Js File
<input type="file" name="upload_file" accept=".js"/></p>
<br />
<input type="hidden" name="hidden_folder_name" id="hidden_folder_name" />
<input type="submit" name="upload_button" class="btn btn-info" value="Upload" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="filelistModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">File List</h4>
</div>
<div class="modal-body" id="file_list">
</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() {
load_folder_list();
function load_folder_list() {
var action = "fetch";
$.ajax({
url: "action.php",
method: "POST",
data: {
action: action
},
success: function(data) {
$('#folder_table').html(data);
}
});
}
$(document).on('click', '.upload', function() {
var folder_name = $(this).data("name");
$('#hidden_folder_name').val(folder_name);
$('#uploadModal').modal('show');
});
$('#upload_form').on('submit', function() {
$.ajax({
url: "upfile.php",
method: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
});
});
$(document).on('click', '.view_files', function() {
var folder_name = $(this).data("name");
var action = "fetch_files";
$.ajax({
url: "action.php",
method: "POST",
data: {
action: action,
folder_name: folder_name
},
success: function(data) {
$('#file_list').html(data);
$('#filelistModal').modal('show');
}
});
});
$(document).on('click', '.remove_file', function() {
var path = $(this).attr("id");
var action = "remove_file";
$.ajax({
url: "action.php",
method: "POST",
data: {
path: path,
action: action
},
success: function(data) {
$('#filelistModal').modal('hide');
load_folder_list();
}
});
});
});
</script>
action.php:
<?php
function format_folder_size($size)
{
if ($size >= 1073741824) {
$size = number_format($size / 1073741824, 2) . ' GB';
} elseif ($size >= 1048576) {
$size = number_format($size / 1048576, 2) . ' MB';
} elseif ($size >= 1024) {
$size = number_format($size / 1024, 2) . ' KB';
} elseif ($size > 1) {
$size = $size . ' bytes';
} elseif ($size == 1) {
$size = $size . ' byte';
} else {
$size = '0 bytes';
}
return $size;
}
function get_folder_size($folder_name)
{
$total_size = 0;
$file_data = scandir($folder_name);
foreach ($file_data as $file) {
if ($file === '.' or $file === '..') {
continue;
} else {
$path = $folder_name . '/' . $file;
$total_size = $total_size + filesize($path);
}
}
return format_folder_size($total_size);
}
if (isset($_POST["action"])) {
if ($_POST["action"] == "fetch") {
$folder = array_filter(glob('*'), 'is_dir');
$output = '
<table class="table table-bordered table-striped">
<tr>
<th>Folder Name</th>
<th>Total File</th>
<th>Size</th>
<th>Upload File</th>
<th>View Uploaded File</th>
</tr>
';
if (count($folder) > 0) {
foreach ($folder as $name) {
$output .= '
<tr>
<td>' . $name . '</td>
<td>' . (count(scandir($name)) - 2) . '</td>
<td>' . get_folder_size($name) . '</td>
<td><button type="button" name="upload" data-name="' . $name . '" class="upload btn btn-info btn-xs">Upload File</button></td>
<td><button type="button" name="view_files" data-name="' . $name . '" class="view_files btn btn-default btn-xs">View Files</button></td>
</tr>';
}
} else {
$output .= '
<tr>
<td colspan="6">No Folder Found</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
if ($_POST["action"] == "fetch_files") {
$file_data = scandir($_POST["folder_name"]);
$output = '
<table class="table table-bordered table-striped">
<tr>
<th>File Name</th>
<th>Download</th>
</tr>
';
foreach ($file_data as $file) {
if ($file === '.' or $file === '..') {
continue;
} else {
$script = 'download.php';
$downloadlink = $script . '/' . $_POST["folder_name"] . '/' . $file;
$path = $_POST["folder_name"] . '/' . $file;
$output .= '
<tr>
<td contenteditable="false" data-folder_name="' . $_POST["folder_name"] . '" data-file_name = "' . $file . '" class="change_file_name">' . $file . '</td>
<td><button name="remove_file" class="remove_file btn btn-danger btn-xs" id="' . $path . '">Get it</button></td>
</tr>
';
}
}
$output .= '</table>';
echo $output;
}
function test()
{
if ($_POST["action"] == "remove_file") {
if (file_exists($_POST["path"])) {
readfile($_POST["path"]);
}
}
}
}
download.php
<?php
//file path in server
$path = $_POST["folder_name"] . '/' . $file;
// check if file exist in server
if (file_exists($path)) {
header("Cache-Control: public");
header('Content-Description: File Transfer');
header('Content-Type: application/x-javascript');
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Content-Length: ' . filesize($path));
// Clear output buffer
flush();
readfile($path);
exit();
} else {
echo "File not found.";
}
?>
The Problem now is that when I download the javascript files from my server then it downloads the file but without any content in it. On the server the files have content in it, so it must be a problem while downloading it from the website. I think the problem is at the download.php but in my opinion the syntax are correct. It could be also a problem at the remove_file fucntion in the index.php and action.php. See $(document).on('click', '.remove_file', function() in index.php

I'd say you need html for this. I don't know if you can use PHP for this. If you really need to use PHP:
<?php
echo "<a href='file.js' download>Click Here to Download</a>";
?>
Essentially, what this does is create a link, in which the user clicks to download the file.

Related

get the ID of the the table I click and send it to popup box

and im stuck of what im doing right now,
anyone can help me what i lacked in my code? I planning to have a clickable table with column and row from database, then if a user click the id, a pop up will display with an Action choices like delete, print and update,.
The problem on my code is, it didn't read the ID of the row I click, it always a empty.
here is my code
$result = $pdo->query("SELECT * FROM tblrv order by ID desc);
if ($result->rowCount() > 0) {
while($row = $result->fetch(PDO::FETCH_BOTH)){
<tr id="' . $row["ID"] . '">
<td><a onclick="openForm()">'. $row["ID"] .'</a></td>
<td>'. $row["RVID"] .'</td>
<td>'. $row["RVDate"] .'</td>
<td>'. $row["Name"] .'</td>
<td>'. $row["ContactNumber"] .'</td>
</tr>
}
}
This is my pop up form
<div class="loginPopup">
<div class="formPopup" id="popupForm">
<div class="formContainer">
<h2>Choose your Action</h2>
<div id="<?php echo $row["ID"]?>" >
<a class="btn btn-danger btn-sm remove">Delete</a>
</div>
<a class="btn btn-success pull-right" href="/api/print.php/?id="<?php echo $row['ID']; ?>" target="_blank"><span class="glyphicon glyphicon-print"></span> Print</a>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</div>
</div>
</div>
and this is the js
<script>
function openForm() {
document.getElementById("popupForm").style.display = "block";
}
function closeForm() {
document.getElementById("popupForm").style.display = "none";
}
</script>
this is the js for the delete
<script type="text/javascript">
$(".remove").click(function(){
var id = $(this).parents("div").attr("id");
if(confirm('Are you sure to Remove Invoice #' + id + ' ')) {
$.ajax({
url: "/api/delete.php",
type: 'GET',
data: {id: id},
error: function() {
alert('Something is wrong');
},
success: function(data) {
$("#"+id).remove();
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
);
}
});
}
});
</script>
The result is always empty,. I hope someone can give me an idea Thanks
Btw, this is working if I manually put the ID and remove the = $row(ID) condition in them, but ofcurz it not the thing I want.

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

How to call Ajax in tpl(template) file OpenCart version 2.3

How to call ajax call in tpl template opencart version 2.3
I have api controller with data and that data I need to post in template(tpl) file. Template file is tpl extension , I need open script tag but I don't know how do it in tpl file and how to target endpoint with function? I provide my code. In controller I have api folder and file reifenmontage and function get_marka_data()...How I target this data in tpl file? I know tpl is only for show data but I must do on this way :/
public function get_marka_data() {
$query = $this->db->query("
SELECT mo.marka
FROM " . DB_PREFIX . "model mo
GROUP BY mo.marka
")->rows;
$data = array_map(function($row){
return array('value'=>$row['marka'],'label'=>$row['marka']);
}, $query);
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($data));
var_dump($data);
}
<script type="text/javascript"><!--
$('#button-getdata').on('click', function() {
$.ajax({
url: 'index.php?route=extension/module/reifenmontage/get_marka_data',
type: 'post',
data: $('#reifenmontage-input select, #reifenmontage-input input'),
dataType: 'json',
beforeSend: function() {
$('#reifenmontage-input').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" /> <?php echo $text_wait; ?></div>');
},
success: function(json) {
$('.success, .warning, .attention, information, .error').remove();
if (json['success']) {
html = "<!-- Retrieved data -->\n";
for (i in json['success']) {
var element = json['success'][i];
console.log(element);
html += "\t<tr><td>" + element['label'] + "</td><td align=\"right\">" + element['value'] + "</td></tr>\n";
}
$('#reifenmontage-output').html(html);
}
}
});
});
//--></script>
<?php if($heading_title) { ?>
<h2><?php echo $heading_title; ?></h2>
<?php } ?>
<h2><?php echo $description_title; ?></h2>
<?php echo $description; ?>
<div id="reifenmontage-input" class="reifenmontage-input">
<form id="reifenmontage-input" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="control-label" for="datum"><?php echo $entry_begin_period; ?></label>
<div class="input-group date">
<input type="text" name="datum" value="<?php echo $current_day . '-' . $current_month . '-' . $current_year; ?>" data-date-format="DD-MM-YYYY" id="datum" class="form-control" />
<span class="input-group-btn">
<button class="btn btn-default" type="button"><i class="fa fa-calendar"></i></button>
</span></div>
</div>
<div class="form-group">
<label class="control-label" for="entry-cyclus"><?php echo $entry_cyclus; ?></label>
<select name="cyclus" id="entry-cyclus" class="form-control">
<option value=""><?php echo $text_select; ?></option>
<?php
for ($i=20;$i<43;$i++) {
if ($i == 28) {
?>
<option value="<?php echo $i; ?>" selected="selected"><?php echo $i; ?></option>
<?php
} else {
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
?>
</select>
</div>
<div class="buttons">
<div class="pull-right">
<input type="button" value="<?php echo $button_create; ?>" id="button-getdata" class="btn btn-default" />
</div>
</div>
</fieldset>
</form>
</div>
<div id="reifenmontage-output"></div>
And for de php-function, change te last part into:
$json = array();
if ($data) {
$json['succes'] = $data;
} else {
$json['error'] = 'Sorry, no data !';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
Example for form, output id and script to retrieve data from controller in extension/module
In controller/api/reifenmontage.php:
<?php
class ControllerApiReifenmontage extends Controller {
private $error = array();
public function get_marka_data() {
$json = array();
if (isset($this->request->post['marka'])) {
$marka_data_query = $this->db->query("SELECT mo.model FROM " . DB_PREFIX . "model mo WHERE mo.marka='" . $this->request->post['marka'] . "'");
$marka_data = $marka_data_query->rows;
$json['succes'] = $marka_data;
} else {
$json['error'] = 'Sorry, no data !';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
Form with script:
<div id="reifenmontage-input" class="reifenmontage-input">
<form id="reifenmontage-input" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group required">
<label class="col-sm-4 control-label" for="input-marka">Marka</label>
<div class="input-group col-sm-8">
<select name="marka" id="input-marka" class="form-control">
<option value="0">Select ...</option>
<option value="AJP">AJP</option>
<option value="APOLO">APOLO</option>
<option value="APRILIA">APRILIA</option>
<!-- All stored marka's -->
</select>
</div>
</div>
</fieldset>
<div class="buttons">
<div class="pull-right">
<button type="button" class="btn btn-primary" id="button-getdata" data-loading-text="Loading ...">Get Data</button>
</div>
</div>
</form>
</div>
<div class="col-xs-12 col-sm-3" style="margin-right:30px;">
<div class="row">
<select class="form-control" id="result">
</select>
</div>
</div>
<script type="text/javascript"><!--
$('#button-getdata').on('click', function() {
$.ajax({
url: 'index.php?route=api/reifenmontage/get_marka_data',
type: 'post',
data: $('#reifenmontage-input select'),
dataType: 'json',
beforeSend: function() {
$('.success, .warning, .attention, information, .error').remove();
$('#result').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" />Please wait ...</div>');
},
success: function(json) {
if (json['error']) {
$('#result').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" />' + json['error'] + '</div>');
}
if (json['success']) {
for (i in json['success']) {
var element = json['success'][i];
//console.log(element);
html = "\t<option value=\""+ element['model'] + "\">" + element['model'] + "</option>\n";
$('#result').append(html);
}
}
}
});
});
//--></script>
New controller/api/reifenmontage.php
<?php
class ControllerApiReifenmontage extends Controller {
private $error = array();
public function get_markas() {
$json = array();
$markas_query = $this->db->query("SELECT marka FROM " . DB_PREFIX . "model GROUP BY marka");
$markas_data = $markas_query->rows;
if ($markas_data) {
$json['success'] = $markas_data;
} else {
$json['error'] = 'Sorry, no data !';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function get_marka_data() {
$json = array();
if (isset($this->request->post['marka'])) {
$marka_data_query = $this->db->query("SELECT mo.model FROM " . DB_PREFIX . "model mo WHERE mo.marka='" . $this->request->post['marka'] . "'");
$marka_data = $marka_data_query->rows;
$json['success'] = $marka_data;
} else {
$json['error'] = 'Sorry, no data !';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
And new script on template / form:
<script type="text/javascript"><!--
function getMarkaData() {
$.ajax({
url: 'index.php?route=api/reifenmontage/get_marka_data',
type: 'post',
data: $('#reifenmontage-input select'),
dataType: 'json',
beforeSend: function() {
$('.success, .warning, .attention, information, .error').remove();
},
success: function(json) {
if (json['error']) {
$('#result').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" />' + json['error'] + '</div>');
}
if (json['success']) {
$('#result2').html('');
for (i in json['success']) {
var element = json['success'][i];
//console.log(element);
html = "\t<option value=\""+ element['model'] + "\">" + element['model'] + "</option>\n";
$('#result2').append(html);
}
}
}
});
}
function getMarkas() {
$.ajax({
url: 'index.php?route=api/reifenmontage/get_markas',
dataType: 'json',
type: 'post',
beforeSend: function() {
$('.success, .warning, .attention, information, .error').remove();
},
success: function(json) {
if (json['success']) {
for (i in json['success']) {
var element = json['success'][i];
html = "\t<option value=\""+ element['marka'] + "\">" + element['marka'] + "</option>\n";
$('#result').append(html);
}
getMarkaData();
}
}
});
}
//--></script>
<script type="text/javascript">
let selectItem = document.getElementById('pneu');
let additionalRow = document.getElementById('additionalRow');
function checkSelected() {
if (selectItem.selectedIndex == "1") {
additionalRow.style.display = 'none';
} else {
additionalRow.style.display = 'flex';
getMarkas();
}
}
$('#result').on('change', function() {
getMarkaData();
});
if ($('#pneu').val() != '1') {
getMarkas();
}
</script>

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

Categories