How to edit URL after a button click in Javascript - javascript

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();
}
});

Related

Error in generating invoice from sales order in suitescript 2.0?

I tried to include a button (created from user event) on Sales order. Upon clicking it, Invoice will be generated. As soon as the button is hit, ther comes an error and invoice doesnt get generated. Can anyone help me with this?
//Client script
function pageInit() {
}
function csForButton(ctx) {
var rec = curr.get();
var customer = rec.getValue({ "fieldId": "customer" });
log.error({
title: 'customer',
details: customer
});
var scriptURL = url.resolveScript({
"scriptId": "customscript_button_task_sl",
"deploymentId": "customdeploy_button_task_sl"
});
console.log('scriptURL', scriptURL);
window.onbeforeunload = null;
window.open(scriptURL + '&id=' + rec.id);
}
return {
pageInit: pageInit,
csForButton: csForButton
};
//User Event Script
function beforeLoad(ctx) {
//if (context.type == context.UserEventType.VIEW) {
addbutton(ctx);
// }
}
function addbutton(ctx) {
try {
var rec = ctx.newRecord;//record object, now we can get its properties through it(e.g. fields)
var statusOfTrans = rec.getValue({ fieldId: 'status' });
log.error('statusOfTrans', statusOfTrans);
ctx.form.clientScriptFileId = "16474"
if (ctx.type == "view" && statusOfTrans == 'Pending Fulfillment') {
ctx.form.addButton({
id: 'custpage_make_invoice',
label: 'create invoice!',
functionName: 'csForButton'
});
}
}
catch (error) {
log.error('addbutton', error);
}
}
return {
beforeLoad: beforeLoad,
}
//Suitelet Script
function onRequest(ctx) {
try {
var req = ctx.request;
var res = ctx.response;
if (req.method == 'GET') {
var objRecord = rec.transform({
fromType: rec.Type.SALES_ORDER,
fromId: req.parameters.id,
toType: rec.Type.INVOICE,
isDynamic: true,
});
objRecord.save({
ignoreMandatoryFields: true
});
res.write({output: 'Invoice created'});
}
} catch (error) {
log.error('onRequest', error);
}
}
return {
'onRequest': onRequest
}
error (in suitelet):
{"type":"error.SuiteScriptError","name":"USER_ERROR","message":"You must enter at least one line item for this transaction.","stack":["anonymous(N/serverRecordService)","onRequest(/SuiteScripts/button SL.js:39)"],"cause":{"type":"internal error","code":"USER_ERROR","details":"You must enter at least one line item for this transaction.","userEvent":null,"stackTrace":["anonymous(N/serverRecordService)","onRequest(/SuiteScripts/button SL.js:39)"],"notifyOff":false},"id":"","notifyOff":false,"userFacing":false}
As Error says to include atleast 1 line but i wanted it to be generated automatically. I am new in suitescript and taking all the help from the documentation. Can anyone jst guide me what is wrong i m doing?
Thank u
You need the SO status to be Pending Billing. If the status of the SO is Pending Fulfillment, then no line items are ready to be invoiced.

Stripe js: don't let empty form be sent

