I'm working on a simple CRUD application where I have a sign in, sign up, and account section for the user. Once the user signs in, then clicks account, there is the option to edit and save your changes. You'll notice I have "here is where you want to change the disable to true" and "here is where you will update the user information in the database". This is where I am supposed to implement the code. How do I actually get those edit and save buttons to work through javascript? Here is my code:
HTML:
<nav>
<div>HOME</div>
<div>ABOUT</div>
<div>SPEAKERS</div>
<div>INFO</div>
<div class="join-button">
JOIN IN
<div class="join-holder">
<div class="sign-in">
<form>
<h2>Sign In</h2>
<label>User Name:</label>
<input id="username" type="text" value="name#name.com">
<label>Password:</label>
<input id="siPW" type="password" value="12345678">
<input class="submit-button si-submit" type="submit">
</form>
</div>
<div class="sign-up">
<form>
<h2>Sign Up</h2>
<label>Name:</label>
<input id="fullName" type="text" value="name">
<label>Email:</label>
<input id="email" type="email" value="name#name.com">
<label>Password:</label>
<input id="pw" type="password" value="12345678">
<input class="submit-button su-submit" type="submit">
</form>
</div>
</div>
</div>
<div class="account">Account</div>
<div class="signOut">Sign Out</div>
</nav>
<div class="home">
Home
</div>
JS:
function setBindings() {
$(".account").click(function (e) {
var ui = DATA.getUserInfo();
if($.isEmptyObject(ui)){
swal("Oops...", "You need to sign in!", "error");
}else{
$(".home").html('<label>Name:</label><input disabled="true" id="userFullName" value="' + ui.fullName +'" type="text"><button class="edit">Edit</button><button class="save">Save</button>');
$(".edit").click(function (e) {
//here is where you want to change the disable to true
});
$(".save").click(function (e) {
//here is where you will update the user information in the database
})
}
});
$(".signOut").click(function (e) {
DATA.signOut();
});
$(".su-submit").click(function (e) {
e.preventDefault();
var fullName = $("#fullName").val(),
email = $("#email").val(),
pw = $("#pw").val(),
cpw = $("#cPw").val();
if(fullName == ""){
swal("Oops...", "You need a name!", "error");
}else if(!validateEmail(email)){
swal("Oops...", "Your email is not valid!", "error");
}else if(pw == "" || pw.length < 8){
swal("Oops...", "Your password needs to be longer than 8!", "error");
}else if(cpw == "" || cpw.length < 8 || pw != cpw){
swal("Oops...", "Your passwords don't match!", "error");
}else{
var info = {
"fullName": fullName,
"email": email,
"password": pw
};
DATA.addUser(info, addedUser);
// swal("Congrats", "You are signed up!", "success");
}
});
$(".si-submit").click(function (e) {
e.preventDefault();
var username = $("#username").val(),
pw = $("#siPW").val();
if(username == "" || validateEmail(username) == false){
swal("Oops...", "You need a username!", "error");
}else if(pw == "" || pw.length < 8){
swal("Oops...", "Your password needs to be longer than 8!", "error");
}else{
DATA.checkUser(username, pw, userSignIn);
}
});
}
function addedUser(data) {
console.log("data " , data);
}
function userSignIn(data) {
console.log(data.fullName);
swal("Congrats", data .fullName + " You are signed in!", "success");
};
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$(document).ready(function () {
setBindings();
});
Data JS:
var userLoggedIn = {};
var _checkUser = function (username, password, callback) {
$.ajax({
url: _baseQueryURL + 'q={"email":"' + username + '","password":"' + password +'"}' + _queryApiKey,
type: "GET",
contentType: "application/json"
}).done(function (data) {
userLoggedIn = data[0];
callback(data[0]);
}).fail(function (error) {
console.log("error " + error);
});
};
var _addUser = function (userInfo, callback) {
console.log(userInfo.email + ' ' + userInfo.password);
$.ajax({
url: _baseQueryURL + 'q={"email":"' + userInfo.email + '","password":"' + userInfo.password +'"}&c=true' + _queryApiKey,
type: "GET",
contentType: "application/json"
}).done(function (data) {
if(data == 0){
$.ajax({
url: _baseURL + _apiKey,
data: JSON.stringify( userInfo ),
type: "POST",
contentType: "application/json"
}).done(function (data) {
userLoggedIn = data;
callback(data);
}).fail(function (error) {
swal("Oops...", "You have an error!", "error");
});
}else if(data == 1){
swal("Oops...", "You are already signed up. Please Sign in!", "error");
}
}).fail(function (error) {
console.log("error " + error);
});
};
var _signOut = function () {
userLoggedIn = {};
};
var _getUserInfo = function () {
return userLoggedIn;
};
return {
checkUser: _checkUser,
addUser: _addUser,
signOut: _signOut,
getUserInfo: _getUserInfo
}
})();
Related
I want validation onclick. I want that before sending data, validate function run, if there is an empty field then it show amessage and data should not be send to php file. else if there is no empty fields then it should send data to php file.Form and functions are given below
<form role="form" id="schclass_form" name="schclass_form">
<div class="form-group">
<label>Enter Class Name</label>
<input class="form-control" type="text" name="class1" id="class1" placeholder="For Example: 'one'">
</div>
<div class="addmore">
<button type="button" class="btn btn-default" id="addmoreclass">Add More</button>
</div>
<button type="button" class="btn btn-default" onClick="schclass(this.id)">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</form>
function validateForm1() {
$('#schclass_form input[type="text"]').each(function(){
var data=""+$(this).val();
if(data=="")
{
swal("Oops...", "Please fill the empty fields first", "error");
}
});
}
here is function which is sending data to php file.
function schclass(a) {
if ($("#" + a).is("[disabled=disabled]")) {
return false
} else {
$("#" + a).attr("disabled", "disabled");
swal("Wait", "Request Initiate, Please Wait....", "info");
var b = $("#schclass_form").serialize() + "&type=schClass;
$.ajax({
type: "POST",
url: "include/function.php",
data: b,
cache: false,
success: function(c) {
try {
c = JSON.parse(c)
} catch (d) {
console.log(d);
swal("Oops...", "Error: Wrong response", "error");
return;
}
if ($.trim(c.result) == "success") {
swal("Success", "Message: "+c.message, "success");
} else {
swal("Oops...", "Error: "+c.message, "error");
}
},
error: function(e, c, d) {
swal("Oops...", "Error: "+d, "error");
}
})
}
$("#" + a).removeAttr("disabled");
return false;
}
I suggest making the validateForm1() function return true/false if valid/invalid, then calling it from an if statement in your schclass(a) function, if it returns true then submit, else don't submit.
Here is your code with the suggested edits:
<form role="form" id="schclass_form" name="schclass_form">
<div class="form-group">
<label>Enter Class Name</label>
<input class="form-control" type="text" name="class1" id="class1" placeholder="For Example: 'one'">
</div>
<div class="addmore">
<button type="button" class="btn btn-default" id="addmoreclass">Add More</button>
</div>
<button type="button" class="btn btn-default" onClick="schclass(this.id)">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</form>
function validateForm1() {
var valid = true;
$('#schclass_form input[type="text"]').each(function(){
var data=""+$(this).val();
if(data=="")
{
valid = false;
}
});
return valid;
}
function schclass(a) {
if ($("#" + a).is("[disabled=disabled]")) {
return false
} else {
if (validateForm1()) {
$("#" + a).attr("disabled", "disabled");
swal("Wait", "Request Initiate, Please Wait....", "info");
var b = $("#schclass_form").serialize() + "&type=schClass;
$.ajax({
type: "POST",
url: "include/function.php",
data: b,
cache: false,
success: function(c) {
try {
c = JSON.parse(c)
} catch (d) {
console.log(d);
swal("Oops...", "Error: Wrong response", "error");
return;
}
if ($.trim(c.result) == "success") {
swal("Success", "Message: "+c.message, "success");
} else {
swal("Oops...", "Error: "+c.message, "error");
}
},
error: function(e, c, d) {
swal("Oops...", "Error: "+d, "error");
}
})
} else {
swal("Oops...", "Please fill the empty fields first", "error");
}
}
$("#" + a).removeAttr("disabled");
return false;
}
!-- Main Page Starts Here -->
<section class="container">
<div class="row">
<div class="centerlogin">
<div class="frmlogin">
<form role="form" name="signin" id="signin" method="post" action="#">
<div class="headtab"><h3>Login</h3></div>
<ul>
<li><i class="glyphicon glyphicon-user"></i> <input type="text" id="email" name="username" class="usern" placeholder="Enter Username"></li>
<li><i class="glyphicon glyphicon-lock"> </i><input type="password" id="pwd" name="password" class="passn" placeholder="Enter Password"></li>
<li><button class="subn" id="btnSubmit">Login</button></li>
</ul>
</form>
</div>
</div>
</div>
</section>
<!-- Main Page Ends Here -->
the above is my login form.
and below is my ajax call
//ajax calls start below
$(document).ready(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
var email = $("#email").val();
var password = $("#pwd").val();
var pwd = $.md5(password);
auth(email, pwd);
});
});
//authenticate function to make ajax call
function auth(email, pwd) {
$.ajax
({
type: "POST",
url: "https://localhost/main/web/sign-in",
dataType: 'json',
type : "POST",
data: { email: email,pwd: pwd },
success: function (r) {
//console.log(r);
if(r.status == '0')
{
var sk=r.sk;
$.ajax({
type: "POST",
url: "http://localhost/main/secret/signin.php",
type : "POST",
data: { sk:sk},
success: function(r)
{
if(r == '0')
{
window.location.href = "http://localhost/main/index.php";
}
else
{
window.location.href = "http://localhost/main/login.php";
alert('Something Went Wrong.Please Try Again!');
}
}
});
}
else if(r.status == '401')
{
alert("Incorrect Email/Password");
$("#signin")[0].reset();
}
else
{
alert("User Doesn't exist");
$("#signin")[0].reset();
}
return false;
}
});
}
I dont know whats wrong with my code even the code its not working, it is not even showing the alerts on form blank inputs and form gets reload after clicking login button,Please help me stuck very badly.
Type property in Ajax call is defined twice.
Please use debugging tool, such as Firebug to debug xhr requests to understand if they are being sent or not. You can also view the responses of those requests which might hint errors.
Try below code as i have just removed http:// from url. hope this helps.
//ajax calls start below
$(document).ready(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
var email = $("#email").val();
var password = $("#pwd").val();
var pwd = $.md5(password);
auth(email, pwd);
});
});
//authenticate function to make ajax call
function auth(email, pwd) {
$.ajax
({
type: "POST",
url: "web/sign-in",
dataType: 'json',
type : "POST",
data: { email: email,pwd: pwd },
success: function (r) {
//console.log(r);
if(r.status == '0')
{
var sk=r.sk;
$.ajax({
type: "POST",
url: "secret/signin.php",
type : "POST",
data: { sk:sk},
success: function(r)
{
if(r == '0')
{
window.location.href = "main/index.php";
}
else
{
window.location.href = "main/login.php";
alert('Something Went Wrong.Please Try Again!');
}
}
});
}
else if(r.status == '401')
{
alert("Incorrect Email/Password");
$("#signin")[0].reset();
}
else
{
alert("User Doesn't exist");
$("#signin")[0].reset();
}
return false;
}
});
}
Code is working after i change the sequence of my javascript files into my html file of my form.
I place my javascript code file after
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
and It was working perfectly.
Bootstrap Modal fires action one time and if I click again it will fire up twice and so on.
<div id="loginModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Log In</h4>
</div>
<div class="modal-body">
<h3>Username</h3>
<input type="text" id="userLogin" placeholder="Username">
<h3>Password</h3>
<input type="password" id="pwdLogin" placeholder="Password">
<br>
<br>
<input type="checkbox" id="rememberMe">Remember Me
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="btnLogin">Log In</button>
</div>
</div>
</div>
</div>
Here's the span that fires the modal.
<span id="comment"><a id="testComment" data-toggle="modal" href="#loginModal" class="btn btn-default">Add comment</a></span>
After I click the span the modal shows. I click the #btnLogin and then the action fires up one time, two times and so on.
javascript that interacts with the modal(the action is within the span click):
$("#testComment").click(function (event) {
if ($("#msg").val() == "" || $("#nombre").val() == "") {
alert("To send a comment fill your mail and message!");
event.stopPropagation();
}
else {
$("#btnLogin").click(function () {
alert("this also");
$(this).off('shown.bs.modal');
if ($("#userLogin").val() != "" && $("#pwdLogin").val() != "") {
var dataToSend = {
"action": "LOGIN"
, "username": $("#userLogin").val()
, "password": $("#pwdLogin").val()
, "remember": $("#rememberMe").is(":checked")
}
$.ajax({
url: "data/applicationLayer.php"
, type: "POST"
, data: dataToSend
, dataTpe: "json"
, success: function (jsonData) {
var data = {
"comment": $("#msg").val()
, "username": $("#username").val()
}
$.ajax({
url: "data/addComment.php"
, type: "POST"
, data: data
, dataType: "text"
, success: function (dataResponse) {
var newHTMLContent = "";
newHTMLContent += "<tr><td>" + data.username + "</td>" + "<td>" + data.comment + "</td></tr>";
$("#commentTable").append(newHTMLContent);
alert("Comment was added!");
}
, error: function (errorMsg) {
alert("Error adding comment in ajax");
}
});
}
, error: function (errorMsg) {
alert("Login Error");
}
});
}
else {
alert('Missing username or password.');
}
});
}
});
Just put $("#btnLogin").click event outside. Here is the my code or go with below link may be it can help you.
JSFiddle
JAVSCRIPT
$("#testComment").click(function(event) {
if ($("#msg").val() == "" || $("#nombre").val() == "") {
alert("To send a comment fill your mail and message!");
event.stopPropagation();
}
});
$("#btnLogin").click(function() {
alert("this also");
$(this).off('shown.bs.modal');
if ($("#userLogin").val() != "" && $("#pwdLogin").val() != "") {
var dataToSend = {
"action": "LOGIN",
"username": $("#userLogin").val(),
"password": $("#pwdLogin").val(),
"remember": $("#rememberMe").is(":checked")
}
$.ajax({
url: "data/applicationLayer.php",
type: "POST",
data: dataToSend,
dataTpe: "json",
success: function(jsonData) {
var data = {
"comment": $("#msg").val(),
"username": $("#username").val()
}
$.ajax({
url: "data/addComment.php",
type: "POST",
data: data,
dataType: "text",
success: function(dataResponse) {
var newHTMLContent = "";
newHTMLContent += "<tr><td>" + data.username + "</td>" + "<td>" + data.comment + "</td></tr>";
$("#commentTable").append(newHTMLContent);
alert("Comment was added!");
},
error: function(errorMsg) {
alert("Error adding comment in ajax");
}
});
},
error: function(errorMsg) {
alert("Login Error");
}
});
} else {
alert('Missing username or password.');
}
});
I'm trying to pass all my form fields, to a ajax function where i will insert the user into the database.
But for some reason, my alert (in my JS file) isn't showing anything.
Any ideas what i'm doing wrong?
My HTML:
<form id="signupForm">
<input id="signupFormEmail" type="text" name="email" placeholder=" E-mail"><br />
<input id="signupFormPassword" type="text" name="password" placeholder=" Password"><br />
<input id="signupFormUsername" type="text" name="userName" placeholder=" User Name"><br />
<input id="submitSignup" type="button" value="SIGN UP" onclick="signUp(this);">
</form>
My javascript file:
function signUp(elem)
{
var postData = $(this).serializeArray();
//$('#myResults').html(postData);
alert($.param($(elem).serializeArray()));
if($(elem).parent().children('#signupFormEmail').val() != ''){
// verifica se o email já existe
$.ajax(
{
url: "/newsletter/check-email/",
type: "POST",
data: {type:'check',email:$(elem).parent().children('#signupFormEmail').val()}
}).done(function(response)
{
if(response == -1) {
$.ajax(
{
url: "/newsignup/registare/",
type: "POST",
data: postData
}).done(function(userCreated) {
if(userCreated == 1) {
alert('user created');
/*
$(elem).parent().children('#signupForm').val('');
$('#signUpCompleted').show();
*/
}
else
{
/*$('#signUpError').show();*/
alert('user not created');
}
})
//testing
//$('#signUpCompleted').show();
}
else //testing
{
$('.emailError').show(); //testing
}
}
);
}
}
It looks like you are serializing the element itself. You have to serialize the form, please check this out.
function signUp(elem)
{
var postData = $('form').serialize();
//$('#myResults').html(postData);
alert(postData);
if($(elem).parent().children('#signupFormEmail').val() != ''){
// verifica se o email já existe
$.ajax(
{
url: "/newsletter/check-email/",
type: "POST",
data: {type:'check',email:$(elem).parent().children('#signupFormEmail').val()}
}).done(function(response)
{
if(response == -1) {
$.ajax(
{
url: "/newsignup/registare/",
type: "POST",
data: postData
}).done(function(userCreated) {
if(userCreated == 1) {
alert('user created');
/*
$(elem).parent().children('#signupForm').val('');
$('#signUpCompleted').show();
*/
}
else
{
/*$('#signUpError').show();*/
alert('user not created');
}
})
//testing
//$('#signUpCompleted').show();
}
else //testing
{
$('.emailError').show(); //testing
}
}
);
}
}
In your onclick attribute, this is not the FORM; this is the button you clicked.
<form method="POST" class="userform" id="loginForm">
<div data-role="content">
<h2> Login:</h2>
<div data-role="fieldcontain">
<input name="email" placeholder="put your name" type="email" data-mini="true">
</div>
<div data-role="fieldcontain">
<input name="password" placeholder="enter your password" type="password" data-mini="true">
</div>
<input type="submit" data-theme="a" value="submit" id="submitButton">
<h5 align="center">
Forget password?
</h5>
</div>
</form>
this is my login.js
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var $bro = $('#loginForm');
$('#submitButton').click(function(e) {
//console.log("submit button has been clicked");
e.preventDefault(); //cancel form submit
var jsObj = $bro.serializeObject()
, ajaxObj = {};
//console.log(jsObj);
ajaxObj = {
type: "POST",
url: "http://192.168.0.100:8080/AdvancedLibrarySystem/api/v1/login",
data: JSON.stringify(jsObj),
contentType:"application/json",
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error " + jqXHR.getAllResponseHeaders() + " " + errorThrown);
},
success: function(data) {
console.log(data);
if(data[0].status == '200') {
alert("Welcome!!!")
$('#div_ajaxResponse').text( data[0] );
$.mobile.changePage('home.html');
}
else{
alert("Incorret Username or Password!!!")
}
},
complete: function(XMLHttpRequest) {
//console.log( XMLHttpRequest.getAllResponseHeaders() );
},
dataType: "json" //request JSON
};
$.ajax(ajaxObj);
});
I'm trying to use an authentification in phonegap via ajax but if i'm trying to run that code in chrome console it works fine but when i'm using it in my phonegap application it's not giving response in the server... Anyone can help me out please...
I am not sure what you mean by 'not giving response in the server', but one thing worth checking out is the cross-domain options in the config.xml of your phonegap project. There should be an "access" tag in there that specifies what domains can be accessed. Try setting it to "*" and try again.