Get values from HTML to javascript - javascript

So I have a simple form where I ask the user some info to register and make an account, this is the part of the form I am using to achieve that:
<form class="login-form2" action="index.html">
<div class="center sliding"><img style='width:20%; margin: 42%; margin-top: 8%; margin-bottom: 0%;'src="./images/logoTemporal.png"></div>
<div class="login-wrap">
<p class="login-img"><i class="icon_lock_alt"></i></p>
<!-- Name -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_profile"></i></span>
<input type="text" id="Name" name="Name" class="form-control" placeholder="Name or Name.Corp" autofocus>
</div>
<!-- Email -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="email" id="Email" name="Email" class="form-control" placeholder="Email">
</div>
<!-- Passwrod -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="password" id="Password" name="Password" class="form-control" placeholder="Password">
</div>
<!-- Confirm password -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="password" class="form-control" placeholder="Confirm Password">
</div>
<!-- Tipo -->
<div class="item-content input-group-addon">
<div class="item-media"><i class="icon f7-icons">Tipo Usuario</i></div>
<br>
<div class="item-input">
<select id="Tipo" name="Tipo">>
<option value="0" selected>Empresa</option>
<option value="1">Usuario</option>
</select>
</div>
</div>
<br>
<!-- Button-->
<!-- <a class="btn btn-primary btn-lg btn-block" href="register.html">Register</a> -->
<p> <input type="button" class="btn btn-primary btn-lg btn-block" id="signup" value="Send"/></p>
</div>
</form>
I am trying to get the values into some variables in a jc, but for some reason I am not getting them:
$(document).ready(function() {
$("#signup").click(function() {
alert("Im in the function");//this is the only alert showing when I test the page...
//From here on it is not working
var Name = $('#Name').val();
var Email = $('#Email').val();
var Password = $('#Password').val();
var Tipo = $('#Tipo').val();
if (Name == '' || Email == '' || Password == '' || Tipo == '')
{ alert("please complete the information"); }
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: 'dummy url',
crossDomain: true,
beforeSend: function(){ $mobile.loading('show')},
complete: function(){ $mobile.loading('hide')},
data: ({Name: Name, Email: Email, Password: Password, Tipo: Tipo}),
dataType: 'json',
success: function(html){
alert("Thank you for Registering with us! you
can login now");
},
error: function(html){
alert("Not Working");
}
});
}//else end
});
});
I am still trying to learn many things here but what I need to know is why the variables are not getting the values from the form, could be something dumb but I just cant see it... Would appreciate some help...
EDIT:
Adding my php code, now I get an error when trying to send the data to my host´s php using JSON, the javascript prints the "not working" alert, what I think is that my php is not really getting the json so its not working but im not 100% sure so here is my php code:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, DELETE, OPTIONS');
require 'data/DataCollector.php';
$varData = json_decode($data);
$Name = $varData->Name;
$Email = $varData->Email;
$Password = $varData->Password;
$Tipo = $varData->Tipo;
$database = new DataCollector([
'database_name' => 'dummy url',
'server' => 'dummy server',
'username' => 'dummy username',
'password' => 'dummy password',
'charset' => 'utf8',
]);
if($_POST){
$database->insert("Usuario", [
"nombre" => $_POST[$Name],
"email" => $_POST[$Email],
"password" => $_POST[$Password],
"tipoUsuario" => $_POST[$Tipo]
]);
}
?>
I have never used JSON and I am trying to learn about it, there is probably A LOT of issues with my code but any help will be very much appreciated! thanks!

your dictionary does not seem to be correct.
try this:
data: {"Name": Name, "Email": Email, "Password": Password, "Tipo": Tipo}

Related

PHP is not returning data to AJAX

I'm testing a login form that submits data via Ajax to the PHP processing file. Once I click the submit button it just redirects me to PHP file and not returning data from PHP. The form is inside a bootstrap modal. I'm just new to jquery and ajax so I hope someone helps. Thanks
HTML
<form action="login-process.php" id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>
JQuery script is placed at site footer after jquery.js cdn
$(document).ready(function(){
// Process form
$('#test-form').submit(function(event){
// get form data
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};
// process the form
$.ajax({
type : 'POST', // define the HTTP method we want to use
url : 'process.php', // url to send data
data : formData, // data object
dataType : 'json', // what type of data to expect back from server
encode : true
})
// using done promise call back
.done(function(data){
// log data to console
console.log(data);
if (data.email-msg) {
alert("success");
}
});
// stop the form from submitting and refresing the page
event.preventDefault();
});
});
process.php
<?php
$data = array(); // array to hold pass back data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['login-email'];
$password = $_POST['login-pass'];
$data['email-msg'] = $email;
$data['pw-msg'] = $password;
echo json_encode($data);
} ?>
try this brother
$(document).ready(function(){
$('#test-form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"action="login-process.php" ",
method:"POST",
data:$(this).serialize(),
success:function(data){
console.log("data send");
}
})
});
});
<form id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>
You Have syntax error in javascript code.
change your code
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};
to
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val()
};
It will solve the problem

