AJAX Form request not sent to Express web server - html

I'm starting to learn about Expressjs, Twitter Bootstrap and BackBonejs.
I have created the basic Expressjs app with the command line tool and added an index.html for the sign in form. When the user click on the "Sign in" button which have an event attached, I retrieve the form information and make an ajax call to the '/login' route but it does not work ..
Here a list of the necessary files :
index.html
login.js
server.js
routes.js
Thank you for your help.

The issue is that the form is still submitting via redirect as that's its default bahavior and it hasn't been instructed to do otherwise. And, because of the redirect, the browser is is aborting the Ajax request.
To prevent the redirect, you'll want to bind to the .submit() event of the <form> and use event.preventDefault():
$(document).ready(function () {
$('#login-form').submit(function (e) {
e.preventDefault();
});
});
It may also be worthwhile to use this event for the Ajax rather than the .click() of the <button> as many browsers allow submitting through other actions besides just clicking a type="submit" button (e.g., pressing Enter when focus is on a <input type="text">):
$(document).ready(function () {
$('#login-form').submit(function (e) {
e.preventDefault();
var _login = $('#login').val(),
_password = CryptoJS.SHA512($('#password').val()),
_remember = $('input:checkbox:checked').val() ? 1 : 0;
// etc.
});
});

For one, you need to prevent the default action from the button click:
$('#btn-login').click(function () {
// ...
});
// should accept the passed event and `prevenDefault`, like...
$('#btn-login').click(function (e) {
e.preventDefault();
// ...
});

Related

window.location.assign() is not catched by Router in dart

I try to use a Router from route_hierarchical/client.dart to listen to an onpopstate event and enable/disable a <div> in my index.html. (Example in stagehand.pub dart plugin)
If this is done via normal <a href="/relativePath"> in index.html, it works.
But if I try to change the path via a button.onClick.listen() handler in which I call:
window.location.assign('/relativePath');
I get 404 and the router is not handling my event properly.
Should that that action not invoke a popstate event which is caught by Router like described here?
handlers.dart
...
button.onClick.listen((_){
window.location.assign('/about');
});
...
router.dart
var router = new Router();
router.root
..addRoute(name: 'about', path: '/about', enter: showAbout)
..addRoute(name: 'login', defaultRoute: true, path: '/', enter: showLogin)
..addRoute(name: 'context', path: '/context', enter: showContext);
router.listen();
}
void showAbout(RouteEvent e) {
// Extremely simple and non-scalable way to show different views.
querySelector('#login').style.display = 'none';
querySelector('#about').style.display = '';
querySelector('#context').style.display = 'none';
} ...
index.html
...
<form>
<button type="button" id="submit" disabled="true" >
Login
</button>
</form>
...
onPopState is the wrong event. This event is only fired if you navigate to an existing history entry (back, forward, pushState, go to 2nd entry in history).
What you are looking for is probably the window.onHashChange event.
OK looks like I am not achieving my goal with assuming the above behavior.
Thanks to Günther Zöchbauer for helping.
I filed it with corresponding Github project as I think it should work.
What I now use and what works including history support is
router.gotoUrl('/relativePath')
in the onButtonClick handler.
That totally does it.

Page can be viewed by typing in the URL?

