angularfire and facebook login getting Cannot read property 'onAuth' of undefined - facebook

Hi i found a sample of auth on routing with angularfire, i just change it to support the new firebase sdk v4 and still using angularfire v1.
this is the link of the piece of code i used (with ui-router) :
angularfire docs
now this is my app.js and index.html
var config = {
"apiKey": "AIzaSyAUoM0RYqF1-wHI_kYV_8LKgIwxmBEweZ8",
"authDomain": "clubears-156821.firebaseapp.com",
"databaseURL": "https://clubears-156821.firebaseio.com",
"projectId": "clubears-156821",
"storageBucket": "clubears-156821.appspot.com",
"messagingSenderId": "970903539685"
};
firebase.initializeApp(config);
var app = angular.module("sampleApp", [
"firebase",
"ui.router"
]);
app.factory("Auth", ["$firebaseAuth",
function ($firebaseAuth) {
return $firebaseAuth();
}
]);
// UI.ROUTER STUFF
app.run(["$rootScope", "$state", function ($rootScope, $state) {
$rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
if (error === "AUTH_REQUIRED") {
$state.go("home");
}
});
}]);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: "/home",
template: "<h1>Home</h1><p>This is the Home page</p>",
resolve: {
"currentAuth": ["Auth", function (Auth) {
return Auth.$waitForAuth();
}]
}
})
.state('profile', {
url: "/profile",
template: "<h1>Profile</h1><p>This is the Profile page</p>",
resolve: {
"currentAuth": ["Auth", function (Auth) {
return Auth.$requireSignIn();
}]
}
})
});
app.controller("MainCtrl", ["$scope", "Auth",
function ($scope, Auth) {
$scope.auth = Auth;
console.log(Auth);
$scope.auth.$onAuth(function(authData) {
$scope.authData = authData;
console.log(authData);
});
}
]);
app.controller("NavCtrl", ["$scope", "Auth",
function ($scope, Auth) {
$scope.auth = Auth;
console.log(Auth);
$scope.auth.$onAuth(function(authData) {
$scope.authData = authData;
});
}
]);
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
</head>
<body>
<div ng-app="sampleApp">
<div ng-controller="MainCtrl">
<nav class="navbar navbar-default navbar-static-top" ng-controller="NavCtrl">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="home">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li ui-sref-active="active">
<a ui-sref="home" href="#">Home</a>
</li>
<li ui-sref-active="active" ng-show="authData">
<a ui-sref="profile" href="#">
My Profile
</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li ng-hide="authData">
<a href="#" ng-click="$parent.auth.$authWithOAuthPopup('facebook')">
<span class="fa fa-facebook-official"></span>
Sign In with Facebook
</a>
</li>
<li ng-show="authData">
<a href="#" ng-click="$parent.auth.$unauth()">
<span class="fa fa-sign-out"></span>
Logout
</a>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div ui-view ng-show="authData"></div>
<div class="login-screen" ng-hide="authData">
<div class="jumbotron text-center">
<h1>Sweet login, brah.</h1>
<p class="lead">This is a pretty simple login utilizing AngularJS and AngularFire.</p>
<button class="btn btn-primary btn-lg" ng-click="auth.$authWithOAuthPopup('facebook')">
<span class="fa fa-facebook-official fa-fw"></span>
Sign in with Facebook
</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script src="app.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/1.1.3/angularfire.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.min.js"></script>
</body>
</html>
now the problem is that i getting an error : Cannot read property 'onAuth' of undefined.
i think its problem of the version of the new SDk and i looked in the proposed solution here in stackoverflow but none of them fix me the problem.
please help...