val and fadeOut not working on click

i'm creating a ajax post request that works fine. however to make it more appealing i'm trying to implement so that when the user click on #sign_in it will change the text while request is going on. if it result in error a message will appear. this message will automatically remove after a couple of seconds. however if u click .close it will force close. The issue is however that following does not work:
$(".alert a").click(function(e) {
$('.alert').fadeOut();
});
Nothing happens when i click on .close. in addition to this below does not work either.
$('#sign_in').val('Logger ind...');
Full Code
<form id="sign_in">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">
</div>
<a href="#">
<small>Forgot password?</small>
</a>
<div class="form-group text-center add_top_20">
<input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
<input type="hidden" name="next" value="{{ next }}" />
</div>
</form>
<div class="alert alert-error alert-danger" style="display: none;">
<a class="close" href="#">×</a>
Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.
</div>
jquery
$("#sign_in").submit(function (event) {
// Change sign in button text
$('#sign_in').val('Logger ind...');
// post request
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: "/account/login/auth/",
type: "POST",
dataType : 'json',
contentType: 'application/json',
data: {
'username': username,
'password': password
}, success: function (data) {
if (data.success) {
alert('success');
} else {
showAlert()
}
// Change sign in text back
$('#sign_in').val('Log ind');
}, error: function(error){
// Change sign in text back
$('#sign_in').val('Log ind');
}
});
});
function showAlert(){
if(!$('.alert').is(':visible'))
{
$('.alert').fadeIn()
$('.alert').delay(4000).fadeOut()
}
}
$(".alert a").click(function(e) {
$('.alert').fadeOut();
});
and all of this is wrapped in $(document).ready(function () {
Mmm, your event is launching but you need to use clearQueue in order to launch your fadeOut animation again interrupting the previous one.
$(".alert a").click(function(e) {
$('.alert').clearQueue();
$('.alert').fadeOut();
});
Change your form id or submit button id and change :visible to :hidden
function showAlert(){
if($('.alert').is(':hidden'))
{
$('.alert').fadeIn()
$('.alert').delay(4000).fadeOut()
}
}
Here I have change form 'id'
<form id="sign_in_form">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">
</div>
<a href="#">
<small>Forgot password?</small>
</a>
<div class="form-group text-center add_top_20">
<input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
<input type="hidden" name="next" value="{{ next }}" />
</div>
</form>
<div class="alert alert-error alert-danger" style="display: none;">
<a class="close" href="#">×</a>
Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.
</div>
jQuery
$("#sign_in_form").submit(function (event) {
// Change sign in button text
$('#sign_in').val('Logger ind...');
// post request
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: "/account/login/auth/",
type: "POST",
dataType : 'json',
contentType: 'application/json',
data: {
'username': username,
'password': password
}, success: function (data) {
if (data.success) {
alert('success');
} else {
showAlert()
}
// Change sign in text back
$('#sign_in').val('Log ind');
}, error: function(error){
// Change sign in text back
$('#sign_in').val('Log ind');
}
});
});
function showAlert(){
if($('.alert').is(':hidden'))
{
$('.alert').fadeIn()
$('.alert').delay(4000).fadeOut()
}
}
$(".alert a").click(function(e) {
$('.alert').clearQueue();
$('.alert').fadeOut();
});

Angular validations: Restrict server request if user enters invalid email or password

<form name="LPform" novalidate>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">Email ID</label>
<input class="mob-adj-inpbx " type="email" name="uemail" ng-model="useremail" placeholder=" me#example.com" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.uemail.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.uemail.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.uemail.$dirty && allow_Invalid">
</div>
</div>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">PASSWORD</label>
<input class="mob-adj-inpbx" type="password" name="upassword" ng-model="userpassword" placeholder=" password" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.upassword.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.upassword.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.upassword.$dirty && allow_Invalid">
</div>
</div>
<div id="server_message" class="form-row clearfix basic-error-msg-loginpopup" ng-show="server_message">
{{server_message}}
</div>
<div class="btn-container clearfix mobile-adj" style="margin-left:17.2%;">
<div class="btn-wrap btn-loginpopup">
<input style="max-height:40px;width:121%;" type="submit" name="commit" value="LOGIN" ng-click="login_request()"/>
</div>
</div>
</form>
This part is displayed to the user and the inputs are validated using angular validations. All validations are working fine.
$scope.login_request = function(){
if(LPform.useremail.$valid && LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$http({
method: 'POST',
url: '/users/home_login',
data: {email: $scope.useremail, password: $scope.userpassword}
}).success(function (response) {
console.log(response);
window.location = response.location;
}).error(function (response) {
console.log(response);
$scope.server_message = response.server_message;
});
}
else if(!LPform.useremail.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid email.";
}
else if(!LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid password.";
}
else{
$scope.allow_Invalid = "true";
$scope.server_message = "Request Failed.";
}
};
This part is in javascript file where I want to use the validations to decide whether to send a request to the server or not. The conditions I have used in the if else clause is not working, which I randomly tried btw. I am aware that I can disable Login button, however, I don't want to implement this that way.
I believe your problem is that the form name is bound to $scope and isn't a global variable.
In controller change
LPform
To
$scope.LPform

