PWA custom install - php

Good day all,
I have tried visiting this page: https://web.dev/customize-install/, stackover flow questions and google pages but I still cannot get it write.
I am trying to achieve three things with my PWA app:
Open "cache" and get files with the install event.
Prevent the default PWA from install using "beforeinstallprompt" listener.
Display a bootstrap modal with a "download" button.
When that button is clicked, trigger the "fetch" event which installs the app.
I am able to do 1 and 2.
I am triggering my modal on main.js. I tried in the service worker but I could not.
The download button on the modal also does not
index.php
<div class="modal fade" id="myModal3" role="dialog">
<div class="modal-dialog">
<div class="modal-content" >
<div class="modal-body">
<center><p><i class="fa fa-arrow-circle-down"></i></p>
<h5 style="margin-top:0vh;" >Download App</h5>
<p>Download our super cool app.
<div >
<div class="wrap-login100-form-btn" >
<div class="login100-form-bgbtn"></div>
<button class="login100-form-btn" class="AndaniDownload" id="btnDownloadAppOffline" >
Download </button>
</div>
</div>
</center>
</div>
</div>
</div>
</div>
Main.js
$(document).ready(function(){
$('#myModal3').modal('show');
});
pwabuilder-sw.js
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');
const CACHE = "pwabuilder-page";
const offlineFallbackPage = "offline.html";
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
self.addEventListener('install', async (event) => {
event.waitUntil(
caches.open(CACHE)
.then((cache) => cache.add(offlineFallbackPage))
);
});
if (workbox.navigationPreload.isSupported()) {
workbox.navigationPreload.enable();
}
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
const preloadResp = await event.preloadResponse;
if (preloadResp) {
return preloadResp;
}
const networkResp = await fetch(event.request);
return networkResp;
} catch (error) {
const cache = await caches.open(CACHE);
const cachedResp = await cache.match(offlineFallbackPage);
return cachedResp;
}
})());
}
});
self.addEventListener('beforeinstallprompt', event => {
event.preventDefault();
var button =self.querySelector('.AndaniDownload');
//button.removeAttribute('hidden');
button.addEventListener('click', () => {
event.prompt();
button.setAttribute('disabled', true);
});
});

Related

Modal doesn't display data fetched by axios

I'm new to Vue and trying to display data fetched by axios to a modal.
The problem is the modal doesn't display the data.
I've checked the birthday variable and it does contain the data.
Template
<div class="modal fade" tabindex="-1" id="birthdayModal" role="dialog">
<div class="modal-dialog modal-md modal-dialog-centered" role="document">
<div class="modal-content mx-auto text-center bg-danger text-warning">
<div class="modal-body">
<h1>
HAPPY
<i class="fa-fw fas fa-birthday-cake"></i> BIRTHDAY!
</h1>
<img
:src="'/img/members/' +birthday.dob"
width="250px"
height="250px"
class="img img-responsive"
/>
<h3 class="mt-3">{{birthday.alias_name}}</h3>
<h3>{{birthday.dob}}</h3>
</div>
</div>
</div>
</div>
Script
<script>
export default {
data() {
return {
birthday: [],
}
},
methods: {
birthdayModal() {
axios
.get('api/members/birthday')
.then(res => (this.birthday = res.data))
.then($('#birthdayModal').modal('show'))
console.log('Birthday Data: ', this.birthday)
},
},
created() {},
mounted() {
this.birthdayModal()
console.log('Component mounted.')
},
}
</script>
Controller
public function birthday()
{
$date = Carbon::now();
$member = Member::whereMonth('dob', '=', $date->month)->whereDay('dob', '=', $date->day)->get();
return $member;
}
First of all, welcome to StackOverflow HelloWorld1014!
I had a similar problem in my project, where datepicker.js wouldn't load in my modal. I resolved this by re-initializing the datepicker on modal shown event.
I did something like this:
$('#myModal').on('shown.bs.modal', function (e) {
$('.date').datepicker();
});
Hope that this can lead you in right direction.
As #ambianBeing pointed out, you don't need two .then(...). Instead, you should create another method, and call it in your first .then(...).
For example:
export default {
data(){
return{
birthday:[],
}
},
methods:{
birthdayModal(){
axios.get('api/members/birthday').then(res=>this.parseAndDisplay(res));
},
parseAndDisplay(result){
this.birthday = result.data;
$('#birthdayModal').modal('show'));
console.log("Birthday Data: ", this.birthday);
}
},
created(){
},
mounted() {
this.birthdayModal();
console.log('Component mounted.')
}
}
Hope this helps.