Ok i figure out the problem and fix it by changing the versions of angular and angularfire. and a little change to migrate to the new sdk.
this is new code.
my problem now is that i don't get all the scope that i want from facebook. for example i want birthday and i cannot see it comes back.
someone have a suggestion ?
var config = {
"apiKey": "AIzaSyAUoM0RYqF1-wHI_kYV_8LKgIwxmBEweZ8",
"authDomain": "clubears-156821.firebaseapp.com",
"databaseURL": "https://clubears-156821.firebaseio.com",
"projectId": "clubears-156821",
"storageBucket": "clubears-156821.appspot.com",
"messagingSenderId": "970903539685"
};
firebase.initializeApp(config);
var app = angular.module("sampleApp", [
"firebase",
"ui.router"
]);
app.factory("Auth", ["$firebaseAuth",
function ($firebaseAuth) {
return $firebaseAuth();
}
]);
//var provider = Auth.FacebookAuthProvider();
//provider.addScope('user_birthday');
//
//Auth.signInWithRedirect(provider);
// UI.ROUTER STUFF
app.run(["$rootScope", "$state", function ($rootScope, $state) {
$rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
if (error === "AUTH_REQUIRED") {
$state.go("home");
}
});
}]);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: "/home",
template: "<h1>Home</h1><p>This is the Home page</p>",
resolve: {
"currentAuth": ["Auth", function (Auth) {
return Auth.$waitForSignIn();
}]
}
})
.state('profile', {
url: "/profile",
template: "<h1>Profile</h1><p>This is the Profile page</p>",
resolve: {
"currentAuth": ["Auth", function (Auth) {
return Auth.$requireSignIn();
}]
}
});
});
app.controller("MainCtrl", ["$scope", "Auth",
function ($scope, Auth) {
$scope.auth = Auth;
console.log(Auth);
$scope.auth.$onAuthStateChanged(function (authData) {
$scope.authData = authData;
console.log(authData);
});
}
]);
app.controller("NavCtrl", ["$scope", "Auth",
function ($scope, Auth) {
$scope.currentUser = null;
$scope.currentUserRef = null;
$scope.currentLocation = null;
$scope.auth = Auth;
console.log(Auth);
/**
* Function called when clicking the Login/Logout button.
*/
// [START buttoncallback]
$scope.SignIn = function () {
if (!Auth.currentUser) {
$scope.auth.$signInWithRedirect('facebook', {
scope: 'email, public_profile, user_birthday'
}).then(function (authData) {
// never come here handle in $onAuthStateChanged because using redirect method
}).catch(function (error) {
if (error.code === 'TRANSPORT_UNAVAILABLE') {
$scope.$signInWithPopup('facebook', {
scope: 'email, public_profile, user_friends'
}).catch(function (error) {
console.error('login error: ', error);
});
} else {
console.error('login error: ', error);
}
});
} else {
// [START signout]
Auth.signOut();
// [END signout]
}
};
// [END buttoncallback]
//
// $scope.updateUserData = function () {
// $scope.currentUserRef.set($scope.currentUser);
// };
$scope.auth.$onAuthStateChanged(function (authData) {
$scope.authData = authData;
console.log('after login');
console.log($scope.authData);
});
}
]);
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
</head>
<body>
<div ng-app="sampleApp">
<div ng-controller="MainCtrl">
<nav class="navbar navbar-default navbar-static-top" ng-controller="NavCtrl">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="home">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li ui-sref-active="active">
<a ui-sref="home" href="#">Home</a>
</li>
<li ui-sref-active="active" ng-show="authData">
<a ui-sref="profile" href="#">
My Profile
</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li ng-hide="authData">
<a href="#" ng-click="SignIn()">
<span class="fa fa-facebook-official"></span>
Sign In with Facebook
</a>
</li>
<li ng-show="authData">
<a href="#" ng-click="SignIn()">
<span class="fa fa-sign-out"></span>
Logout
</a>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div ui-view ng-show="authData"></div>
<div class="login-screen" ng-hide="authData">
<div class="jumbotron text-center">
<h1>Sweet login, brah.</h1>
<p class="lead">This is a pretty simple login utilizing AngularJS and AngularFire.</p>
<button class="btn btn-primary btn-lg" ng-click="SignIn()">
<span class="fa fa-facebook-official fa-fw"></span>
Sign in with Facebook
</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script src="app.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
</body>
</html>

Related

Firebase Authorization and Standard Google App Engine - cannot login or signup