CAPTCHA fails shows alert but form submitting automatically how to stop this

This is basic registration module in this i added captcha works
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-register" role="form" id="register-form">
<div>
<input name="name" id="name" type="text" class="form-control" placeholder="User name">
<span class="help-block"></span>
</div>
<div>
<input name="email" id="email" type="email" class="form-control" placeholder="Email address" >
<span class="help-block"></span>
</div>
<div>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<span class="help-block"></span>
</div>
<div>
<input name="confirm_password" id="confirm_password" type="password" class="form-control" placeholder="Confirm Password">
<span class="help-block"></span>
</div>
<div>
<td id="imgparent">
<div id="imgdiv">
<img id="img" src="captcha.php">
</div>
<img id="reload" src="images/reload.png">
<input id="captcha1" name="captcha" type="text" class="form-control" placeholder="Enter captcha">
</td>
</tr>
<span class="help-block"></span>
</div>
<button class="btn btn-block bt-login" id="button" type="submit">Sign Up</button>
<h4 class="text-center login-txt-center">Alternatively, you can log in using:</h4>
<a class="btn btn-default facebook_rnd" href="login.php?type=facebook"> <i class="fa fa-facebook modal-icons-rnd"></i> </a>
<a class="btn btn-default google_rnd" href="login.php?type=google"> <i class="fa fa-google-plus modal-icons-rnd"></i> </a>
</form>
it is register.js
$(document).ready(function(){
$("#register-form").validate({
submitHandler : function(e) {
$(form).submit();
},
rules : {
name : {
required : true
},
email : {
required : true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
},
password : {
required : true
},
confirm_password : {
required : true,
equalTo: "#password"
}
},
messages : {
name : {
required : "Please enter name"
},
email : {
required : "Please enter email",
remote : "Email already exists"
},
password : {
required : "Please enter password"
},
confirm_password : {
required : "Please enter confirm password",
equalTo: "Password and confirm password doesn't match"
}
},
errorPlacement : function(error, element) {
$(element).closest('div').find('.help-block').html(error.html());
},
highlight : function(element) {
$(element).closest('div').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('div').removeClass('has-error').addClass('has-success');
$(element).closest('div').find('.help-block').html('');
}
});
});
it is for CAPTCHA js
// JavaScript Document
$(document).ready(function() {
// Change CAPTCHA on each click or on refreshing page.
$("#reload").click(function() {
$("#img").remove();
$('<img id="img" src="captcha.php" />').appendTo("#imgdiv");
});
// Validation Function
$('#button').click(function() {
var name = $("#username1").val();
var email = $("#email1").val();
var captcha = $("#captcha1").val();
if (name == '' || email == '' || captcha == '') {
} else {
// Validating CAPTCHA with user input text.
var dataString = 'captcha=' + captcha;
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
success: function(html) {
if ($.trim(captcha) == '2') {
alert('Entered code is wrong');
reloadCaptcha();
return false;
}
validated = true;
$("#button").submit();
alert(html);
}
});
}
});
});
here when all validation are works fine but if the CAPTCHA is wrong then also it submitting he form why?>>
how to stop when CAPTCHA is worng return to form ??
What you're doing here is never what you want to be doing with Captcha.
The reason Captcha exists is to prevent malicious form submissions, meaning that you're not supposed to be able to submit any data to the server without a valid Captcha. However, what you're doing is validating the Captcha in Javascript, then submitting the form.
There is nothing stopping someone from manually calling $('#button').submit() to push whatever data they like to the server. The Captcha is essentially useless; it's like a door with no walls around it.
You'll need to re-implement your Captcha solution to do the validation on the server side, wherever your form is submitting to. First validate the Captcha, then process the form submission.
You could use something like this:
session_start();
if($_POST['captcha'] != $_SESSION['<insert Captcha Session key here>']) { /* invalid captcha */ }

