Unable to use firebase.auth from my js file - javascript

Problem
: getting an error when I try to use firebase.auth to create a new user.
Error
Uncaught TypeError: firebase.auth.createUserWithEmailAndPassword is not a function
What should happen : In my html there is a form for user sign up with email and password. On button click my script takes the input from the sign up form and passes it to firebase.auth however firebase.auth seems to not be available from an external script that is being included into the html file. The html file does have the firebase includes and I can deploy my code into firebase hosting, I already went through the firebase localhost installation process from the firebase docs.
Here is my HTML
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Sign Up</title>
<link href="https://fonts.googleapis.com/css?family=Nunito:300,400,400i,600,700,800,900" rel="stylesheet">
<link href="dist-assets/css/themes/lite-purple.min.css" rel="stylesheet">
<!-- update the version number as needed -->
<script defer src="/__/firebase/7.12.0/firebase-app.js"></script>
<!-- include only the Firebase features as you need -->
<script defer src="/__/firebase/7.12.0/firebase-auth.js"></script>
<script defer src="/__/firebase/7.12.0/firebase-database.js"></script>
<script defer src="/__/firebase/7.12.0/firebase-messaging.js"></script>
<script defer src="/__/firebase/7.12.0/firebase-storage.js"></script>
<!-- initialize the SDK after all desired features are loaded -->
<script defer src="/__/firebase/init.js"></script>
<link href="https://fonts.googleapis.com/css?family=Nunito:300,400,400i,600,700,800,900" rel="stylesheet">
<link href="dist-assets/css/themes/lite-purple.min.css" rel="stylesheet">
</head>
<div class="auth-layout-wrap" style="background-image: url(dist-assets/images/photo-wide-4.jpg)">
<div class="auth-content">
<div class="card o-hidden">
<div class="row">
<div class="col-md-6 text-center" style="background-size: cover;background-image: url(dist-assets/images/photo-long-3.jpg)">
<div class="pl-3 auth-right">
<div class="auth-logo text-center mt-4"><img src="dist-assets/images/car.png" alt=""></div>
<div class="flex-grow-1"></div>
<div class="w-100 mb-4"><a class="btn btn-outline-primary btn-block btn-icon-text btn-rounded" href="/"><i class="i-Mail-with-At-Sign"></i> Sign in with Email</a><a class="btn btn-outline-google btn-block btn-icon-text btn-rounded"><i class="i-Google-Plus"></i> Sign in with Google</a><a class="btn btn-outline-facebook btn-block btn-icon-text btn-rounded"><i class="i-Facebook-2"></i> Sign in with Facebook</a></div>
<div class="flex-grow-1"></div>
</div>
</div>
<div class="col-md-6">
<div class="p-4">
<h1 class="mb-3 text-18">Sign Up</h1>
<form action="">
<div class="form-group">
<label for="username">Your name</label>
<input class="form-control form-control-rounded" id="username" type="text">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input class="form-control form-control-rounded" id="email" type="email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input class="form-control form-control-rounded" id="password" type="password">
</div>
<div class="form-group">
<label for="repassword">Retype password</label>
<input class="form-control form-control-rounded" id="repassword" type="password">
</div>
<button onclick="signUpWithEmail(event)" class="btn btn-primary btn-block btn-rounded mt-3">Sign Up</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// // 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
// // The Firebase SDK is initialized and available here!
//
// firebase.auth().onAuthStateChanged(user => { });
// firebase.database().ref('/path/to/ref').on('value', snapshot => { });
// firebase.messaging().requestPermission().then(() => { });
// firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
//
// // 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
try {
let app = firebase.app();
let features = ['auth', 'database', 'messaging', 'storage'].filter(feature => typeof app[feature] === 'function');
const auth = firebase.auth();
console.log(features);
} catch (e) {
console.error(e);
}
});
</script>
<script src="dist-assets/js/app-js/app-dist.js"></script>
And Here is my js
//Sign up with email and password
function signUpWithEmail(e){
e.preventDefault();
var name = document.getElementById("username").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var passwordMatch = document.getElementById("repassword").value;
//Create user
auth.createUserWithEmailAndPassword(email, password).then(cred => {
console.log(cred);
})
//Get UID
//Create New Collection identified by UID
//Create user info document
//Add user email and name to user info document
}