I have a google app engine and I recently decided to add app engine to it. I have gone through the steps, have imported my google project into firebase, added all the initialization code, and some temp functions for logging in and signing up. However, the app never goes past the points where I try to log in. I have been searching everywhere and trying everything I can. I'm sure I'm just missing something small, but could use another set of eyes. Thanks.
Here is my html file:
<!DOCTYPE html>
<html>
<head>
<title>Hello Endpoints!</title>
<script type="text/javascript" src="/js/base.js"></script>
<!-- SCRIPT FOR FIREBASE -->
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-database.js"></script>
<script type="text/javascript" src="/js/firebaseApp.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="/bootstrap/css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="/bootstrap/css/bootstrap-responsive.css">
<link type="text/css" rel="stylesheet" href="/css/style.css">
</head>
<body>
<div class="container">
<input id="txtEmail" type="email" placeholder="Email">
<input id="txtPassword" type="password" placeholder="Password">
<button id="btnLogin" class="btn btn-action" onclick="loginEvent()">
Log in
</button>
<button id="btnSignUp" class="btn btn-secondary" onclick="signupEvent()">
Sign Up
</button>
<button id="btnLogout" class="btn btn-action hide">
Log out
</button>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
projectId: "<PROJECT_ID>",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
};
firebase.initializeApp(config);
</script>
</div>
<div class="container">
<form action="javascript:void(0);">
<h2>Add Asteroid</h2>
<div><span class="label">Name: </span><input id="asteroidName" /></div>
<div><span class="label">Diameter: </span><input id="asteroidDiam" /></div>
<div>Dimensions:</div>
<div><span class="dimlabel">Length: </span><input id="asteroidLength" /></div>
<div><span class="dimlabel">Width: </span><input id="asteroidWidth" /></div>
<div><span class="dimlabel">Height: </span><input id="asteroidHeight" /></div>
<div><span class="label">Mean Distance From Sun: </span><input id="asteroidDist" /></div>
<div><input id="addAsteroid" type="submit" class="btn btn-small" value="Submit"></div>
</form>
<form action="javascript:void(0);">
<h2>Refresh Asteroids</h2>
<div><input id="listAsteroids" type="submit" class="btn btn-small" value="Refresh"></div>
</form>
<table id="AsteroidTable">
<tr>
<th>Asteroid</th>
<th>Diameter</th>
<th>Dimensions</th>
<th>Mean Distance From Sun</th>
</tr>
</table>
<script type="text/javascript">
function init() {
google.devrel.samples.hello.init('//' + window.location.host + '/_ah/api');
}
</script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
</div>
</body>
</html>
And here is my FirebaseApp.js:
function loginEvent()
{
const email = document.getElementById('txtEmail');
const pass = document.getElementById('txtPassword');
email.value = "HELLO";
email.value = firebase.app().name;
pass.value = "NO";
firebase.auth().signInWithEmailAndPassword(email, pass)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
});
pass.value = "YES"
}
function signupEvent()
{
const email = document.getElementById('txtEmail');
const pass = document.getElementById('txtPassword');
firebase.auth().createUserWithEmailAndPassword(email, pass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
}
I was changing the values of the email and password just to make sure I was reaching that point. printing out the value of firebase.app().name returns [DEFAULT]. I also made sure email/password option was selected in Firebase. Thank you for any help you can provide.
You only need to include https://www.gstatic.com/firebasejs/4.3.1/firebase.js which contains all the modules needed. No need to include all the others: firebase-app.js, firebase-auth.js, etc.
Also signInWithEmailAndPassword and createUserWithEmailAndPassword accept string arguments. You are passing input elements instead. There should errors thrown in the console because of this. So instead of email, pass email.value.

Use different Login page for AdminLTE

I used AdminLTE for Laravel 5.3. But i want to use my login page with connect to we server.
When i replace my code with auth/login.blade.php page, when i put my username and password and connect to web service, after get response from we server, i try to redirect to another page with window.location.href = "/AddStudent";. but page refresh and stay in login page. How must i do? which setting must i change?
<link rel="stylesheet" href="FileOfLogin/css/style.css">
<div class="wrapper">
<div class="container">
<h1>Welcome</h1>
<form class="form">
<input id="username" type="text" placeholder="Username">
<input id="password" type="password" placeholder="Password">
<button id="loginsubmit" type="button" id="login-button">Login</button>
</form>
</div>
<ul class="bg-bubbles">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="FileOfLogin/js/index.js"></script>
<!-- jQuery 2.1.3 -->
<script src="{{ asset ("/bower_components/AdminLTE/plugins/jQuery/jQuery-2.2.3.min.js") }}"></script>
<!-- Sweet Alarm -->
<script src="SweetAlert/sweetalert-dev.js"></script>
<link rel="stylesheet" href="SweetAlert/sweetalert.css">
<script type="text/javascript">
$( "#loginsubmit" ).click(function() {
console.log('111');
var username=$('#username').val();
var password=$('#password').val();
// console.log(username);
// console.log(password);
$.ajax({
type: "POST",
url: "http://79.132.212.50:8080/SchoolServiceWebService/login",
contentType: 'application/json',
data: '{ "username": "'+username+'", "password": "'+password+'" }',
dataType: "json",
success: function (GetResult) {
// console.log(GetResult);
if (GetResult.result) {
console.log(GetResult);
console.log("8888888888888");
window.location.href = "/AddStudent";
// window.location.replace('/AddStudent');
} else {
sweetAlert("خطا", "ورود !!!!!!", "error");
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
})//ajax
});
</script>
One way to do it is to override the methods in "Auth\LoginController". This way, you can specify your own view and redirect to a custom page. For more information about Laravel Authentication Mechanism, check this oficial page

Angular states and Browser back button

I am trying to adapt the following code:
Plunker
Here is the code:
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title>AngularJS: UI-Router Quick Start</title>
<!-- Bootstrap CSS -->
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter- bootstrap/2.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container">
<div class="navbar">
<div class="navbar-inner">
<a class="brand" ui-sref="index">Quick Start</a>
<ul class="nav">
<li><a ui-sref="index">Home</a></li>
<li><a ui-sref="route1">Route 1</a></li>
<li><a ui-sref="route2">Route 2</a></li>
</ul>
</div>
</div>
<div class="row">
<div class="span6">
<div class="well" ui-view="LeftMenu"></div>
</div>
<div class="span6">
<div class="well" ui-view="Content"></div>
</div>
</div>
<!-- Angular -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>
<!-- UI-Router -->
<script src="//angular-ui.github.io/ui-router/release/angular-ui-router.js"></script>
<!-- App Script -->
<script>
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider){
$stateProvider
.state('index', {
url: "",
views: {
"LeftMenu": {
template: '<ul><li><a ui-sref="index.LeftMenuMenu1">Index-Left Menu1</a></li><li><a ui-sref="index.LeftMenuMenu2">Index-Left Menu2</a></li><li><a ui-sref="index.LeftMenuMenu3">Index-Left Menu3</a></li></ul>'
},
"Content": {
template: "<div ui-view></div>"
}
}
})
.state('index.LeftMenuMenu1', {
template: "LeftMenu.Menu1 selected"
})
.state('index.LeftMenuMenu2', {
template: "LeftMenu.Menu2 selected"
})
.state('index.LeftMenuMenu3', {
template: "LeftMenu.Menu3 selected"
})
.state('route1', {
url: "/route1",
views: {
"LeftMenu": {
template: '<ul><li><a ui-sref="Route1.Menu1">Route1-Left Menu1</a></li><li><a ui-sref="Route1.Menu2">Route1-Left Menu2</a></li><li><a ui-sref="Route1.Menu3">Route1-Left Menu3</a></li></ul>'
},
"viewB": {
template: "route1.viewB"
}
}
})
.state('route2', {
url: "/route2",
views: {
"LeftMenu": {
template:'<ul><li>Route2-Left Menu1</li><li>Route2-Left Menu2</li><li>Route2-Left Menu3</li></ul>'
},
"viewB": {
template: "route2.viewB"
}
}
})
});
</script>
It definitely works fine. What I'd like to have is when I click on Back button it doesn't go back to the previous vertical state if they were selected, but instead goes back to the previous state on the horizontal menu.
Is that possible?
Thanks

jQuery getJSON not working on Internet Explorer 11

I have a site that uses jQuery within the Codeigniter framework. It works perfectly in both Firefox and Chrome. However in IE the getJSON does not work, jQuery load() works but not getJSON. Ive tried the $.ajaxSetup{{cache:false}} among others but no joy.
var url="../../index.php/cslcontrol/";
$(document).ready(function(){
//hide divs with the class '.views' except the one with id of 'home'
$(".views:not('#home')").hide();
//function that ensures only the div related to the selected menubar icon is dislayed
$("li a[href]").click(function(){
//storing the value of the clicked list a href
var tabVal=$(this).attr('value');
//showing a div whose div name is the same as the value of the selected list ahref
$("#"+tabVal).show();
//keeping the other divs hidden
$(".views[id!="+tabVal+"]").hide();
});
$("#home_text").load("css/history.html #home_txt");
$("#eighties_text").load("images/Eighties_seasons.html h1, p");
$("#nineties_text").load("images/Nineties_seasons.html h1, p");
//making a ajax call to fill the champions table
$.getJSON(url+"titleWin", function(data){
$.each(data, function(){
$("#senior_champions").append("<tr><td>"+ this["Season"] + "</td><td>"+ this["Winner"] + "</td><td>" + this["Runner up"] + "</td><td>"+ this["Play off"] + "</td></tr>");
});
});
//making a ajax call to fill the senior cup table
$.getJSON(url+"senCup", function(data){
$.each(data, function(){
$("#senior_cup_finals").append("<tr><td>"+ this["Season"] + "</td><td>"+ this["Winner"] + "</td><td>" + this["Score"] + "</td><td>"+ this["Runner-up"] + "</td></tr>");
});
});
$.getJSON(url+"getClub", function(data){
$.each(data, function(){
$("#club_info").append("<a class=\"name\" role=\"button\" data-toggle=\"modal\" data-target=\"#modalCSL\">"+this["Club"]+"</a>");
});
var crests = [];
$.each(data, function(){
if(this["Image"]!=""){
crests.push("<img src=\"images/"+this["Image"]+"\" alt=\""+this["Image"]+"\" title=\""+this["Club"]+"\"/>");
}
});
$("#pix1").html(crests.slice(0, 5));
$("#pix2").html(crests.slice(5, 10));
$("#pix3").html(crests.slice(10, 15));
});
});
$(document).ajaxSuccess(function(event,xhr,settings){
//if(settings.url=="history.txt"){
// $("#home_text").append("<div class=\"home-images\">do</div>");
//}
if(settings.url==url+"senCup"){
$("#senior_cup_finals td:eq(26), #senior_cup_finals td:eq(30)").append("<sup> R</sup>");
$("#senior_cup_finals td:eq(34)").append("<sup> R-p</sup>");
}
if(settings.url==url+"titleWin"){
$("#champions td:eq(11)").append("<sup> R</sup>");
$("#champions td:eq(52)").append("<sup> Gr</sup>");
$("#champions td:eq(56)").append("<sup> Pr</sup>");
}
if(settings.url==url+"getClub"){
$(".name").click(function(){
var aref= $(this).text();
$(".modal-body").load("css/history.html h1:contains('"+aref+"'), h1:contains('"+aref+"')+p");
$(".modal-footer").html("<button id=\"butt\" name=\""+aref+"\" value=\""+aref+"\">"+aref+" honours</button><div id=\"dead\"></div>");
});
$("#club_info .name:last-of-type").css({"margin-right":"50%"});
}
if(settings.url=="css/history.html"){
$("#butt").click(function(){
var testing=$(this).attr('value');
var testclean=encodeURIComponent(testing);
$.getJSON(url+"getHonours?name="+testclean, function(data){
var honours=[];
$.each(data, function(){
honours.push("<table class=\"table\" id=\"honstab\"><tr><th>"+data[0]["Source"]+"</th><th>"+data[1]["Source"]+"</th><th>"+data[2]["Source"]+"</th><th>"+data[3]["Source"]+"</th><th>"+data[4]["Source"]+"</th><th>"+data[5]["Source"]+"</th><th>"+data[6]["Source"]+"</th><th>"+data[7]["Source"]+"</th><th>"+data[8]["Source"]+"</th></tr><tr><td>"+data[0]["COUNT(*)"]+"</td><td>"+data[1]["COUNT(*)"]+"</td><td>"+data[2]["COUNT(*)"]+"</td><td>"+data[3]["COUNT(*)"]+"</td><td>"+data[4]["COUNT(*)"]+"</td><td>"+data[5]["COUNT(*)"]+"</td><td>"+data[6]["COUNT(*)"]+"</td><td>"+data[7]["COUNT(*)"]+"</td><td>"+data[8]["COUNT(*)"]+"</td></tr></table>");
$("#dead").html(honours.slice(0,1));
$("#honstab td").each(function(){
if ($(this).html()=="0"){
trial=$(this).index();
$("#honstab th:eq("+trial+"), #honstab td:eq("+trial+")").remove();
if($("#honstab tr").html()==0){
$("#honstab").html("<tr><th>No Honours</th></tr></table>");
}
}
});
});
});
});
}
});
<!--Heres the view file-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="../../docs-assets/ico/favicon.png">
<link href='http://fonts.googleapis.com/css?family=Anton' rel='stylesheet' type='text/css'>
<title>Connacht Senior League</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet" type='text/css'>
<link href="css/main-style.css" rel="stylesheet" type='text/css'>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="heading">
<h1>Connacht Senior League</h1>
</div>
<nav class="navbar navbar-default" id="csl-navbar" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<!--creates the toggle button that displays the menu in small screen formats-->
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"></a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav" id="accordion" role="tablist" aria-multiselectable="false">
<li>Home</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">History<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li>Eighties Seasons</li>
<li>Nineties Seasons</li>
</ul>
</li>
<li>Clubs</li>
<li>Champions</li>
<li>Senior-Cup</li>
</ul>
<!-- for the search and go form on the right of navbar-->
<form class="navbar-form navbar-right" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Go</button>
</form>
</div>
</nav>
<div id="home" class="views">
<div class="row">
<div class="col-xs-12" id="home_text">
</div>
<div class="col-xs-12" id="home_image">
<img src="images/home_page.png"/>
</div>
<div class="col-xs-12" id="ina_logo">
<img src="images/ina.PNG" width="30%"/>
</div>
</div>
</div>
<div id="eighties" class="views">
<div class="row">
<div class="col-xs-12" id="eighties_text">
</div>
</div>
</div>
<div id="nineties" class="views">
<div class="row">
<div class="col-xs-12" id="nineties_text">
</div>
</div>
</div>
<div id="clubs" class="views">
<div class="row">
<div class="col-xs-12">
<div id="club_info">
<div class="modal fade bs-example-modal-lg" id="modalCSL" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body">
...
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="champions" class="views">
<div class="row">
<div class="col-xs-12">
<h1>Champions</h1>
<p>The following table lists the League Champions and sides who finished Second. Goal differnece did not count so occassionally Play-offs were needed. An exception is the case of the 94-95 season where the League was split into two groups so a Play-off was mandatory. In 96-97 the season had Two divisions, the table only shows details of the Premier Division with First Division details in the footnotes</p>
<table class="table table-striped" id="senior_champions">
<tr>
<th>Season</th>
<th>Winner</th>
<th>Runner-up</th>
<th>Play off</th>
</tr>
</table>
<div class="notes"><p><a name="merv_salt" id="merv_salt"></a>R: 2nd Replay after two 2-2 draws</p>
<p><a name="straide" id="straide"></a>Gr: League split into 2 groups with group winners meeting in a play-off final. Top 3 teams in each group would go into a Premiership and the rest into a first division</p>
<p><a name="prem" id="prem"></a>Pr: This season had a Premiership and a First Division. Ballinasloe Town were First Division Champs.</p>
</div>
</div>
</div>
</div>
<div id="senior_cup" class="views">
<div class="row">
<div class="col-xs-12">
<h1>Senior Cup</h1>
<p>The following table lists details of the Senior Cup Finals. This was the main knockout competition involving the Connacht Senior clubs. However champions from the four junior leagues were also included and they are highlighted with a (J)</p>
<table class="table table-striped" id="senior_cup_finals">
<tr>
<th>Season</th>
<th>Winner</th>
<th>Score</th>
<th>Runner-up</th>
</tr>
</table>
<div class="notes"><p><a name="calry_merv" id="calry_merv"></a>R: Replay after 1-1 draw</p>
<p><a name="salt_calry" id="salt_calry"></a>R-p: Replay won on penalties after 1-1 draw</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" pause="onload">
<!-- Wrapper for slides-->
<div class="carousel-inner" role="listbox">
<div class="item active" id="pix1">
</div>
<div class="item" id="pix2">
</div>
<div class="item" id="pix3">
</div>
</div>
</div>
</div>
<!--[if lt IE 9]>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
<script src="http://code.jquery.com/jquery-2.0.3.js"></script>
<!--<![endif]-->
<script src="js/bootstrap.js"></script>
<script src="js/csl.js" type="text/javascript">
</script>
</body>
</html>
Right then, it seems that IE had a problem with the js file. It does not like the fact I have the global 'url' variable outside of all functions. So I had to name this variable within the (document).ready(function{}). Also I had the ajaxSuccess and ajaxError functions operating on their own, they also needed to be brought within the (document).ready function, merely naming the url variable inside them individually did not work. Basically everything needs to be wrapped in one main function. this link here inspired the solution http://patrickgibson.com/news/andsuch/000202.php
$(document).ready(function(){
var url="../../index.php/cslcontrol/";
//$.ajaxSetup({ global: true });
//hide divs with the class '.views' except the one with id of 'home'
$(".views:not('#home')").hide();
//function that ensures only the div related to the selected menubar icon is dislayed
$("li a[href]").click(function(){
//storing the value of the clicked list a href
var tabVal=$(this).attr('value');
//showing a div whose div name is the same as the value of the selected list ahref
$("#"+tabVal).show();
//keeping the other divs hidden
$(".views[id!="+tabVal+"]").hide();
});
$("#home_text").load("css/history.html #home_txt");
$("#eighties_text").load("images/Eighties_seasons.html h1, p");
$("#nineties_text").load("images/Nineties_seasons.html h1, p");
//making a ajax call to fill the champions table
$.getJSON(url+"titleWin", function(data){
$.each(data, function(){
$("#senior_champions").append("<tr><td>"+ this["Season"] + "</td><td>"+ this["Winner"] + "</td><td>" + this["Runner up"] + "</td><td>"+ this["Play off"] + "</td></tr>");
});
});
//making a ajax call to fill the senior cup table
$.getJSON(url+"senCup", function(data){
$.each(data, function(){
$("#senior_cup_finals").append("<tr><td>"+ this["Season"] + "</td><td>"+ this["Winner"] + "</td><td>" + this["Score"] + "</td><td>"+ this["Runner-up"] + "</td></tr>");
});
});
$.getJSON(url+"getClub", function(data){
$.each(data, function(){
$("#club_info").append("<a class=\"name\" role=\"button\" data-toggle=\"modal\" data-target=\"#modalCSL\">"+this["Club"]+"</a>");
});
var crests = [];
$.each(data, function(){
if(this["Image"]!=""){
crests.push("<img src=\"images/"+this["Image"]+"\" alt=\""+this["Image"]+"\" title=\""+this["Club"]+"\"/>");
}
});
$("#pix1").html(crests.slice(0, 5));
$("#pix2").html(crests.slice(5, 10));
$("#pix3").html(crests.slice(10, 15));
});
$(document).ajaxSuccess(function(event,xhr,settings){
//var json="http://davestest.webuda.com/index.php/cslcontrol/";
//if(settings.url=="history.txt"){
// $("#home_text").append("<div class=\"home-images\">do</div>");
//}
if(settings.url==url+"senCup"){
$("#senior_cup_finals td:eq(26), #senior_cup_finals td:eq(30)").append("<sup> R</sup>");
$("#senior_cup_finals td:eq(34)").append("<sup> R-p</sup>");
}
if(settings.url==url+"titleWin"){
$("#champions td:eq(11)").append("<sup> R</sup>");
$("#champions td:eq(52)").append("<sup> Gr</sup>");
$("#champions td:eq(56)").append("<sup> Pr</sup>");
}
if(settings.url==url+"getClub"){
$(".name").click(function(){
var aref= $(this).text();
$(".modal-body").load("css/history.html h1:contains('"+aref+"'), h1:contains('"+aref+"')+p");
$(".modal-footer").html("<button id=\"butt\" name=\""+aref+"\" value=\""+aref+"\">"+aref+" honours</button><div id=\"dead\"></div>");
});
$("#club_info .name:last-of-type").css({"margin-right":"50%"});
}
if(settings.url=="css/history.html"){
$("#butt").click(function(){
var testing=$(this).attr('value');
var testclean=encodeURIComponent(testing);
$.getJSON(url+"getHonours?name="+testclean, function(data){
var honours=[];
$.each(data, function(){
honours.push("<table class=\"table\" id=\"honstab\"><tr><th>"+data[0]["Source"]+"</th><th>"+data[1]["Source"]+"</th><th>"+data[2]["Source"]+"</th><th>"+data[3]["Source"]+"</th><th>"+data[4]["Source"]+"</th><th>"+data[5]["Source"]+"</th><th>"+data[6]["Source"]+"</th><th>"+data[7]["Source"]+"</th><th>"+data[8]["Source"]+"</th></tr><tr><td>"+data[0]["COUNT(*)"]+"</td><td>"+data[1]["COUNT(*)"]+"</td><td>"+data[2]["COUNT(*)"]+"</td><td>"+data[3]["COUNT(*)"]+"</td><td>"+data[4]["COUNT(*)"]+"</td><td>"+data[5]["COUNT(*)"]+"</td><td>"+data[6]["COUNT(*)"]+"</td><td>"+data[7]["COUNT(*)"]+"</td><td>"+data[8]["COUNT(*)"]+"</td></tr></table>");
$("#dead").html(honours.slice(0,1));
$("#honstab td").each(function(){
if ($(this).html()=="0"){
trial=$(this).index();
$("#honstab th:eq("+trial+"), #honstab td:eq("+trial+")").remove();
if($("#honstab tr").html()==0){
$("#honstab").html("<tr><th>No Honours</th></tr></table>");
}
}
});
});
});
});
}
});
$(document).ajaxError(function(event, jqxhr, settings){
if(settings.url==url+"senCup"){
alert("not loading");
}
});
});
Try to use Knockout binding and method ko.toJS in your view model js.

I need clic twice or cannot get the the data form

I have the following problem.
If I put he JavaScript code into the head or body tag, I need to click twice the submit button and then the Ajax form or whatever I need to do it does correctly, but I need to click twice.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>XXXX</title>
<!--Este es el JS que hace que funcione Phonegap-->
<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<!--JS específicos de Jquery Mobile-->
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/jquery.mobile-1.4.2.min.js"></script>
<!--Estos son script creados para la aplicacion-->
<script src="js/md5.js"></script>
<script src="js/login.js"></script>
<!--CSS del tema que he creado para apotecalia-->
<link rel="stylesheet" href="themes/XXXX.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="css/jquery.mobile.structure-1.4.2.min.css" />
</head>
<div id="login">
<div data-role="header" data-position="fixed">
</div>
<div data-role="content">
<form id="check-user" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label> Usuario </label>
<input type="text" id="correo" name="correo">
</div>
<div data-role="fieldcontain">
<label> Contraseña </label>
<input type="password" id="pwd" name="pwd" >
</div>
<input type="submit" data-role="button" value="Acceder" name="enviar" id="enviar">
</fieldset>
</form>
</div>
<div data-role="footer" data-position="fixed">
</div>
</div>
</body>
</html>
Login.js
$(function () {
$('#enviar').click( function() {
if($('#correo').val().length > 0 && $('#pwd').val().length > 0){
alert($('#correo').val() + $('#pwd').val());
}
});
});
But if I put the script code into the tag page where I need to use it, I don't need to click twice, but I cannot get the data form to do my Ajax request.
The same code, but if I put the script code into data-role="page" I have to put this code into all the tags... The alert in this case is empty.
<div id="login">
<script src="js/login.js"></script>
<div data-role="header" data-position="fixed">
</div>
<div data-role="content">
Please I don't know how to do it, I tried two weeks fixing this, I need your help.
Add simple type="button" instead of type="submit" .
<input type="button" data-role="button" value="Acceder" name="enviar" id="enviar">
$(function () {
$('#enviar').click( function() {
if($('#correo').val().length > 0 && $('#pwd').val().length > 0){
alert($('#correo').val() + $('#pwd').val());
// Add code here submit form data using Ajax
var ajax_call = your_serviceURL;
var str = $('#check-user').serialize();
$.ajax({
type: "POST",
url: ajax_call,
data: str,
dataType: "json",
success: function(response){
// It's success json response
}
}).done(function() {
})
}
});
});
Include your script in the head tag.
Declare your page container <div data-role="page" id="login">.
Change your code in login.js to:
$(document).on("pageinit", "#login", function(event, ui)
{
$(document).on("click", "#enviar", function(event)
{
if ($('#correo').val().length > 0 && $('#pwd').val().length > 0)
alert($('#correo').val() + $('#pwd').val());
});
});