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.
Related
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.
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 want to make a login page which check the conditon and user is redirected to home page afterwards , now i want to implement a condition that when user has visited home page and he clicks on the back button or browser he should'nt be able to again visit login page . i tried to set a variable isLogged in as false and after checking the username and password make that variable to true and store that in local storage and use it like flag , but i am not able to properly get where's m wrong .
here is my app.js
var validationApp = angular.module('validationApp',['ngRoute','ngStorage']);
var loggedIn = false;
validationApp.run(function($rootScope, $localStorage){
//var loggedIn = false;
//if(!loggedIn) {
storage = window.localStorage;
//storage.setItem("loggedIn", true);
//console.log(storage.getItem("loggedIn"));
// $rootScope.$storage = $localStorage.$default({
// loggedIn: false
// })
// }
});
validationApp.controller('mainController', function($scope,loginservice,$localStorage) {
$scope.dologin = function () {
//storage.setItem("loggedIn" ,true);
//loginsucess = storage.getItem("loggedIn");
if(loggedIn == false) {
//console.log(loginsucess);
if ($scope.userForm.$valid) {
loginservice.login($scope.user.email, $scope.user.password);
}
storage.setItem("loggedIn", true);
}
}
});
i tried to put a check condition into my routes also and now i am not able to get my home page even after valid credentials .
validationApp.config(
function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'mainController'
})
.when('/home', {
templateUrl: 'home.html',
resolve:{
"check":function($location){
if(storage.getItem(loggedIn) == true)
{
alert(loggedIn);
$location.path("/home");
}
else
{
$location.path("/main");
}
}
},
controller: 'mainController'
})
.otherwise({
redirectTo: '/'
});
});
validationApp.service('loginservice',function($location)
{
this.login = function(username, password){
console.log(username,password);
if(username == "ank#gmail.com" && password=="1234")
{
//alert('thank you for submitting your form');
$location.path("/home");
//console.log(storage.getItem("loggedIn"));
}
else
{
//alert("invalid username and password");
$location.path("/main");
}
}
});
Please see working example: http://plnkr.co/edit/46O0znC5HFDE4cYXSm5h?p=preview
Stored data in cookies in login function as follows,
$cookies.userinfo = {
'id': 1,
'name': 'pqr'
};
And on logout remove that data -
delete $cookies.userinfo;
then check for 'angular.isDefined($cookies.userinfo)' (userinfo is cookie name which given at the time of storing data in it) if find then redirect it to your page which you want to see after login. i.e
app.run(function ($cookies) {
$rootScope.$on("$routeChangeStart", function () {
if (angular.isDefined($cookies.userinfo)) {
$location.path("/pathname");
}
});
});
See if this serves your purpose
var validationApp = angular.module('validationApp', ['ngRoute','ngStorage']);
var loggedIn = false;
validationApp.run(function($rootScope, $localStorage, $location){
storage = window.localStorage;
$rootScope.$on("$routeChangeStart", function (evt, next, current) {
if(storage.getItem(loggedIn) == true) {
if (next.$$route.originalPath == '/login')
$location.path('/home');
}
else
$location.path('/login');
});
});
I hope someone can help me with this.
I have a Backbone based SPA for a responsive website with a .net WebAPI providing all of the data.
I've recently found a weird problem. I've added a search box, which searches one of the catalogues on the system. This works fine on desktop browsers and on Android. On iOS, executing a search seems to take you back to the sign in page.
You can execute a search in various ways, you can either hit enter or you can click the search icon. Both of these then trigger a method that navigates the router to the URL for the search result.
My first thought was that it was some button weirdness, but I don't think that's the problem as both methods of search execution are causing the same problem.
The search results are displayed in a view that is secured (It requires a username to be present - this is stored in a hidden field on the page). There are two search boxes on the site - one on the home page and one on the search results page itself (it shows a default set when you load it first time - which it does load first time fine). Both search boxes are exhibiting the same behaviour.
My site is set up in such a way that when Backbone pulls back a model, if it gets a 401 back from the API then it will send you back to the login page, so I can only think it's happening here.
Here's my view code...
function (SiansPlan, ErrorManager, RecipeSearchResult, Header, Components, TemplateSource) {
var recipeSearchView = SiansPlan.SecureView.extend({
name: 'Recipe Search',
sectionName: 'Recipes',
queryText: '',
template: Handlebars.compile(TemplateSource),
headerView: new Header({ text: 'Recipes', swatch: 'e' }),
searchBoxRegion: undefined,
$searchWrapper: undefined,
$queryHeaderMobile: undefined,
$queryHeaderDesktop: undefined,
$searchButton: undefined,
$searchInput: undefined,
$recipeSearch : undefined,
events: {
'click .link-container': 'showRecipe',
'click #searchWrapper': 'showSearch',
'click #searchButton': 'showOrPerformSearch',
'keydown #searchButton': 'performSearchOnEnter',
'keydown #recipeSearch': 'performSearchOnEnter'
},
initialize: function (options) {
this.options = options || {};
SiansPlan.SecureView.prototype.initialize.call(this, options);
this.queryText = Object.exists(this.options.query) ? this.options.query : '';
},
bindData: function () {
this.$el.html(this.template({ results: this.collection.toJSON() }));
},
render: function () {
var that = this;
if (this.isSecured()) {
this.trigger('rendering');
var params = {
success: function () {
that.bindData();
that.trigger('rendered');
},
error: function (model, xhr) {
if (Object.exists(xhr) && xhr.status == 401) {
that.applyTimedOutSecureLoginPrompt();
} else {
that.$el.html('Unable to fetch search results');
ErrorManager.handleXhr('Search failed', xhr);
}
that.trigger('rendered');
}
};
if (!Object.exists(this.collection)) {
this.collection = new RecipeSearchResult.Collection({ username: SiansPlanApp.session.username(), query: this.queryText });
}
this.collection.fetch(params);
} else {
this.applySecureLoginPrompt();
}
return this;
},
postRender: function () {
var that = this;
var queryHeader = "All recipes";
if (Object.hasValue(this.queryText)) {
queryHeader = this.collection.length + " results for '" + this.queryText + "'";
}
this.$searchWrapper = $('#searchWrapper');
this.$queryHeaderMobile = $('#queryHeaderMobile');
this.$queryHeaderDesktop = $('#queryHeaderDesktop');
this.$searchButton = $('#searchWrapper');
this.$searchInput = $('#searchInput');
this.$recipeSearch = $('#recipeSearch');
this.$queryHeaderMobile.html(queryHeader);
this.$queryHeaderDesktop.html(queryHeader);
this.$recipeSearch.val(this.queryText);
SiansPlanApp.session.waitForLoad(30, function () {
that.searchBoxRegion = new SiansPlan.Region({ el: '.recipe-search-box-container' });
that.searchBoxRegion.renderView(new Components.RecipeSearchBox({ username: SiansPlanApp.session.username(), query: that.queryText, title: 'Search' }));
});
},
performSearchOnEnter: function (e) {
if (e.keyCode == 13) {
this.showOrPerformSearch(e);
}
},
showOrPerformSearch: function (e) {
if (!this.$searchInput.is(':visible')) {
this.showSearch(e);
} else {
e.preventDefault();
var url = '/recipes/search/' + this.$recipeSearch.val();
window.SiansPlanApp.router.navigate(url, true);
}
return false;
},
showRecipe: function (e) {
e.preventDefault();
var url = $(e.target).find('a').first().attr('href');
window.SiansPlanApp.router.navigate(url, true);
},
showSearch: function (e) {
e.preventDefault();
if (!this.$searchInput.is(':visible')) {
this.$queryHeaderMobile.hide();
this.$searchInput.show();
this.$recipeSearch.focus();
this.$recipeSearch.select();
}
return false;
}
});
return recipeSearchView;
});
UPDATES
I've set up some alerts as follows in the script to see what's going on and I've discovered the following...
render: function () {
var that = this;
if (this.isSecured()) {
this.trigger('rendering');
var params = {
success: function () {
alert('Bind has succeeded!');
that.bindData();
that.trigger('rendered');
},
error: function (model, xhr) {
alert('Bind has failed!');
if (Object.exists(xhr) && xhr.status == 401) {
that.applyTimedOutSecureLoginPrompt();
} else {
that.$el.html('Unable to fetch search results');
ErrorManager.handleXhr('Search failed', xhr);
}
that.trigger('rendered');
alert(xhr.status + ' ' + xhr.responseText);
}
};
if (!Object.exists(this.collection)) {
alert('Binding new collection: ' + SiansPlanApp.session.username() + ' - ' + this.queryText);
this.collection = new RecipeSearchResult.Collection({ username: SiansPlanApp.session.username(), query: this.queryText });
}
alert('About to fetch using ' + this.collection.url());
this.collection.fetch(params);
} else {
alert('I dont appear to be secured??');
this.applySecureLoginPrompt();
}
return this;
},
When I first load the page (to show all the results) it loads fine and 'Bind Succeeded!' appears. The API call made is /api/recipes/search/{username}/
When I submit search criteria it fails ('Bind failed!') with the API call of /api/recipes/search/{username}/{query} and returns a 401.
This has me even more befuddled than before as this now looks like an API issue, but other devices are working fine and if I submit the same queries into Fiddler everything is, as expected, fine.
I've found the answer in the smallest place...
The issue was that the search criteria had an upper case letter. So, for example, when searching with 'Fish', The API generated a 301 which redirected to /api/recipes/search/{username}/fish. iOS didn't like that and reported it as a 401 (Which truly sucks!)
I'm not sure how to express this in code, as I can't seem to locate the problem, but my issue is that Backbone.history seems to be recording two items when a user clicks on a list item in my app.
This is not consistent.
My app has a 4 item navigation at the bottom that links to 4 main sections (the first one being home - routed to '/'). If I load up the app, go to one of the other navigation pages, then click the 'Home' button again and then click one of the navigation options I get a list of items to choose from. If I then choose one two entries are added - Firstly, for some reason, a reference to the home route with /# at the end and then the route for the item I clicked.
The end result is that 'back' then inexplicably takes me to the home page.
If it helps, my router looks like this...
var siansplanRouter = Backbone.Router.extend({
initialize: function () {
var that = this;
this.routesHit = 0;
//keep count of number of routes handled by your application
Backbone.history.on('route', function() { that.routesHit++; }, this);
window.SiansPlanApp.render();
window.SiansPlanApp.router = this;
},
routes: {
'': 'showHome',
'home': 'showHome',
'hub': 'showHome',
'samples': 'showJqmSamples',
'mealplanner': 'showCurrentMealPlanner',
'mealplanner/:planId': 'showMealPlanner',
'recipes': 'showRecipeSearch',
'recipes/:recipeId': 'showRecipe',
'settings': 'showSettings',
'versioninfo': 'showVersionInfo',
'*other': 'showHome'
},
routesHit: 0,
back: function() {
if(this.routesHit > 1) {
window.history.back();
} else {
//otherwise go to the home page. Use replaceState if available so
//the navigation doesn't create an extra history entry
this.navigate('/', { trigger: true, replace: true });
}
},
showHome: function () {
SiansPlanApp.renderHome();
},
showJqmSamples: function () {
SiansPlanApp.renderView(new SiansPlanApp.views.Hub.Samples());
},
showMealPlanner: function (planId) {
SiansPlanApp.renderView(new SiansPlanApp.views.Planner.MealPlanner({ id: planId }));
},
showCurrentMealPlanner: function () {
SiansPlanApp.renderView(new SiansPlanApp.views.Planner.MealPlanner({ current: true }));
},
showRecipeSearch: function () {
SiansPlanApp.renderView(new SiansPlanApp.views.Recipes.Search());
},
showRecipe: function (recipeId) {
SiansPlanApp.renderView(new SiansPlanApp.views.Recipes.Recipe({ id: recipeId }));
},
showSettings: function () {
SiansPlanApp.renderView(new SiansPlanApp.views.System.Settings());
},
showVersionInfo: function () {
SiansPlanApp.renderView(new SiansPlanApp.views.About.VersionInfo.ListView());
}
});
I've got some basic elements in a kick off file too here...
define(['router', 'regions/r-app', 'jquery', 'domReady'],
function (SiansPlanRouter, AppRegion) {
var run = function () {
// Global click event handler to pass through links to navigate
$(document).on("click", "a:not([data-bypass])", function (e) {
var href = { prop: $(this).prop("href"), attr: $(this).attr("href") };
var root = location.protocol + "//" + location.host + SiansPlanApp.root;
if (href.prop && href.prop.slice(0, root.length) === root) {
e.preventDefault();
Backbone.history.navigate(href.attr, true);
}
});
$.ajaxPrefilter(function (options, originalOptions, jqXhr) {
//options.url = '/api' + options.url;
});
// Create the global namespace region object.
window.SiansPlanApp = new AppRegion();
// Adds the authorization header to all of the API requests.
$(document).ajaxSend(function (e, xhr, options) {
xhr.setRequestHeader("Authorization", 'SiansPlan ' + SiansPlanApp.cookies.getSessionData());
});
// Load up session data if any is present yet - this can't happen until the XHR headers are set up.
SiansPlanApp.session.loadSession();
// Instantiate the router.
window.SiansPlanApp.router = new SiansPlanRouter();
// Boot up the app:
Backbone.history.start();
};
return {
run: run
};
});