I was calling firebase.auth.createUserWithEmailAndPassword()
It should have been firebase.auth().createUserWithEmailAndPassword() which I did do right on my sign in method using auth()..
Yep Im kicking myself right now

Related

How to display error on the same page when an error is returned by a form?

I have built a login form using below code.
I am using a CGI version CGIDEV2 native to IBMi series. I am Validating the userid and password in the flower.cgi program. If the userid and password are validated, I am loading another html file to show a table. This works flawlessly.
If the userid and password are wrong, I am returning out of the program without writing anything. This results in a 500 Internal server error.
I want to capture this 500 Internal server error using javascript. I have tried using ajax but was not successful as I have limited understanding of javascript.
What could be the best way to achieve this?
<form method="POST" action="/nature/flower.cgi">
<!-- Username input -->
<div class="form-outline mb-4">
<input type="text" name="userid" id="form3Example3" class="form-control form-control-lg" style="text-transform:uppercase" placeholder="Enter a valid IBMi UserID" />
<label class="form-label" for="form3Example3">IBMi UserID</label>
</div>
<!-- Password input -->
<div class="form-outline mb-3">
<input type="password" name="passwd" id="form3Example4" class="form-control form-control-lg" placeholder="Enter password" />
<label class="form-label" for="form3Example4">Password</label>
<br>
</div>
<div class="d-flex justify-content-between align-items-center">
<!-- Checkbox -->
<div class="form-check mb-0">
<input class="form-check-input me-2" type="checkbox" value="" id="form2Example3" />
<label class="form-check-label" for="form2Example3">Remember me</label>
</div>
Forgot password?
</div>
<div class="text-center text-lg-start mt-4 pt-2">
<button type="submit" class="btn btn-primary btn-lg" style="padding-left: 2.5rem; padding-right: 2.5rem;">Login</button>
</div>
</form>
You can't capture an error from a URL the browser is navigating to.
The only way you could would be if you replaced the normal form submission with Ajax (in which the request is made and the response processed with JavaScript).
Generally speaking, if you were going to do that you would also want to rewrite the CGI program so it output structured data (e.g. as JSON) instead of semantic data (HTML).
It would not be a particularly small undertaking. You said you had tried it, which probably gives you some idea of the scope of it (i.e. far outside the scope of a Stackoverflow question).
A more sensible approach would almost certainly be to track down the cause of the 500 error and change the CGI program so it would capture it itself.
yes, the fetch api in javascript can post form data to your CGI program and check for the 500 response code. Then the web page can either display an error message or run the form.submit() method to actually submit the form up to the server.
Here is PHP and javascript code that simulates the whole thing. Should work similar with CGI. The key is you change the form submit button from type 'submit' to type 'button'. That way, clicking the submit button can run javascript code instead of the form being submitted to the server.
<?php
// site/tester/php/submit-form.php
header("Content-type: text/html; charset:utf-8;");
?>
<?php
$userid = isset($_POST["userid"]) ? $_POST["userid"]: '' ;
$passwd = isset($_POST["passwd"]) ? $_POST["passwd"]: '' ;
$remember = isset($_POST["remember"]) ? $_POST["remember"]: 'off' ;
if ( strtolower($userid) == 'alex')
{
http_response_code( 500 );
echo "$userid - invalid user name";
exit ;
}
?>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row mt-3">
<div class="col-auto">
<h1>submit form demo</h1>
</div>
</div>
</div>
<div class="container">
<div class="row mt-3">
<div class="col-4">
<form method="POST" id="main-form" action="./index.php">
<!-- Username input -->
<div class="form-outline mb-4">
<input type="text" name="userid" id="userid"
class="form-control form-control-lg"
value="<?= $userid ?>"
style="text-transform:uppercase" placeholder="Enter a valid IBMi UserID" />
<label class="form-label" for="userid">IBMi UserID</label>
</div>
<!-- Password input -->
<div class="form-outline mb-3">
<input type="password" name="passwd" id="passwd" class="form-control form-control-lg"
placeholder="Enter password" />
<label class="form-label" for="passwd">Password</label>
<br>
</div>
<div class="d-flex justify-content-between align-items-center">
<!-- Checkbox -->
<div class="form-check mb-0">
<input class="form-check-input me-2" type="checkbox"
<?= ($remember == 'on' ? 'checked' : '' ) ?>
name="remember" id="form2Example3" />
<label class="form-check-label" for="form2Example3">Remember me</label>
</div>
Forgot password?
</div>
<div class="text-center text-lg-start mt-4 pt-2">
<button id="login-button" type="button" class="btn btn-primary btn-lg"
style="padding-left: 2.5rem; padding-right: 2.5rem;">
Login</button>
</div>
</form>
</div>
</div>
<div id="login-errmsg-collapse" class="collapse row mt-3">
<div class="alert alert-warning" role="alert">
<p id="login-errmsg">Invalid login. User name does not exist.</p>
</div>
</div>
</div>
<div class="container">
<div class="row mt-3">
<div class="col-auto">
<p>userid: <?= $userid ?></p>
<p>passwd: <?= $passwd ?></p>
<p>remember: <?= $remember ?></p>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<script src="./app.js"></script>
</body>
// ./submit-form/app.js
// enable the submit button click handler.
{
const elem = document.getElementById('login-button');
elem.addEventListener('click', event =>
{
login_click();
});
}
// -------------------------------- login_errmsg_show ---------------------
function login_errmsg_show( respText )
{
// show the response message in the bootstrap collapse alert box.
{
const elem = document.getElementById('login-errmsg') ;
elem.textContent = respText ;
}
const myCollapse = document.getElementById('login-errmsg-collapse')
const bsCollapse = new bootstrap.Collapse(myCollapse, {
toggle: false
});
bsCollapse.show( ) ;
}
// -------------------------------- login_click -------------------
async function login_click()
{
const elem = document.getElementById('main-form');
if (elem)
{
const {respText, status} = await webpage_post( ) ;
if ( status != '500')
{
elem.submit();
}
else
{
login_errmsg_show( respText ) ;
}
}
}
// --------------------------------- webpage_post -----------------------
async function webpage_post( )
{
const userid = document.getElementById('userid').value ;
const passwd = document.getElementById('passwd').value ;
const remember = 'on' ;
const url = "./index.php";
const params = { userid, passwd, remember } ;
const query = object_toQueryString(params);
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: query
});
const respText = await response.text();
const status = response.status ;
console.log( respText ) ;
return {respText, status} ;
}
// ------------------------- object_toQueryString ------------------------
function object_toQueryString(obj)
{
const qs = Object.keys(obj)
.map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
.join('&');
return qs;
}