I'm trying to avoid letting users submit stripe form when inputs are empty, I`m using stripe.js elements integration to render my form and handle form submition inside my vue component.
this.cardNumberElement.on('change', this.enableForm);
this.cardExpiryElement.on('change', this.enableForm);
this.cardCvcElement.on('change', this.enableForm);
After checking the docs I tried to use the change event on inputs but this is not working sice the user can just not type anything and click submit button.
This is my component:
mounted()
{
console.log(this.$options.name + ' component succesfully mounted');
this.stripe = Stripe(this.stripePK);
this.elements = this.stripe.elements();
this.cardNumberElement = this.elements.create('cardNumber', {style: this.stripeStyles});
this.cardNumberElement.mount('#card-number-element');
this.cardExpiryElement = this.elements.create('cardExpiry', {style: this.stripeStyles});
this.cardExpiryElement.mount('#card-expiry-element');
this.cardCvcElement = this.elements.create('cardCvc', {style: this.stripeStyles});
this.cardCvcElement.mount('#card-cvc-element');
let stripeElements = document.querySelectorAll("#card-number-element, #card-expiry-element, #card-cvc-element");
stripeElements.forEach(el => el.addEventListener('change', this.printStripeFormErrors));
this.cardNumberElement.on('change', this.enableForm);
this.cardExpiryElement.on('change', this.enableForm);
this.cardCvcElement.on('change', this.enableForm);
},
methods:
{
...mapActions('Stripe', ['addSource', 'createSourceAndCustomer']),
...mapMutations('Stripe', ['TOGGLE_PAYMENT_FORM']),
...mapMutations('Loader', ['SET_LOADER', 'SET_LOADER_ID']),
enableForm:function(event){
if(event.complete){
this.disabled = false;
}
else if(event.empty){
this.disabled = true;
}
},
submitStripeForm: function()
{
this.SET_LOADER({ status:1, message: 'Procesando...' });
var self = this;
this.stripe.createSource(this.cardNumberElement).then(function(result) {
if (result.error) {
self.cardErrors = result.error.message;
}
else {
self.stripeSourceHandler(result.source.id);
}
});
},
stripeSourceHandler: function(sourceId)
{
console.log('stripeSourceHandler');
this.cardNumberElement.clear();
this.cardExpiryElement.clear();
this.cardCvcElement.clear();
if(this.customerSources.length == 0)
{
console.log('createSourceAndCustomer');
this.createSourceAndCustomer({ id: sourceId });
}
else
{
console.log('addSource');
this.addSource({ id: sourceId });
}
},
printStripeFormErrors: function(event)
{
if(event.error)
{
self.cardErrors = event.error.message
}
else
{
self.cardErrors = '';
}
}
}
Given the stripe docs, the use of the event seems correct (though it can be improved a bit with using this.disabled = !event.complete to cover error case and not only empty case).
You may try to console.log in the event callback enableForm to check if event is well fired.
Anyway, it's more likely coming from the disabling logic of the submit button and it misses in your post. I've created below a fake secure-component that triggers a change event when value change.
The interesting part in on the container component :
Submit is disabled by default through data disabled,
Submit is enabled if event received has a property complete set to true. If false, it is disabled.
Hope it will help you to focus your trouble.
/**
Mock component to emulate stripes card element behavior with change event
*/
const SecureInput = {
template: '<input type="text" v-model="cardnumber"/>',
data: () => ({
cardnumber: null
}),
watch: {
cardnumber: function(val) {
if(!val) {
this.$emit('change', {empty: true, error: false, complete: false});
return;
}
if(val.length < 5) {
this.$emit('change', {empty: false, error: true, complete: false});
return;
}
this.$emit('change', {empty: false, error: false, complete: true});
}
}
}
/* Logic is here */
const app = new Vue({
el: '#app',
components: {
SecureInput
},
data: {
disabled: true
},
methods: {
updateDisable: function(event) {
this.disabled = !event.complete;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<form #submit.prevent="$emit('submitted')">
<p><secure-input #change="updateDisable"/></p>
<p><input type="submit" :disabled="disabled"/></p>
</form>
</div>

Javascript Alert On Successful Form Submission

I am currently using Django 1.9 and Braintree payments JS v3. What I want to be able to do is when the user submits the form successfully, have a Javascript alert() pop up. But the pop-up message will be contingent on what the back end Python returns...
So like this:
Submit the form
Run the backend stuff
Pop up the alert with a message dependent on what is returned by the Python backend
When the alert is closed, refresh or redirect
var client_token = "{{ request.session.braintree_client_token }}"
var form = document.querySelector('#checkout-form');
var submit = document.querySelector('input[type="submit"]');
braintree.client.create({
authorization: client_token
}, function (clientErr, clientInstance) {
if (clientErr) { // for error loading client authorization
if(alert('There was a form verification issue, reloading page on close.')){}
else window.location.reload();
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: 'Credit Card Number'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019'
},
postalCode: {
selector: '#postal-code',
placeholder: '10014'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) { // for errors creating form
if(alert('There was a form creation issue, reloading page on close.')){}
else window.location.reload();
return;
}
submit.removeAttribute('disabled');
form.addEventListener('submit', function (event) {
event.preventDefault();
document.querySelector('input[id="pay-button"]').value = "Please wait...";
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
if (tokenizeErr.code === 'HOSTED_FIELDS_FIELDS_EMPTY') {
alert('Please fill in card info');
document.querySelector('input[id="pay-button"]').value = "Complete Booking";
}
return;
}
// Put `payload.nonce` into the `payment_method_nonce`
document.querySelector('input[name="payment_method_nonce"]').value = payload.nonce;
form.submit();
$('input[type="submit"]').prop('disabled',true);
});
}, false);
});
});
I'm thinking that this functionality would need to be right after form.submit() is run on the bottom...
Edit:
I added the vars up top in my code

post callback function synchronization

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

Iron Route to inserted value by user in Meteor

I need to run function that takes an input from user and routes to that value. For example inserted value is
https://www.youtube.com/watch?v=_ZiN_NqT-Us
And it should route to the url:
download?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_ZiN_NqT-Us
I get the value and Set.session to get Session back in Router, the following way but it doesn't get any value.
Template.inputBar.events({
'click #download':function(event, template) {
var url = template.find('.url').value;
if (url.value != "") {
Session.set('url', url);
}
else {
alert('paste link');
}
}
});
Routes to inserted value and executes call to server:
Router.map(function(){
this.route('frontPage', {path: '/'} );
this.route('downloadLinks', {
path: '/download?link=:url',
data: function() {
var url = Session.get('url');
Meteor.call('command', url, function(error, result) {
if(result.stdout) {
console.log(result.stdout)
}
else {
alert("Not supported site");
}
});
}
});
});
Docs for Router.go
Template.inputBar.events({
'click #download':function(event, template) {
var url = template.find('.url').value;
if (url.value != "") {
Router.go(url.value);
} else {
alert('paste link');
}
}
});
This will redirect to the route you want.

Categories