Parse.com javascript login - javascript

Hi Stackoverflow members,
I started learning javascript a couple days ago but was stumped on one of the problems i came across.
Form:
<form class="login-form" method="post" onsubmit="return tryLogin(this);">
<h3 class="form-title">Login to your account</h3>
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span>
Enter any username and password.
</span>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">Username</label>
<div class="input-icon">
<i class="fa fa-user"></i>
<input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username" id="username"/>
</div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<div class="input-icon">
<i class="fa fa-lock"></i>
<input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password" id="password"/>
</div>
</div>
<div class="form-actions">
<label class="checkbox">
<input type="checkbox" name="remember" value="1"/> Remember me </label>
<button type="submit" class="btn green pull-right">
Login <i class="m-icon-swapright m-icon-white"></i>
</button>
</div>
</form>
Javascript:
<script type="text/javascript">
jQuery(document).ready(function() {
App.init();
Login.init();
});
function tryLogin(form) {
var username = form.username.value;
var password = form.password.value;
console.log("Username: " + username + " Password: " + password);
Parse.User.logIn(username, password, {
success: function(user) {
window.location.href="dashboard.html";
//self.undelegateEvents();
//delete self;
alert("Sucess");
return true;
},
error: function(user, error) {
window.location.href="login.html";
alert("Error: " + error.code + " " + error.message + username + password);
return false;
}
});
}
</script>
The problem is that when I attempt to login I get a 100 XMLHttpRequest failed error. This only happens when I input data into the form and click log in. If i don't enter any data and click login, it correctly attempts to login. If i put the username + password directly into the javascript it also works - but doesn't through the form.
Console.log, logs the correct username and password being inputted, but the Parse.User.logIn(username, password) doesn't want to pass it in... but it works if I fill it in like this:
Parse.User.logIn("myemail#email.com", "mypassword", {....
Any help would be appreciated.
Cheers!
Edit: Here's the error
XMLHttpRequest failed: {"statusText":"","status":0,"response":"","responseType":"","responseXML":null,"responseText":"","upload":{"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null},"withCredentials":false,"readyState":4,"timeout":0,"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null}
Could it be a MAMP issue? PS: Creating new objects etc. works fine.

As you dont call preventDefault on the submit event, what happens is that it posts form when you click which has for effect to cancel the ajax call Parse.User is making.
Add event.preventDefault(); in your event handler and you should be fine.
<form class="login-form" method="post" onsubmit="tryLogin(this); event.preventDefault();">
Or better use jQuery to manage this event
$(".login-form").submit (function(event) {
...
event.preventDefault();
});

Related

Redirect to another HTML page after successfull login attempt | with JS

I have created a login form. I want a JS code that:
If the information on the login page i.e Username and Login is correct, It will proceed to another HTML page.
Simply, I want the page to redirect to another page after successfull login attempt. | With JS
I dont want any PHP or MySql code.
I have tried this code but this doesnt works. On wrong information, it says Invalid information. But on correct info, it refreshes the page and there a ? is visible at te end of the url:
Html:
<form id="form" action="" method="GET">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" id="email" class="form-control" aria-describedby="emailHelp" >
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" id="password" class="form-control" >
</div>
<button type="submit" class="btn btn-outline-success btn-lg shadow" onClick="auth()">Submit</button>
</form>
JavaScript:
function auth() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email === "admin#gmail.com" && password === "user") {
location = location['href'];
// alert("You Are a ADMIN");
} else {
alert("Invalid information");
return;
}
}
I have also used:
window.location.replace("upload.html");
instead of:
location = location['href'];
But still does not works.
A couple of things here. One you're doing a GET with your form rather than doing a POST. You should change that. Second, on your JavaScript call for auth you should pass the event parameter so that the default action of the form will be stopped. Third, you should be using a relative path for your URL within your redirect. Last, You should do a window.redirect() to simulate an HTTP redirect when the function executes.
Here is the code with the updates:
<form id="form" action="post">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email"
id="email"
class="form-control"
aria-describedby="emailHelp" >
<small id="emailHelp"
class="form-text text-muted">
We'll never share your email with anyone else.
</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" id="password" class="form-control" >
</div>
<button type="submit"
class="btn btn-outline-success btn-lg shadow"
onClick="auth(event)">Submit</button>
</form>
<script>
function auth(event) {
event.preventDefault();
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email === "admin#gmail.com" && password === "user") {
window.location.replace("/upload.html");
} else {
alert("Invalid information");
return;
}
}
</script>