Data not being updated in CI

I am designing CI application and is stuck in ajax query. Basically the function which i have written is taking id as null when save button is pressed even though when i click on edit button it shows its picking up the correct id. Looks like I have some error in function. BELOW IS THE FUNCTION WHICH i HAVE WRITTEN :
public function ajax_update()
{
$this->_validate();
$data = array(
//'firstName' => $this->input->post('firstName'),
//'lastName' => $this->input->post('lastName'),
//'gender' => $this->input->post('gender'),
//'address' => $this->input->post('address'),
//'dob' => $this->input->post('dob'),
//'tid' => $this->input->post('tid'),
'name' => $this->input->post('tname'),
);
$this->transport->update(array('tid' => $this->input->post('tid')), $data);
var_dump( $this->input->post());
echo json_encode(array("status" => TRUE));
}
the update function is
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
View is
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><html lang="en">
<head>
<?php include_once("header.php"); ?>
</head>
<body class="fixed-nav sticky-footer bg-dark">
<!-- Navigation-->
<?php include_once("sidebar.php"); ?>
<div>
<div class="content-wrapper">
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
Home
</li>
<li class="breadcrumb-item active">Manage Transport</li>
</ol>
<!--Button to add Client
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal2"><i class="fa fa-plus" style="color:white"></i> Add Transport</button>-->
<button class="btn btn-success" onclick="add_transport()"><i class="glyphicon glyphicon-plus"></i> Add Transport</button>
<br>
<br>
<!-- Example DataTables Card-->
<div class="card mb-3">
<div class="card-header">
<i class="fa fa-table"></i> View Transport Details</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th style="width:90%;">Transport Detail</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Transport Detail</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.container-fluid-->
<!-- /.content-wrapper-->
</div>
<!-- Modal to add Transport-->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Transport Details</h4>
<button type="button" class="close" data-dismiss="modal">x</button>
</div>
<div class="modal-body">
<!--<form role="form" name="form1" action="<?php echo base_url('search/add_trans'); ?>" method="post" autocomplete="on">-->
<form action="#" id="form" class="form-horizontal">
<div class="row">
<div class="col-md-2">
<label>Transport Details</label>
</div>
<div class="col-md-10" id="new_data">
<textarea name="tname" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<!--<input type="submit" name="submit" class="btn btn-primary" value="Submit">-->
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal Finishes-->
</div>
<?php include_once 'footer.php'; ?>
<script type="text/javascript">
var save_method; //for save method string
var table;
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
function add_transport()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#myModal').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Transport'); // Set Title to Bootstrap modal title
}
function edit_transport(id)
{
//var table = $('#dataTable').DataTable();
// console.log( table.row( id ).data() );
// $("#tid").val(data.tname);
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('transport/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
// $('[name="id"]').val(data.id);
//$('[name="tid"]').val(data.tid);
$('[name="tname"]').val(data.tname);
// $('[name="firstName"]').val(data.firstName);
//$("#tid").val(data.tname);
//alert(data.tname);
// $('[name="lastName"]').val(data.lastName);
// $('[name="gender"]').val(data.gender);
// $('[name="address"]').val(data.address);
// $('[name="dob"]').datepicker('update',data.dob);
// $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('#myModal').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Transport'); // Set title to Bootstrap modal title
// new_data
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea> <input type="text" name="row_id" value="'+id+'" readonly hidden >');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
//function reload_table()
//{
// table.ajax.reload(null,false); //reload datatable ajax
//}
function reload_table() {
table.api().ajax.reload(null, false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('transport/ajax_add')?>";
} else {
url = "<?php echo site_url('transport/ajax_update')?>";
}
// console.log($('#form').serialize());
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#myModal').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea> ');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea>');
}
});
}
function delete_transport(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('transport/ajax_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#myModal').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
function reload_table()
{
//console.log(table);
table.api().ajax.reload( null, false );
}
$(document).ready(function() {
//datatables
table = $('#dataTable').dataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('transport/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
</script>
</body>
</html>
Any pointers please ?

How do I customize import file in OroCRM

I want to add a import button in my app to import a file to sever, after that I’ll handle the file by myself. It means I just want to reuse import button and import dialog, but in OroCRM, I have to use processor and importing sevice serve by OroCRM. How can I just use import button and import dialog without using the way OroCRM import file?
Thanks a lots. :)
If you don't want to use OroCrm import. Then you can do it like this process. It might help you.
Follow these steps.
Step.1(index.html.twig)
{% set html %}
{{ UI.dropdownItem({
'path': '#',
'aCss': 'import',
'title': 'Import File',
'label': 'Import File',
'iCss': 'fa-download'
}) }}
{% endset %}
{{ UI.dropdownButton({
'label': 'Import File',
'iCss': 'fa-download',
'aCss': 'pull-right',
'html': html
}) }}
Step.2(in index.html.twig). Create modal section.
{# Modal popup starts here #}
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title file-add-h">Select Import File</h4>
<h4 class="modal-title file-report-h" style="display:none;">Import File Report</h4>
</div>
<div class="modal-body">
<div id="file-add">
<input type="file" name="File Upload" id="txtFileUpload" accept=".csv" />
<button type="button" class="btn btn-info btn-lg pull-right submit-file">Submit</button>
</div>
<div id="file-report" style="display:none;"> </div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
{# modal popup end here #}
Step.3(in javascript file)
{# javascript #}
// Set the target
$(document).ready(function () {
$(".import").attr('data-toggle', 'modal');
$(".import").attr('data-target', '#myModal');
});
// Method that checks that the browser supports the HTML5 File API
function browserSupportFileUpload() {
var isCompatible = false;
if (window.File && window.FileReader && window.FileList && window.Blob) {
isCompatible = true;
}
return isCompatible;
}
function importFile(flag) {
if (!browserSupportFileUpload()) {
alert('The File APIs are not fully supported in this browser!');
} else {
var data = null;
var file = $('#txtFileUpload')[0].files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function (event) {
var csvData = event.target.result;
data = $.csv.toArrays(csvData);
if (data && data.length > 0) {
//console.log(data);
var jsonArr = [];
for (var i = 0; i < data.length; i++) {
if (i !== 0)
{
var json_obj = {};
for (var j = 0; j < data[0].length; j++) {
json_obj[data[0][j]] = data[i][j];
}
jsonArr.push(json_obj);
}
}
$.ajax({
url: '{{path('your_import_controller_path')}}',
type: 'POST',
data: {'data': JSON.stringify(jsonArr), 'flag': flag},
success: function (response, status, xhr) {
alert(response);
}
});
} else {
alert('No data to import!');
}
};
reader.onerror = function () {
alert('Unable to read ' + file.fileName);
};
}
$('#txtFileUpload').val("");
$("#file-report").html("");
$(".file-add-h").show();
$(".file-report-h").hide();
$("#file-add").show();
$("#file-report").hide();
$('#myModal').modal('toggle');
}
$(document).on("click", ".submit-file", function () {
importFile(0);
});
$(document).on("click", ".inser-file", function () {
importFile(0);
});
{# Then in your controller action #}
/**
* #Route("/import",name="your_import_controller_path")
*/
public function importDataAction(Request $request)
{
$import_data = $request->request->get('data');
$flag = $request->request->get('flag');
$import_arr = json_decode($import_data);
$em = $this->container->get('doctrine')->getManager();
$message = '';
foreach ($import_arr as $i) {
$tbl = new EntityTableName(); // in which entity you want to insert
$tbl->setCode($i->CodeA); // CodeA is columns from excel
$em->persist($tbl);
}
$em->flush();
echo 'Records Imported Successfully';
exit;
}

jQuery Load function not loading inside a div but loads new page

I have following html markup:
<button class="btn btn-success" id="search"><span class="glyphicon glyphicon-search"></span> Search</button>
<div class="row text-center" style="margin-top: 50px;">
<div class="col-md-12">
<div id="content-area"></div>
</div>
</div>
I want to load a page.php inside #content-area. This is the jQuery I used for this:
$("#search").click(function(){
$("#content-area").load("page.php");
});
The problem is page.php is not loading inside #content-area but it loads as a new page itself. I want page.php to load inside #content-area. Please help.
//you have to make ajax call to get content without page load.
$("#search").click(function(){
$.ajax({
url: 'page.php', // point to server-side PHP script
dataType: 'json', // what to expect back from the PHP script, if anything
type: 'POST',
success: function (data) {
if (data.status === 'success')
{
$("#content-area").html(data);
}
else if (data.status === 'error')
{
alert(data.message);
}
},
error: function (e) {
return false;
Msg.show('Something went wrong, Please try again!','danger', 7000);
}
});
});
I have tried below code its working fine for me.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<button class="btn btn-success" id="search"><span class="glyphicon glyphicon-search"></span> Search</button>
<div class="row text-center" style="margin-top: 50px;">
<div class="col-md-12">
<div id="content-area"></div>
</div>
</div>
<script>
$("#search").click(function(){
$("#content-area").load("test1.php");
});
</script>

Php Yii: Detecting changes in forms

I am implementing an edit feature for 3 related models..
and to divide the work .. i implemented 3 tabs using bootstrap extensions...now each tab contains textfields, drop downs, etc., now the contents of the text and the dropdowns, radio buttons etc are pre-loaded for the user; since this is an edit feature, it would be convenient for them if their choices were retained, and that they only need to change specific fields that they want to change without really having to re-do the entire form.
Each form in a tab has its own independent "Save" button that saves the model and then switches to the next tab after refresh.
Here's what i'm trying to do, (and quite having a hard time )..
I'm sure everybody has a facebook account here.. remember when you try to write a status update, or when you are chatting with somebody and then you click a button that redirects to another page?
Then a dialog box (or modal?) will alert you that you haven't finished your post yet, and that it gives you an option whether to leave or to stay in the page?
Similar to what i'm trying to do; i'm trying to alert the user if he/she wants to save or discard his changes (if there are changes made) before he switches to another tab.. I really have no idea how to do this..
on how the widget works..is abstracted (or i haven't found it yet atleast), and unlike in java where i can easily search for "Events" onChange() or something..i'm new to php and yii.. any idea ,on how to do it, what to use, or a sample code will be really helpful guys.. Thanks a lot!
You could use a global var like var saved=false to check your form has been saved.
To catch the on change of your forms:
$('form :input').change(function(){saved=false;});
See: jquery get all form elements: input, textarea & select
When the user left the page you could fire a beforeunload:
$(window).on('beforeunload', function() {
if(!saved) return 'Leave page?';
});
See also:
Dialog box runs for 1 sec and disappears?
catching beforeunload confirmation canceled?
To catch the tab change you could use a default confirm (http://www.w3schools.com/js/js_popup.asp):
$('#myTab a').click(function (e)
{
e.preventDefault();
if(!saved)
{
if(confirm('Leave tab?'))
{
$(this).tab('show');
}
}
else
{
$(this).tab('show');
}
});
Or you could try to build your own confirm dialog:
Note it seems you can't catch the window beforeunload but for the tab change:
html:
<ul class="nav nav-tabs" id="myTab">
<li class="active">Home</li>
<li>Profile</li>
<li>Messages</li>
<li>Settings</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">...</div>
<div class="tab-pane" id="profile"><form><input type="text"><input type="submit" class="btn btn-success"></form></div>
<div class="tab-pane" id="messages">...</div>
<div class="tab-pane" id="settings">...</div>
</div>
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<p>Form not saved!</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button id="leavetab" class="btn btn-primary">Leave tab</button>
</div>
</div>
javascript:
var saved = true;
var confirmed = false;
var thistab = null;
function checksave()
{
return saved;
}
$(function () {
$('#myTab a:last').tab('show');
$('#myTab a').click(function (e)
{
e.preventDefault();
thistab = $(this);
if(!checksave()){ $('#myModal').modal(); return false;}
thistab = null;
if(saved || confirmed)
{
$(this).tab('show');
saved = false;
confirmed = false;
}
});
//see: https://stackoverflow.com/questions/12862601/jquery-get-all-form-elements-input-textarea-select
$('form :input').change(function(){saved=false; confirmed = false;});
$('#myModal').on('hidden', function () {
return false;
});
// modal click set confirmed to true
$('#leavetab').click(function()
{
{
$('#myModal').modal('hide');
thistab.tab('show');
saved = false;
confirmed = false;
}
});
});

Categories