On my meteor app I have a login system that sends you to the /dashboard path if you log in or sign up successfully. However, right now it is possible to get to the /dashboard path just by typing in localhost:3000/dashboard. How can I prevent this?
In addition to filtering the route with router hooks or custom actions, you may ensure that the template itself is displayed only to privileged users:
<template name="secret">
{{#if admin}}
...
{{/if}}
</template>
Handlebars.registerHelper('admin', function(options) {
if(Meteor.user() && Meteor.user().admin) return options.fn(this);
return options.inverse(this);
});
If you want to show a template to all registered users, you may use {{#if currentUser}} instead, in which case you don't need to register an additional helper.
You can accomplish this using before hooks. Here is a simple example with three routes: index, signin, and dashboard:
Router.map(function() {
this.route('index', {
path: '/'
});
this.route('signin');
this.route('dashboard');
});
var mustBeSignedIn = function() {
if (!(Meteor.user() || Meteor.loggingIn())) {
Router.go('signin');
this.stop();
}
};
Router.before(mustBeSignedIn, {except: ['signin']});
Before all routes except signin, we redirect the user back to the signin page unless they are logged in or in the process of logging in. You can see more examples in the using hooks section of the IR docs.
You need to check the state of the user before each route is run. If the user is not logged in (Meteor.userId() returns null) then redirect the user to the login route.
Router.before(function() {
if (!Meteor.userId()) {
this.redirect('userLoginRoute');
this.stop();
}
}, {
except: ['userLoginRoute', 'userSignupRoute', 'userNewPasswordRoute']
});
I believe you can use custom actions for iron-router. You can check Meteor.userId() if it's null (not logged in) in the custom action, and redirect accordingly.

Chrome Extension: Insert a clickable image using a content script

I know hat it is possible, but I am not quite sure how to do it the 'right' way, as to ensure there are no conflicts.
I came across this question: Cannot call functions to content scripts by clicking on image . But it is so convoluted with random comments that it's hard to understand what the corrected way was.
Use case:
Html pages have a div on the page where they expect anyone using the Chrome extension to inject a picture. When users click on he picture, I want to somehow notify an event script. So I know I need to register a listener so the code inserted messages the event script.
Can I get some indication on what code to inject through the content script? I saw that sometimes injecting jquery directly is advised.
I am trying to avoid having the html page to post a message to itself so it can be intercepted. Thanks
With the help of Jquery something like this would capture the image onclick event and allow you to pass a message to a background page in the Chrome Extension:
$("img").click(function(){
var imageSrc = $(this).attr("src");
//Post to a background page in the Chrome Extension
chrome.extension.sendMessage({ cmd: "postImage", data: { imgSrc: imageSrc } }, function (response) {
return response;
});
});
Then in your background.js create a listener for the message:
chrome.extension.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.cmd == "postImage") {
var imageSrc = request.data.imgSrc;
}
});

How to show html files with modal.open using jquery?

Currently i use a fine working code for opening a modal with Jquery :
$(document).ready(function(){
$("span.ico-detail").click(function(){
modal.open({content: "View detail of " + $(this).parent().parent().attr("id")});
e.preventDefault();
});
});
And now the problem is : How can I use modal.open to open a HTML file named "view.html", which contaning the string of "View detail of "?
What should I change the content : "xxx" with, so I can open the HTML file (view.html) and join it with other text ?
Thanks before.
If the view.html is stored on a server and its content is static, then you can choose to preload the content of the file using ajax.
$(function () {
window.myAppNs = {
viewContent: null;
};
$.ajax({
url: 'view.html',
dataType: 'html',
type: 'GET'
}).done(function (resp) {
myAppNs.viewContent = resp;
});
$("span.ico-detail").click(function(){
modal.open({content: myAppNs.viewContent + $(this).parent().parent().attr("id")});
e.preventDefault();
});
});
I am creating a global variable myAppNs. This will hold all app related variables. The idea is not pollute the global namespace with unnecessary variables. There are better and safer ways to create a namespace. If that interests you, you can google for the same.
The ajax call preloads the content of the view.html and stores it in myAppNs.viewContent. The click handler reads that content from the variable.
There is a slight chance that the user can click the element before the ajax response is returned. If that's an issue, you can always move the namespace creation and ajax call out of document.ready and place it in the head section, immediately after referencing jquery. That ought to give the browser enough time to fetch the content before the dom is ready, but there is still that small possibility that the response might be delayed. If you need to ensure the user can click only if the data has been fetched, then bind the click handler inside the done callback of the ajax call.

jQuery Does Not Run <script> When AJAX $.load() Method Called by Click Event

I've been struggling with this for a while and can't figure it out. Hopefully it's something obvious that I missed.
Here's the code:
$(document).ready(function() {
$('#clickbox').load('eventpage/clicks.html.php #click2', function () {
console.log('click2 loaded');
$(this).hide()
.fadeIn(3000);
$('#click2').click(function(e) {
e.preventDefault();
console.log('click2 clicked');
$('#bizdev').load('pagewithscripttags.php', function (data) {
console.log(data);
console.log('#bizdev is loaded, but scripts are not run');
$('#bizdev').hide();
console.log('bizdev hidden');
});
$('#content').hide();
$('#bizdev').show();
});
});
When I run this (from an external js file), the file 'pagewithscripttags.php' is loaded into the DOM on the click event, but the scripts are not executed and I can't figure out why. HELP!
However, when I move the load method into the callback function of the first load, the file is inserted into the DOM and the scripts are run:
$(document).ready(function() {
$('#clickbox').load('eventpage/clicks.html.php #click2', function () {
console.log('click2 loaded');
$(this).hide()
.fadeIn(3000);
$('#bizdev').load('pagewithscripttags.php', function (data) {
console.log(data);
console.log('#bizdev loaded and scripts are run');
$('#bizdev').hide();
console.log('#bizdev hidden');
});
$('#click2').click(function(e) {
e.preventDefault();
console.log('click2 clicked');
$('#content').hide();
$('#bizdev').show();
});
});
Why do the scripts run as part of the callback function, but not on the click event (which is when I need them to run)?
Here are the contents of pagewithscripts.php:
<script>console.log('this script was run');</script>
<script type="IN/MemberProfile" data-id="http://linkedin.com/publicprofileurl" data-format="inline" width='106px' data-related="false"></script>
The first script is run and appears on the console.log, but the second is just inserted into the DOM without being run, except when I place the .load() method outside of the click handler.
(I need to load the scripts on the click event because they take several seconds to run (they call the LinkedIn API) and there's freezing/lag when I run them on document ready.)
You probably need to tell the LinkedIn framework to re-scan the page.
IN.parse(domNode)
This is covered on the JavaScript API reference document on events here:
https://developer.linkedin.com/documents/inauth-inevent-and-inui
Load the script datatype
http://api.jquery.com/jQuery.getScript/
Actually jQuery 'click()' function will not handle the 'click' event of dynamic elements, so try on() or live() functions to make your code working fine, using these functions you can move the click handler code out of the first load() callback.
FYI: Try to replace your $('#click2').click(function(e) { code with this $('#click2').live("click", function(e) { code.
Note: 'live()' function is deprecated from the jQuery version 1.7 onwards.
If you are not clear to use these functions then just provide your full page source so that I can check and adjust your code accordingly.