Bootstrap validation is not showing the error message for empty input on submit

I am trying to add a Bootstrap validation in a form. My expected results is:
When the form is submitted, if "First name" field is empty, the "Please enter a name" message should be displayed below the field, otherwise "Looks good" should be displayed.
I tried it by adding and removing "d-none" class in the javascript, but the problem is "Looks good" is disappearing but "Please enter a name" is not displaying.
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
var invalidOptions = document.querySelectorAll(".form-control:invalid");
invalidOptions.forEach(function (element) {
element.parentNode.childNodes.forEach(function (node) {
if (node.className == 'valid-feedback') {
node.classList.add('d-none');
}
});
});
var validOptions = document.querySelectorAll(".form-control:valid");
invalidOptions.forEach(function (element) {
element.parentNode.childNodes.forEach(function (node) {
if (node.className == 'invalid-feedback') {
node.classList.remove('d-none');
}
});
});
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationServer01">First name</label>
<input type="text" class="form-control is-valid" id="validationServer01" placeholder="First name" value="Mark"
required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback d-none">Please enter a name</div>
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</div>
</form>
</body>
</html>
Your js code is Bootstrap will manage the showing & hiding of the valid-feedback and invalid-feedback depending on whether the content is valid. By manually adding d-none to the invalid-feedback, it is affecting this behaviour. Simply remove d-none from the classes and it works:
<label for="validationServer01">First name</label>
<input type="text" class="form-control is-valid"
id="validationServer01" placeholder="First name" value="Mark"
required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please enter a name</div> <!-- REMOVE d-none FROM HERE -->
Now, when you submit the form, if the name is empty it will show your "Please enter a name" message.
Working Example:
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
var invalidOptions = document.querySelectorAll(".form-control:invalid");
invalidOptions.forEach(function (element) {
element.parentNode.childNodes.forEach(function (node) {
if (node.className == 'valid-feedback') {
node.classList.add('d-none');
}
});
});
var validOptions = document.querySelectorAll(".form-control:valid");
invalidOptions.forEach(function (element) {
element.parentNode.childNodes.forEach(function (node) {
if (node.className == 'invalid-feedback') {
node.classList.remove('d-none');
}
});
});
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationServer01">First name</label>
<input type="text" class="form-control is-valid" id="validationServer01" placeholder="First name" value="Mark"
required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please enter a name</div>
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</div>
</form>
</body>
</html>

