I'm using datatables and after post I want to refresh the page after changes in the database are done. But for now it's pretty much random if the page refreshes before or after the database is updated. I also tried to add 'success:' to the callback function but this doesn't help.
Script for datatables projects.php:
<script> $(document).ready( function () {
var projects = $('#projects').DataTable({
paging:true, dom: 'Blfrtip', colReorder: true, select: {style: 'single'},
buttons: [
{
text: 'Edit',
action: function () {
$projectID = $(projects.row('.selected').node()).data('id');
if ($projectID === undefined)
{
alert("Please select a project.");
} else {
window.location.href = "../projects/editProject.php?projectID=" + $projectID;
}
}
},
{
text: 'Add',
action: function () {
window.location.href = "../projects/addProject.php";
}
},
{
text: 'Delete',
action: function () {
$projectID = $(projects.row('.selected').node()).data('id');
if ($projectID === undefined)
{
alert("Please select a project.");
} else {
$.post("../projects/deleteProject.php",
{
projectID: $projectID,
function() {
window.location.reload(true);
}
}
);
}
}
}
] }); } ); </script>
deleteProject.php:
<?php
require("../database/dbService.php");
require("../projects/deleteProjectService.php");
session_start();
$connection = connectToDB();
// check if input data is set
if (!isset($_POST['projectID'])){
header("Location: ../projects/projects.php");
exit;
}
// input data
$projectID = $_POST['projectID'];
deleteProject($connection, $projectID);
$_SESSION['message'] = "The project has been deleted!";
?>
You placed callback function in the wrong place, it should have been:
$.post(
"../projects/deleteProject.php",
{ projectID: $projectID },
function(){ window.location.reload(true); }
);
Related
How can I run the following woodmart theme jquery script based on a php condition?
The jQuery script here asks for age validation on the website and restricts the page if there is no validation.
I just want to use this code for some category products but I don't know how to add condition to jQuery script and I am bad at javascript.
(function($) {
woodmartThemeModule.ageVerify = function() {
if ( typeof Cookies === 'undefined' ) {
return;
}
if ( woodmart_settings.age_verify !== 'yes' || Cookies.get('woodmart_age_verify') === 'confirmed') {
return;
}
$.magnificPopup.open({
items : {
src: '.wd-age-verify'
},
type : 'inline',
closeOnBgClick : false,
closeBtnInside : false,
showCloseBtn : false,
enableEscapeKey: false,
removalDelay : 500,
tClose : woodmart_settings.close,
tLoading : woodmart_settings.loading,
callbacks : {
beforeOpen: function() {
this.st.mainClass = 'mfp-move-horizontal wd-promo-popup-wrapper';
}
}
});
$('.wd-age-verify-allowed').on('click', function(e) {
e.preventDefault();
Cookies.set('woodmart_age_verify', 'confirmed', {
expires: parseInt(woodmart_settings.age_verify_expires),
path : '/',
secure : woodmart_settings.cookie_secure_param
});
$.magnificPopup.close();
});
$('.wd-age-verify-forbidden').on('click', function(e) {
e.preventDefault();
$('.wd-age-verify').addClass('wd-forbidden');
});
};
$(document).ready(function() {
woodmartThemeModule.ageVerify();
});
})(jQuery);
UPDATE
The code here is working now, echo is no more, I also added 999 as priority and it works fine that way.
<?php
add_action( 'wp_footer', 'add_age_verify', 999 );
function add_age_verify() {
if( is_product_category( array( 4201, 4500, 4300 ) ) ) {
?>
<script type="text/javascript"> (function($) {
woodmartThemeModule.ageVerify = function() {
if ( typeof Cookies === 'undefined' ) {
return;
}
if ( woodmart_settings.age_verify !== 'yes' || Cookies.get('woodmart_age_verify') === 'confirmed') {
return;
}
$.magnificPopup.open({
items : {
src: '.wd-age-verify'
},
type : 'inline',
closeOnBgClick : false,
closeBtnInside : false,
showCloseBtn : false,
enableEscapeKey: false,
removalDelay : 500,
tClose : woodmart_settings.close,
tLoading : woodmart_settings.loading,
callbacks : {
beforeOpen: function() {
this.st.mainClass = 'mfp-move-horizontal wd-promo-popup-wrapper';
}
}
});
$('.wd-age-verify-allowed').on('click', function(e) {
e.preventDefault();
Cookies.set('woodmart_age_verify', 'confirmed', {
expires: parseInt(woodmart_settings.age_verify_expires),
path : '/',
secure : woodmart_settings.cookie_secure_param
});
$.magnificPopup.close();
});
$('.wd-age-verify-forbidden').on('click', function(e) {
e.preventDefault();
$('.wd-age-verify').addClass('wd-forbidden');
});
};
$(document).ready(function() {
woodmartThemeModule.ageVerify();
});
})(jQuery); </script>
<?php
}
}
You can send a JQuery ajax call to the php script, the php script then sends it back to the javascript file and then you can easily use the variable within javascript.
$.ajax({
url: 'path/to/your/php/file',
type: 'get',
success: (res) => {
//do things when you get the response
},
error: (err) => {
//do things when you get the error, error is optional
},
})
or you can even simplify it
$.get('url/to/your/script', (res) => {
//do things with the response
})
I copied the jQuery script into the child theme and then <script src='/wp-content/themes/woodmart-child/js/scripts/global/ageVerify.js'></script> to show the jQuery script, while doing this I added the conditions with PHP and now it works fine.
The final version of the code with PHP is like this.
<?php
add_action( 'wp_footer', 'add_age_verify_jquery', 999 );
function add_age_verify_jquery() {
if ( has_term(array('jacket', 'fridge', 'hats', 'magic wand'), 'product_cat')) {
?>
<script src='/wp-content/themes/woodmart-child/js/scripts/global/ageVerify.js'></script>
<?php
}
}
?>
could someone help me with one problem? I want to add a process bar when you waiting for a response from the server (Django 3.x).
Step to reproduce:
On the page 'A' we have the form.
Enter data to form.
Submit POST request by clicking to button on the page 'A'.
Waiting for getting the result on the page 'A'.
Get the result on the page 'A'.
So, I want to add process bar after 4th and before 5th points on the page 'A'. When you will get the result on the page 'A' it should disappear.
Python 3.7
Django 3.x
You can use nprogress, it's a library used for progress bars. Use this inside the interceptor where you can config it for displaying only when request is in progress until finished.
There are lots of ways to do this. I think using jquery would be easier. Basically you just need to prevent submitting the page and do an Ajax request to server. something like
<script type='text/javascript'>
$(document).ready(function () {
$("form").submit(function (e) {
// prevent page loading
e.preventDefault(e);
$('#loadinAnimation').show();
// preapre formdata
$.ajax({
type: "yourRequestType",
url: "yourUrlEndpoint",
data: formdata,
success: function (data) {
$('#loadinAnimation').hide();
// do rest of the work with data
}
});
});
});
</script>
and show appropriate loading animation in your html part
<div id='loadinAnimation' style='display:none'>
<div>loading gif</div>
</div>
You can also do it using UiKit Library in Javascript on your Django Template Page.
Below code is when a file is Uploaded
In your template file (template.html)
<body>
..
<form>
<progress id="js-progressbar" class="uk-progress" value="0" max="100" hidden></progress>
...
<div class="uk-alert-danger uk-margin-top uk-hidden" id="upload_error" uk-alert></div>
...
</form>
</head>
<script type="text/javascript">
$(document).ready(function(){
var bar = document.getElementById('js-progressbar');
UIkit.upload('.js-upload-list', {
url: '',
name : "customer-docs",
params :{
"csrfmiddlewaretoken":"{{csrf_token}}"
},
method : "POST",
concurrent:1,
allow:'*.(csv|xlsx)',
beforeSend: function (environment) {
console.log('beforeSend', arguments);
// The environment object can still be modified here.
// var {data, method, headers, xhr, responseType} = environment;
},
beforeAll: function (args,files) {
console.log('beforeAll', arguments);
},
load: function () {
console.log('load', arguments);
},
error: function (files) {
console.log("---------------")
},
complete: function () {
console.log('complete', arguments);
},
loadStart: function (e) {
console.log('loadStart', arguments);
bar.removeAttribute('hidden');
bar.max = e.total;
bar.value = e.loaded;
},
progress: function (e) {
console.log('progress', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
loadEnd: function (e) {
console.log('loadEnd', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
completeAll: function (data) {
console.log('completeAll', arguments);
console.log('completeAll', data);
let redirect_loc = ""
setTimeout(function () {
bar.setAttribute('hidden', 'hidden');
}, 1000);
// This is the response from your POST method of views.py
data.responseText = JSON.parse(data.responseText)
if(data.responseText.status == 201){
// swal is another library to show sweet alert pop ups
swal({
icon: data.responseText.status_icon,
closeOnClickOutside: true,
text: data.responseText.message,
buttons: {
Done: true
},
}).then((value) => {
switch (value) {
case "Done":
window.location.href = ""
break;
}
});
}
else if(data.responseText.status == 500){
swal({
icon: data.responseText.status_icon,
closeOnClickOutside: true,
text: data.responseText.message,
buttons: {
Ok: true
},
}).then((value) => {
switch (value) {
case "Ok":
window.location.href = ""
break;
}
});
}
}
});
// This block of code is to restrict user to upload only specific FILE formats (below example is for CSV & XLSX files)
(function() {
var _old_alert = window.alert;
window.alert = function(e) {
console.log(e)
if(e.includes("csv|xlsx") || e.includes("Invalid file type")) {
$("#upload_error").html("Invalid file format. Valid formats are CSV, XLSX").removeClass('uk-hidden')
}else if(e.includes("Internal Server Error")) {
$("#upload_error").html("Internal Server Error Kindly upload Documents again").removeClass('uk-hidden')
}
else {
_old_alert.apply(window,arguments);
$("#upload_error").addClass('uk-hidden').html("")
}
};
})();
});
</script>
On your views.py you can do your computation and once done, you can return a response like below
resp_json = {
"status" : 201,
"status_icon" : "success",
"url" : "/",
"message": message
}
return HttpResponse(json.dumps(resp_json))
For more info on SWAL (Sweet Alerts), visit https://sweetalert.js.org/guides/
My web application is an Employee task manager where tasks can be created and they have states (INIT,IN-PROGRESS,COMPLETED) the states will be changed upon actions (Add,complete)
When I click "Add" button, the URL is viewEmployeeTaskList/empNumber/4
I input some data and click save button.(CREATE) .Then the input form fields will be hidden and the record will be displayed in the table below.
Next I click the the link to that entry from the list table.
There new button appears
Then th URL becomes viewEmployeeTaskList/empNumber/4/id/1
But when I click "Add" adain, the URL remains as viewEmployeeTaskList/empNumber/4/id/1 But I want to remove the id from the URL. Any idea?
Here is my JavaScript code.
$(document).ready(function() {
$('#search-results').removeClass('box');
$('.actionable-buttons').click(function(){
var action = $(this).attr('action');
$('#emptasks_action').val(action);
$('#frmEmpTaskManager').submit();
});
$('#btnSaveTask').click(function() {
$('#frmEmpTaskManager').submit();
});
$("#frmEmpTaskManager").validate({
rules: {
'emptasks[task_name]': {required: true},
'emptasks[description]' : {maxlength:1000},
'emptasks[due_date]' : {valid_date: function(){
return {format:datepickerDateFormat,
required:false,
displayFormat:displayDateFormat
};
}
}
},
messages: {
'emptasks[task_name]': {required: lang_taskNameRequired},
'emptasks[description]': {maxlength: lang_descriptionLength},
'emptasks[due_date]' : {valid_date: lang_invalidDate}
}
});
if(!(haveTasks)) {
$(".check").hide();
}
if($('#emptasks_id').val()==''){
$('#addEmployeeTask').hide();
}else{
$('#addEmployeeTask').show();
}
$('#btnAdd').click(function() {
$('#addEmployeeTask').show();
clearAddForm();
$('#search-results').find('div.top').hide();
});
$('#btnCancel').click(function() {
clearAddForm();
$('#addEmployeeTask').hide();
$('#search-results').find('div.top').show();
});
$('#btnDelete').attr('disabled', 'disabled');
$("#ohrmList_chkSelectAll").click(function() {
if ($(":checkbox").length == 1) {
$('#btnDelete').attr('disabled', 'disabled');
}
else {
if ($("#ohrmList_chkSelectAll").is(':checked')) {
$('#btnDelete').removeAttr('disabled');
} else {
$('#btnDelete').attr('disabled', 'disabled');
}
}
});
$(':checkbox[name*="chkSelectRow[]"]').click(function() {
if ($(':checkbox[name*="chkSelectRow[]"]').is(':checked')) {
$('#btnDelete').removeAttr('disabled');
} else {
$('#btnDelete').attr('disabled', 'disabled');
}
});
$('#dialogDeleteBtn').click(function() {
document.frmList_ohrmListComponent.submit();
});
$('#btnDelete').click(function() {
$('#deletePopUpMessenger').click();
});
$('#dialogDeleteBtn').click(function() {
document.frmList_ohrmListComponent.submit();
});
function clearAddForm() {
$('#emptasks_id').val('');
$('#emptasks_task_name').val('');
$('#emptasks_description').val('');
$('#emptasks_due_date').val('');
$('div#addEmployeeTask label.error').hide();
$('div#messagebar').hide();
}
});
When user visits login.html page, localStorage is used to check if a user is logged in. The page should redirect to profile.html and display notofication message.
The message is displayed, but the page (login.html) is the same..
if( localStorage.user_login ) {
mainView.router.loadPage({url:'profile.html', ignoreCache:true, reload:true });
myApp.addNotification( {
message: 'Welcome '+ localStorage.user_username +'!'
} );
}
How can i make the page redirect if the user is logged in?
put this before myApp framework7 initialization.
$$(document).on('pageInit', function (e) {
var page = e.detail.page;
if (page.name === 'index') {
try{
var storedData = window.localStorage['f7form-'+ 'idofyourloginform'];
if(storedData) {
//do your ajax login request here
// if successful do your login redirect
mainView.router.loadPage({url:'profile.html', ignoreCache:true, reload:true });
}
}
);
Inside your Login page, use like this codes:
HTML
Log In
JavaScript
return {
methods: {
signIn: function () {
var $ = this.$;
var app = this.$app;
var username = $('input#demo-username-1').val();
var password = $('input#demo-password-2').val();
app.request.post('http://localhost:4103/api/User/Login?username='+username+'&password='+password, function (data) {
var obj = JSON.parse(data);
console.log(obj);
console.log(obj.success);
if (obj.success) {
app.data.IsLogin=true;
app.data.UserName='salman';
app.views.main.router.navigate(obj.RedirectUrl);
} else {
app.dialog.alert(obj.Message , function () {});
}
});
}
}
}
Try calling
myApp.closeModal('.login-screen.modal-in')
before
mainView.router.loadPage({url:'profile.html', ignoreCache:true, reload:true })
That should solve the problem.
login page ajax post and response in Framework7 with jquery
inside your my-app.js file use like this codes
myApp.onPageInit('sign-in', function(page) {
$('#loginb').click(function() {
$('#loginb').html('Please Wait...');
var fuid = $('#uid').val();
var fpass = $('#pass').val();
$.ajax({
url: 'chklogin.php',
data: {
"uid": fuid,
"pass": fpass
},
type: 'post',
success: function(returnedData) {
$('#loginb').html(returnedData);
if (returnedData == "Success") {
mainView.router.load({
url: 'deshboard.php',
ignoreCache: true
});
} else {
mainView.router.load({
url: 'login.php',
ignoreCache: true
});
}
}
});
});
});
Use this function with route name:
app.views.main.router.navigate('/profile');
But make sure app is which you initialize project such as:
var app = new Framework7({....});
I've tried a lot of things, but still can access a .js file from inside a form: please, can anyone tell me how it can be done?
this is what I am trying to call:
<script type="text/javascript">
if (confirm("Press 'OK' to leave, or 'Cancel' if you want to stay: "))
{
window.location="http://google.com";
}
else
{
Go back
}
</script>
this is how I've been trying to call:
<input type="BUTTON" value="Back to Main Page" onclick= ??? >
Thank you.
var answer = confirm ("Press Ok to leave. Cancel to stay.")
if (answer)
window.location="http://google.com"
else
window.location="http://www.mysite.com/"
You are adding HTML code inside of your JavaScript code. You need to separate them. Something like:
document.write('Go back');
would do the trick.
You need to make your code into a javascript function, like this
function sayHello()
{
alert('hello');
}
And in the button html:
<input type="BUTTON" value="Back to Main Page" onclick="javascript: sayHello();" >
// start active and inactive confirm message box
var Regionid = '#Model.RegionID';
if (Regionid != 0) {
$(function () {
$('#inactive').change(function () {
$("#ConformationDlg").html('#Constants.ChangeStatus');
$("#ConformationDlg").dialog({
title: "",
buttons: [
{
text: "Yes",
click: function () {
$("#ConformationDlg").dialog("close");
}
},
{
text: "No",
click: function () {
$('#active').prop("checked", true);
$("#ConformationDlg").dialog("close");
}
}
]
});
});
})
}
// End active and inactive confirm message box
$(function () {
$("#btnSubmit").click(function () {
var form = $("#frm");
var Regionid = $("#hdnRegionID").val();
if (form.valid()) {
if (Regionid == 0) {
$("#ConformationDlg").html('#Constants.AddFormSubmit');
$("#ConformationDlg").dialog({
title: "",
buttons: [
{
text: "Yes",
click: function () {
window.location.href = "../RegionFoodTypes/RegionFoodTypes";
$("#ConformationDlg").dialog("close");
}
},
{
text: "No",
click: function () {
$("#ConformationDlg").dialog("close");
}
}
]
});
}
else {
$("#ConformationDlg").html('#Constants.EditFormSubmit');
$("#ConformationDlg").dialog({
title: "",
buttons: [
{
text: "Yes",
click: function () {
window.location.href = "../RegionFoodTypes/RegionFoodTypes";
$("#ConformationDlg").dialog("close");
}
},
{
text: "No",
click: function () {
$("#ConformationDlg").dialog("close");
}
}
]
});
}
}
})
})
function resetFields(form) {
$("#ConformationDlg").html('#Constants.CancelForm');
$("#ConformationDlg").dialog({
title: "",
buttons: [
{
text: "Yes",
click: function () {
window.location.href = "../RegionFoodTypes/RegionFoodTypes";
$("#ConformationDlg").dialog("close");
}
},
{
text: "No",
click: function () {
$("#ConformationDlg").dialog("close");
}
}
]
});
}