function not pulling input data from local host

I am creating a simple login an sign up form that is used to create a user and store it in the local host. I have got the sign up form working as it should, but when I try and pull the information from the localhost, it just refreshes the page. Im just wondering how I can get the function to work correctly.
Here is my JS:
const signup = (e) => {
let user = {
firstName: document.getElementById("firstName").value,
lastname: document.getElementById("lastName").value,
email: document.getElementById("email").value,
username: document.getElementById("username").value,
password: document.getElementById("password").value,
confirm_password: document.getElementById("confirm_password").value,
};
localStorage.setItem("user", JSON.stringify(user));
console.log(localStorage.getItem("user"));
e.preventDefault();
alert("Signup Successful")
};
function login() {
var stored_username = localStorage.getItem('username');
var stored_password = localStorage.getItem('password');
var username1 = document.getElementById('username1');
var password2 = document.getElementById('password2');
if(username1.value == stored_username && password2.value == stored_password) {
alert('Login Successful.');
}else {
alert('Username or password is incorrect.');
}
}
document.getElementById("login-btn").addEventListener(type = click, login())
And here is my HTML:
<div class="bodyBx">
<section>
<div class="container">
<div class="user signinBx">
<div class="imgBx"><img src="https://images.unsplash.com/photo-1551034549-befb91b260e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" style="width: 400px;" alt="" /></div>
<div class="formBx">
<form>
<h2>Sign In</h2>
<input type="text" id="username2" placeholder="Username" />
<input type="password" id="password2" placeholder="Password" />
<button id = "login-btn" type="submit" onclick="login();">Submit</button>
<p class="signup">
Need an account ?
Sign Up.
</p>
</form>
</div>
</div>
</div>
</section>
<!-- ================= Sign Up Form Start ================= -->
<section>
<div class="container">
<div class="user signupBx" id="section2">
<div class="imgBx"><img src="https://images.unsplash.com/photo-1555680206-9bc5064689db?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" style="width: 400px;" alt="" /></div>
<div class="formBx">
<form role="form" onsubmit="signup(event)">
<h2>Sign Up</h2>
<input type="text" id="firstName" placeholder="First Name" />
<input type="text" id="lastName" placeholder="Last Name" />
<input type="email" id="email" placeholder="example#email.com..." />
<input type="text" id="username" placeholder="Username" />
<input type="password" id="password" placeholder="Password" />
<input type="password" id="confirm_password" placeholder="Confirm Password" />
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
</section>
</div>
Change the type of login button to button from submit, like below
<button id = "login-btn" type="button" onclick="login();">Submit</button>
If type=submit the form is posted to the url specified in the action attribute of the form, else to the same page if action is missing and you will see a page refresh.
Alternate method - You can also try return false; in your login()
Also your addEventListener should be like below, you don't have to provide type = click, the first param is of type string and second param is of type function. Check docs
document.getElementById("login-btn").addEventListener("click", login)
Localstorage can only store text. So you store a stringified object, which is fine, but you're trying to retrieve properties from it which don't exist.
Instead of:
var itm={someField:1};
localStorage.setItem("itm",JSON.stringify(itm));
//then later
localStorage.getItem("someField");
//localstorage doesnt know what someField is
You want:
var itm={someField:1};
localStorage.setItem("itm",JSON.stringify(itm));
//then later
itm = JSON.parse(localStorage.getItem("itm"));
someField = itm.someField
As for the refresh, check this out:
Stop form refreshing page on submit
TL;DR: Add e.preventDefault() in function login() (you'll have to change it to function login(e).

jquery close and reset custom box

Hello I have a simple Jquery question, I have a simple jquery popup form that displays a thank you message when users have completed it. They can then close it. I am having trouble getting the box to reset and show the original form once a user closes it.
//open popup Book a demo
$(".actionButtonHeader, .bookADemoBTN").click(function(){
$("#overlay_form").fadeIn(1000);
$(".background_overlay").fadeIn(500);
positionPopup();
e.preventDefault();
});
var email = document.getElementById("email").value;
var subscribed = document.getElementById("subscribed").value
$("#overlay_form").submit(function(e)
{
var postData = $(this).serializeArray();
$.ajax(
{
url : "demoEmailProcess.php",
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$(".formContent").html("<div id='messageDemo'><h2 style='text-align: center; font-size: 27px;'>Thank you " + (fullName.value).split(" ")[0]+ "!" + "</h2>" + "<p style='font-size: 21px;'> Your message has beeen successfully sent. We appreciate your interest in Cybertonica and will get back to you within the next 24 hours. </p>" + "<a class='messageLink' href='index.php'>Return to Homepage</a></div>")
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault();
});
$("#ajaxform").submit(); //Submit the FORM
//close popup Book a demo
$(".close").click(function(){
$("#overlay_form").fadeOut(500);
$(".background_overlay").fadeOut(500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="background_overlay"></div>
<form id="overlay_form" style="display:none" action="" method="post" >
<div class="close"><div class="innerClose">X</div></div>
<div class="formContent">
<b class="popupText">Want to see how we manage fraud and increase sales? We would love to hear from you. Book a demo with Cybertonica!</b>
<p class="popupText">Briefly explain your business needs and how you manage fraud and we will happily get back to you within the next 24 hours.</p>
<p id="returnmessage"></p>
<div class="popupRowOne">
<li><b>Full Name<sup>*</sup></b>
<input id="fullName" name="fullName" required type="text">
</li>
<li><b>Company Name<sup>*</sup></b>
<input required name="companyName" id="companyName" type="text"></li>
</div>
<div class="popupRowTwo">
<li><b>Email<sup>*</sup></b>
<input required name="address" id="address" type="text">
</li>
<li><b>Job Title<sup>*</sup></b>
<input required name="jobTitle" id="jobTitle" type="text">
</li>
<li id="hiddenPot"><b>Please leave this blank<sup>*</sup></b>
<input type="text" name="email" id="email">
</li>
</div>
<div class="popupRowThree">
<li><b>Your Message<sup>*</sup></b>
<input name="textMessage" id="textMessage" class="textareaPopup" required>
</li>
</div>
<div id="contactSubscribe">
<p class="checkBoxText"><input type="checkbox" id="subscribed" value="subscribed" name="subscribed" checked> I would like to sign up to Cybertonica newsletter</p>
<button type="submit" id="submit" value="Submit" class="popUpactionButton">Submit</button>
</div>
</div>
</form>
Try this:
After:
$(".background_overlay").fadeOut(500);
Add this line:
$("#overlay_form").reset();

submit a form and prevent from refreshing it

i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}

Meteor.call method not found

I am working my way through the Microscope project in Discover Meteor and I have hit a problem. I am getting a 'Method not found' error for the following code:
HTML Template - microscope/client/templates/posts/post_submit.html
<template name="postSubmit">
<form class="main form">
<div class="form-group">
<label class="control-label" for="url">URL</label>
<div class="controls">
<input name="url" id="url" type="text" value="" placeholder="Your URL" class="form-control"/>
</div>
</div>
<div class="form-group">
<label class="control-label" for="title">Title</label>
<div class="controls">
<input name="title" id="title" type="text" value="" placeholder="Name your post" class="form-control"/>
</div>
</div>
<input type="submit" value="Submit" class="btn btn-primary"/>
</form>
JS - microscope/client/templates/posts/post_submit.js
Template.postSubmit.events({
'submit form': function(e) {
e.preventDefault();
var post = {
url: $(e.target).find('[name=url]').val(),
title: $(e.target).find('[name=title]').val()
};
Meteor.call('postInsert', post, function(error, result) {
// display the error to the user and abort
if (error)
return alert(error.reason);
Router.go('postPage', {_id: result._id});
});
}
});
I am not sure how to debug this as I am getting no errors in the console. Please can anyone suggest where I am going wrong?
Very likely that you need to add the method postInsert to the server side. If you're following along in Discover Meteor, they do that in the next section - https://book.discovermeteor.com/chapter/creating-posts
For example, you put the method in a file called lib/collections/posts.js like this
Meteor.methods({
postInsert: function(postAttributes) {
check(Meteor.userId(), String);
check(postAttributes, {
title: String,
url: String
});

Categories

Resources