AngularJS $resource writeFileSync giving Error: ENOENT: no such file or directory, open

I have been doing a tutorial on AngularJS and am stuck on trying to fill this form and have it saved to disk as a json file using the $resource service.
I keep getting the error
Error: ENOENT: no such file or directory, open '/data/event/999.json'
app/NewEvent.html
<!doctype html>
<html lang="en" ng-app="eventsApp">
<head>
<meta charset="utf-8">
<title>Event Registration</title>
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/app.css">
</head>
<body>
<div class="container">
<div class="navbar-inner">
<ul class="nav">
<li>Create Event</li>
</ul>
</div>
<style> input.ng-invalid.ng-dirty {background-color:pink}</style>
<div ng-controller="EditEventController" style="padding-left:20px; padding-right:20px">
<div class="container">
<h1>New Event</h1>
<hr>
<form name="newEventForm">
<fieldset>
<label for="eventName">Event Name:</label>
<input id="eventName" type="text" required ng-model="event.name" placeholder="Name of your event ...">
<label for="eventDate"> Event Date</label>
<input id="eventDate" type="text" required ng-pattern="/\d\d/\d\d/\d\d\d\d/" ng-model="event.date" placeholder="format (mm/dd/yyyy)...">
<label for="eventTime">Event Time:</label>
<input id="eventTime" type="text" ng-model="event.time" placeholder="start and end time ...">
<label for="eventLocation"> Event Location</label>
<input id="eventLocation" type="text" ng-model="event.location.address" placeholder="Address of event...">
<br>
<input id="eventCity" type=text" ng-model="event.location.city" class="input-small" placeholder="City...">
<input id="eventProvince" type="text" ng-model="event.location.province" class="input-small" placeholder="Province...">
<label for="eventImageUrl">Image:</label>
<input id="eventImageUrl" type="url" ng-model="event.imageUrl" class="input-xlarge" placeholder="Url of image...">
</fieldset>
<img ng-src="{{event.imageUrl}}" src="">
<br>
<br>
<button type="submit" ng-disabled="newEventForm.$invalid" ng-click="saveEvent(event, newEventForm)" class="btn btn-primary">Save</button>
<button type="button" ng-click="cancelEdit()" class="btn btn-default">Cancel</button>
</form>
</div>
</div>
</div>
<script src="/lib/jquery.min.js"></script>
<script src="/lib/underscore-1.4.4.min.js"></script>
<script src="/lib/bootstrap.min.js"></script>
<script src="/lib/angular/angular.js"></script>
<script src="/lib/angular/angular-resource.js"></script>
<script src="/lib/angular/angular-sanitize.js"></script>
<script src="/js/app.js"></script>
<script src="/js/controllers/EventController.js"></script>
<script src="/js/controllers/EditEventController.js"></script>
<script src="/js/services/EventData.js"></script>
<script src="/js/filters.js"></script>
</body>
</html>
app/js/controllers/EditEventController.js
eventsApp.controller('EditEventController',function EditEventController($scope,eventData) {
$scope.saveEvent = function (event, newEventForm) {
if(newEventForm.$valid){
eventData.save(event)
.$promise.then(
function (response) { console.log('success',response)},
function (response) { console.log('failure',response)}
)
}
}
$scope.cancelEdit = function () {
window.location = "/EventDetails.html";
}
})
app/js/services/EventData.js
eventsApp.factory('eventData', function ($resource) {
return {
getEvent: function() {
return $resource('/data/event/:id.json',{id:'#id'}).get({id:1});
},
save: function (event) {
event.id = 999;
return $resource('/data/event/:id',{id:'#id'}).save(event);
}
}
})
scripts/eventsController.js
var fs = require('fs')
module.exports.get = function (req,res) {
var event = fs.readFileSync('/data/event/' + req.params.id ,'utf8');
res.setHeader('Content-Type','application/json');
res.send(event)
}
module.exports.save = function (req,res) {
var event = req.body;
fs.writeFileSync('/data/event/' + req.params.id +'.json', JSON.stringify(event));
res.send(event)
}
scripts and app are on the same level
EventDetails.html is inside app and in the same level as NewEvent.html
At first glance the code looks correct, could this maybe be a permission problem?