Form doesn't submit on callback

I am trying to send an e-mail after an ajax call has been successfully completed. I do not have access to the file that I am making the AJAX call to.
I am preventing the first submit, making the ajax call and submitting the form again upon competition. When doing this, I can't seem to figure out why I have to press the submit button twice for the email to be sent.
Here is my code:
"use strict";
var submitted = '';
/* Send info to the portal */
jQuery(function($) {
$('#quote').submit(function(e){
var firstName = $('#firstName').val(),
lastName = $('#lastName').val(),
email = $('#email').val(),
phone = $('#primaryPhone').val(),
weight = $('#weight').val(),
origin = $('#originPostalCode').val(),
destination = $('#destinationPostalCode').val(),
notes = $('#whatsTransported').val()
if( submitted != 1 )
{
e.preventDefault();
$.ajax({
type: "POST",
url: "https://somewhere.on/the/internet.php",
crossDomain: true,
dataType: "json",
data: {"key": "my secret key","first": firstName, "last": lastName, "email": email, "phone": phone, "weight": weight, "origin_postal": origin, "dest_country": destination, "note": notes }
})
.done(function(data){
if(data[1][0][0] == 2)
{
$('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
} else if(data[1][0][0] == 0) {
console.log("Made it.");
$('#quote #submit').submit();
} else {
$('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
}
})
.fail(function(data) { console.log(data); });
}
submitted = '1';
});
});
Here is the form HTML
<form action="<?php echo bloginfo($show='template_url').'/includes/form-email.php'; ?>" class="span6 offset1" id="quote" method="post">
<div class="row formRow">
<div class="firstName span3">
<label for="firstName"><?php _e('First Name:','StreamlinedService'); ?></label>
<input type="text" name="firstName" id="firstName">
</div>
<div class="lastName span3">
<label for="lastName"><?php _e('Last Name:','StreamlinedService'); ?></label>
<input type="text" name="lastName" id="lastName">
</div>
</div>
<div class="row formRow">
<div class="email span3">
<label for="email"><?php _e('Email Address:','StreamlinedService'); ?></label>
<input type="text" name="email" id="email">
</div>
<div class="primaryPhone span3">
<label for="primaryPhone"><?php _e('Phone Number:','StreamlinedService'); ?></label>
<input type="text" name="primaryPhone" id="primaryPhone">
</div>
</div>
<div class="row formRow">
<div class="weight span2">
<label for="weight"><?php _e('Weight (lbs):','StreamlinedService'); ?></label>
<input type="text" name="weight" id="weight">
</div>
</div>
<div class="row formRow">
<div class="originPostalCode span3">
<label for="originPostalCode"><?php _e('Origin:','StreamlinedService'); ?></label>
<input type="text" name="originPostalCode" id="originPostalCode">
</div>
<div class="destinationPostalCode span3">
<label for="destinationPostalCode"><?php _e('Destination:','StreamlinedService'); ?></label>
<input type="text" name="destinationPostalCode" id="destinationPostalCode">
</div>
</div>
<div class="row">
<div class="whatsTransported span6">
<label for="whatsTransported"><?php _e('What can we help you transport?','StreamlinedService'); ?></label>
<textarea name="whatsTransported" id="whatsTransported" rows="5"></textarea>
</div>
<input type="hidden" name="formType" value="quote" />
<input type="hidden" name="siteReferer" value="<?php echo $blog_id ?>">
<input type="submit" id="submit" name="submit" value="<?php _e('Get Freight Quote','StreamlinedService') ?>" class="btn btn-primary btn-large span3 offset3" style="float:right;">
</div>
</form>
My question is two-fold: Is there a more efficient way to do this? If not, why isn't this working?
Just use the .submit directly on the form node (note the [0])
$('#quote #submit').submit();
becomes
$('#quote')[0].submit();
this bypasses the jQuery bound event and forces a postback.
You use the wrong approach to Jquery
You miss the key : Write Less Do More, the heart of JQuery.
Anyway try this:
"use strict";
/* Send info to the portal */
jQuery(function($) {
$('#quote').submit(function(e){
var tis = $(this);
$.ajax({
type: "POST",
url: "https://somewhere.on/the/internet.php",
cache: true,
dataType: "json",
data: tis.serialize(),
success: function(data){
if(data[1][0][0] == 2){
$('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
} else if(data[1][0][0] == 0) {
console.log("Made it.");
$('#quote #submit').submit();
} else {
$('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
}
},
error: function(data){console.log(data);}
});
e.stroPropagation();
e.preventDefault();
});
});
Last thin.. you CAN'T request a remote page that's not hosted on the same domain of the script.. For that ther's This answer

Categories