text message disapears after doing javascript validation

I have a form and I'm doing some validation JavaScript before send it to PHP, and the JavaScript function after validation post the text the user entered in a <p> tag at the bottom of the page; However, this message displays briefly and then disappears...
How can I make the message stay in the page, and send the rest of data to a PHP script?
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Contact Us</title>
<!-- Bootstrap -->
<link href="bootstrap.min.css" rel="stylesheet">
<!-- stylesheet for this form -->
<link href="contact-stylesheet.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script type="text/javascript">
function validateForm() {
var message = "";
var letters = /^[A-Za-z]+$/;
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var subject = document.forms["myForm"]["subject"].value;
var text = document.forms["myForm"]["text"].value;
var outputMsg = "";
if (name == null || name == "") {
message += "name field missing!\n";
}
if (name != "" && !name.match(letters)) {
message += "Invalid name: only letters allowed!\n";
}
if (subject == null || subject == "") {
message += "Subject field is empty!\n";
}
if (text == null || text == "") {
message += "Text field is empty!\n";
}
if (message != "" ) {
alert(message);
return false;
}
outputMsg = "Message Sent!....\n" +
"Name: " + name + "\n" +
"Email: " + email + "\n" +
"Subject: " + subject + "\n" +
"Text: " + text + "\n";
document.getElementById("msg-result").innerHTML = outputMsg;
return true;
}
</script>
</head>
<body>
<div class="row">
<div class="hero-unit" style="padding:20px 100px">
<h1>Contact Us</h1>
<p>aldkfjasdkfjaskdfasdfkasdkfjadsfjsdkfjaskfjasdkfjasjfaskdfjsdkfjsksdsdkjsd</p>
</div>
<div class="col-sm-6">
<div class="my-form">
<form class="form-horizontal" name="myForm" action="" onsubmit="validateForm()" method="post">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Name:</label>
<div class="col-sm-8">
<input type="name" name="name" class="form-control" id="inputEmail3" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Email:</label>
<div class="col-sm-8">
<input type="email" name="email" class="form-control" id="inputPassword3" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Subject:</label>
<div class="col-sm-8">
<input type="text" name="subject" class="form-control" placeholder="Subject">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Text:</label>
<div class="col-sm-8">
<textarea name="text" class="form-control" rows="7" placeholder="Text"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Send</button>
</div>
</div>
</div>
</form>
</div>
<div class="col-sm-6">
<div style="width:500px;heigth:350px;border:solid 1px brown">
<h1>GOOGLE MAP HERE!</h1>
</div>
<!-- <img sytle="padding:0px 20px" src="https://maps.googleapis.com/maps/api/staticmap?center=Miami+Downtown,Miami,FL&zoom=13&size=500x350&maptype=roadmap&markers=color:red%7CMiami+Downtown,Miami,FL"> -->
</div>
</div>
<div class="col-sm-6" style="padding:10px 140px">
<p id="msg-result"></p>
<!-- display form result message here! -->
</div>
<!--
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
It's because you are updating the text in the field and then submitting to php (wiping out all of the fields since the page refreshes). You could set hidden elements to hold the values that you want to display so they post over to php and then you can just echo them where you want them to be. Another way of doing it would be to make an ajax call to a php to do your updating instead of posting back to the same page.
So with ajax you would do something like:
formSubmit()
{
//do validation
//do a jquery post to a php page
$.ajax
({
type: "POST",
//the url of the php page
url: 'test.php',
dataType: 'json',
async: false,
//json object to sent to the authentication url
data: '{"test": "info"}',
success: function (result) {
//update stuff
}
})
return false;
}
I think the form is submitted after the check. You must return the result (to cancel the submit if validateForm() is false):
onsubmit="return validateForm();"
or prevent default:
onsubmit="return validateForm(event);"
with
function validateForm(event) {
...
event.preventDefault();

No change when click on login button in ios phonegap app

My index.html page is:
<link rel="stylesheet" href="../css/jquery.mobile-1.3.1.min.css">
<link rel="stylesheet" type="text/css" href="../css/style.css" />
<script src="../js/jquery-1.9.1.min.js"></script>
<script src="../js/jquery.mobile-1.3.1.min.js"></script>
<script src="../js/common.js"></script>
<script src="../js/cordova.js"></script>
<script src="../js/jstorage.js"></script>
<script type="text/javascript">
$(document).ready(function(){
loadHeader("YSN Login", false);
});
</script>
</head>
<body>
<!-- Home -->
<div id="header"></div>
<div class="firstDiv"></div>
<div data-role="content">
<form id="loginForm">
<div data-role="fieldcontain">
<label for="textinput6">
Email Address
</label>
<input name="username" id="username" type="text" onkeyup="toggle(this)" value="">
</div>
<span class="ValidationErrors" id="userNameMsg" style="display: none;">Should be a valid Email Id</span>
<div data-role="fieldcontain">
<label for="textinput6">
Password
</label>
<input name="password" id="password" type="password" onkeyup="toggle(this)" value="" class="btn btn-8 btn-8a">
</div>
<span class="ValidationErrors" id="passwordMsg" style="display: none;">Should be a valid password</span>
<a data-role="button" data-theme="b" onclick="loginUser();">
Login
</a>
<div>
<a href ="#" onclick="openSelfWindow('resetPassword.html')" data-transition="fade">
Forget your password?
</a>
</div>
</form>
and my loginUser function which runs on click of login button, I am calling restful web services through ajax
function loginUser(){
var loginData = new Object();
loginData.username = $("#username").val();
loginData.password = $("#password").val();
var loginObj = new function(){
this.url = ysnURL + "userservice/login/user/"
this.data = JSON.stringify(loginData)
this.success = loginSuccess
this.error = loginError
this.beforeSend = validateLoginForm//validates the login form
}
tugnavAjaxPOST(loginObj);
}
function loginSuccess(data){
console.debug(JSON.stringify(data));
stopSpinner();
if(data.success == "true"){
setSession($.parseJSON(data.message));
var ref = openSelfWindow("dashboard.html");
}
else{
showAlert("YSN Login", data.message, function(){});
}
}
function loginError(data){
console.debug(JSON.stringify(data));
stopSpinner();
showAlert("YSN Login", "Error while logging to YSN", function(){});
}
I am ruuning this app on ios simulator, when I click on resetpassword link it takes me to the next page but clicking on login button does not show any alert or in simple words screen remains same.The same code is running properly for android but not for ios,even I have included the cordova.js file for ios then also the problem remains same.

Categories