Unable to Ajax Call Using Jquery - javascript

I am trying to do login with the help of Jquery ajax, but at the time of making ajax call using method jQuery.ajax(....) with servlet (Java) this method was unable to call. I am using ajax lib from link http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js.
Every time I am getting the below URL in address bar of browser.
Project/?email=abc88%40gmail.com&password=1234&sendbtn=Send+Message
Below is the Jquery Ajax Code.
$(document).ready(function() {
//global vars
var username=jQuery("#email");
var password=jQuery("#password");
function checkLoginForm() {
if(username.attr("value") && password.attr("value")) {
return true;
} else {
return false;
}
}
jQuery(".txtbar, .txtbox").live("focus", function() {
var thelabel = jQuery(this).prev();
var infobox = jQuery(this).next();
var rowbox = jQuery(this).parent();
var currid = jQuery(this).attr('id');
var pxlchange = '-45px';
rowbox.addClass('colors');
thelabel.animate({left: pxlchange}, 350, 'linear', function() {});
// The animation is completed
infobox.animate({opacity: 1.0}, 350, 'linear', function() {
// The animation is completed
});
}
jQuery(this).live("keyup", function() {
var theval = jQuery(this).val();
var limitval = 3;
var replacehtml = "";
var emailinfohtml = "Enter a valid e-mail address.";
var subjectinfohtml = "Enter Password.";
if(currid == "email") {
replacehtml = emailinfohtml;
} else if(currid == "password") {
replacehtml = subjectinfohtml;
limitval = 2;
}
// checking against e-mail regex
if(currid == "email") {
if(checkValidEmailAddress(theval)) {
infobox.html("Looks good!");
infobox.addClass('good');
} else if(!checkValidEmailAddress(theval)) {
infobox.html(replacehtml);
infobox.removeClass('good');
}
} else {
// we use this logic to check for name+message fields
if(theval.length >= limitval) {
infobox.html("Looks good!");
infobox.addClass('good');
} else if(theval.length < limitval) {
infobox.html(replacehtml);
infobox.removeClass('good');
}
}
// now we check if we can display the send button
// much easier to just look for 'good class on the req fields
});
});
jQuery(".txtbar, .txtbox").live("blur", function() {
var thelabel = jQuery(this).prev();
var infobox = jQuery(this).next();
var rowbox = jQuery(this).parent();
var currid = jQuery(this).attr('id');
rowbox.removeClass('colors');
infobox.animate({opacity: 0}, 400, 'linear', function() {
// The animation is completed
});
});
jQuery("#sendbtn").click(function() {
if (checkLoginForm()) {
jQuery.ajax({
type : "GET",
url : "/DoLogin.htm",data:"userName="+ username.val()+ "&password="+ password.val(),
success : function(msg) {
alert("Ajax Return Success");
return false;
}
});
} else {
alert("Ajax Return Fail Code ");
return false;
}
});
function checkValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+") ([\w-+]+(?:\.[\w-+]+)*))(#((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};
HTML code:
<div id="wrap">
<form id="contact-form" name="contact-form">
<div class="rowbox">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" class="txtbar req" tabindex="1">
<div class="infobox">
Enter a valid e-mail address
</div>
</div>
<div class="rowbox">
<label for="subject">Password</label>
<input type="password" id="password" name="password" class="txtbar" tabindex="1">
<div class="infobox">
Enter Password
</div>
</div>
<input type="submit" value="Send Message" id="sendbtn" name="sendbtn" class="submit-button">
</form>
</div>

If you make the data property an object, jQuery will handle parameterizing and URI-encoding it for you automatically. If you insist on it being a string, you need to do all of that yourself.
jQuery.ajax({
type: "GET",
url: "/DoLogin.htm",
data: { userName: username.val(), password: password.val() },
success: function() {
alert("Ajax Return Success");
}
});
On a security note, I wouldn't simply check that the #email and #password fields have value attributes and return true, nor would I transmit plain-text login info over the wire. Maybe you intended this as boilerplate code to get things working and you'll validate/encrypt them better later. :)

Related

I'm having a cannot POST when attempting to submit a form with JS

I am having an issue with my Javascript and HTML where when I submit my form, I get a Cannot POST error. I already looked at Shows error "Cannot POST" when I try to submit the HTML form, but that seems to be server-based. I'm sorry, but I'm doing this for a class, so I'm in a bit of a time crunch right now.
My login JS code:
function login(){
var pw = document.forms['login']['passcode'].value;
var email = document.forms['login']["email"].value;
var login = userLogin().get();
if(email == "adrian#tissue.com" && pw == "welcome1"){
window.location = "issues.html";
}
else if(email == "admin#tissue.com" && pw == "admin123"){
window.location = "subscription-dashboard.html"
}
else if(email == login[0] && pw == login[1]){
window.location = "issues.html";
}
else{
alert("That password/email is incorrect");
return false;
};
}
My module for get is:
(function userLogin(){
return {
store: function(password, email){
sessionStorage.setItem(pass, password);
sessionStorage.setItem(user, email);
return false;
},
get: function(){
var mail = sessionStorage.getItem(user);
var pwkey = sessionStorage.getItem(pass);
var loginfo = [mail, pwkey];
return loginfo;
}
}
});
And my HTML code is:
<form action="#" name="login" method="post" onsubmit="return login()">
<input type="text" name="email" placeholder="Email" required>
<input type="password" name="passcode" placeholder = "Password" required>
<input type="submit" value="login">
</form>
Here's my fiddle for ease. I'm using Brackets and this class is Client side JS.
https://jsfiddle.net/MiguelPi/nmp6oxat/1/
Seems like you are trying to access to an anonymous function, rewrite userFunction like this (without external parentheses):
function userLogin(){
return {
store: function(password, email){
sessionStorage.setItem(pass, password);
sessionStorage.setItem(user, email);
return false;
},
get: function(){
var mail = sessionStorage.getItem(user);
var pwkey = sessionStorage.getItem(pass);
var loginfo = [mail, pwkey];
return loginfo;
}
}
}

Session TImeout after logon?

Below is a logon code I have set up with html. I would like to set a timeout setting to initiate a log off function after x minutes idle time. Is this possible? I currently have a log off button that initiates the log off, so possibly have that timeout select that function. Thank you.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<legend>Enter credentials</legend>
<p>
<label for="username">User name:</label>
<input type="text" id="username" name="username" />
</p>
<p>
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
</p>
</fieldset>
<input type="submit" id="login-button" name="login-button" value="Log On" />
</form>
<script src="scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// Web Proxy request to fetch the configuration
ajaxWrapper({ url: 'Home/Configuration', dataType: 'xml', success: configSuccess });
$('form').submit(function () {
var username = $('#username').val(),
password = $('#password').val();
clearMessage();
if (!username || !password) {
showMessage('Enter a username and a password');
return false;
}
// Ensure the user name is correct...
// If the username has the domain string at position 0, then
// the username is correct and just use it as normal, but if
// not, username needs to have the domain prepended.
// Because of the backslashes in the strings, they need to be
// escaped with "\\"
username = username.indexOf("domain\\") === 0 ? username : "domain\\" + username;
// Web Proxy request to log the user on
ajaxWrapper({
url: 'PostCredentialsAuth/Login',
dataType: 'xml',
success: loginSuccess,
error: loginError,
data: { username: username, password: password }
});
return false;
});
});
</script>
Below is the code I added to the section after the logonsuccess form is selected.
function loginSuccess(data) {
var $loginXml = $(data),
result = $loginXml.find('Result').text();
if (result == 'success') {
$('form').hide();
$('#log-off').show();
// Set timeout variables.
var timoutWarning = 60000; // Display warning in 14 Mins.
var timoutNow = 30000; // Warning has been shown, give the user 1 minute to interact
var logoutUrl = '($configXml.find('authManager').attr('logoffURL'));'; // URL to logout page.
var warningTimer;
var timeoutTimer;
// Start warning timer.
function StartWarningTimer() {
warningTimer = setTimeout("IdleWarning()", timoutWarning);
}
// Reset timers.
function ResetTimeOutTimer() {
clearTimeout(timeoutTimer);
StartWarningTimer();
$("#timeout").dialog('close');
}
// Show idle timeout warning dialog.
function IdleWarning() {
clearTimeout(warningTimer);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
$("#timeout").dialog({
modal: true
});
// Add code in the #timeout element to call ResetTimeOutTimer() if
// the "Stay Logged In" button is clicked
}
// Logout the user.
function IdleTimeout() {
window.location = logoutUrl;
}
And below is the Log Off button that is shown where a user can manually log off.
$('#log-off').click(function () {
// Web Proxy request to log the user off
url = ($configXml.find('authManager').attr('logoffURL'));
ajaxWrapper({ url: url, dataType: 'text', success: logoffSuccess });
return false;
});
});
Your code doesn't call incativityTime function. Call the function on window onload (or jquery onready) like window.onload = function() { inactivityTime() };
<html>
<body>
<script>
window.onload = function() { inactivityTime() };
var inactivityTime = function ()
{
var t;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.php'
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 3000)
// 1000 milisec = 1 sec
}
}
</script>
</body>
</html>
I added it with no success. Below is how the logon success code looks.
function loginSuccess(data) {
var $loginXml = $(data),
result = $loginXml.find('Result').text();
if (result == 'success') {
$('form').hide();
$('#log-off').show();
// Web Proxy request to enumerate the resources available to the user
url = $configXml.find('resourcesProxy').attr('listURL');
ajaxWrapper({ url: url, success: listResourcesSuccess });
} else {
showMessage('Login failed - try again');
}
var inactivityTime = function () {
var t;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.php'
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 3000)
// 1000 milisec = 1 sec
}
};
}

when i click on submit button my email is not send why?

when i click on submit button it will show me the message from the javascript file but it will not go to the php file that i have generated..
here is my html code
<form method="post" id="contactForm" action="email_send.php">
<div class="clearfix">
<div class="grid_6 alpha fll">
<input type="text" name="senderName" id="senderName" placeholder="Name *" class="requiredField" />
</div>
<div class="grid_6 omega flr">
<input type="text" name="senderEmail" id="senderEmail" placeholder="Email Address *" class="requiredField email" />
</div>
</div>
<div>
<textarea name="message" id="message" placeholder="Message *" class="requiredField"></textarea>
</div>
<input type="submit" id="sendMessage" name="sendMessage" value="Send Email" />
<span> </span>
</form><!-- end form -->
my js file
if ($("#contactForm")[0]) {
$('#contactForm').submit(function () {
$('#contactForm .error').remove();
$('#contactForm .requiredField').removeClass('fielderror');
$('#contactForm .requiredField').addClass('fieldtrue');
$('#contactForm span strong').remove();
var hasError = false;
$('#contactForm .requiredField').each(function () {
if (jQuery.trim($(this).val()) === '') {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>*Please fill out all fields.</strong>');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>Is incorrect your email address</strong>');
hasError = true;
}
}
});
if (!hasError) {
$('#contactForm').slideDown('normal', function () {
$("#contactForm #sendMessage").addClass('load-color');
$("#contactForm #sendMessage").attr("disabled", "disabled").addClass("btn-success").val('Sending message. Please wait...');
});
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function (data) {
$('#contactForm').slideUp("normal", function () {
$(this).before('<div class="notification-box notification-box-success"><p><i class="fa fa-check"></i>Thanks!</strong> Your email was successfully sent. We check Our email all the time.</p></div>');
});
});
}
return false;
});
}
my php file which i have written on action is
<?php
if(isset($_POST['senderName']) && isset($_POST['senderEmail']) && isset($_POST['message']) )
{
$senderName = $_POST['senderName'];
$senderEmail = $_POST['senderEmail'];
$message = $_POST['message'];
if(!empty($senderName) && !empty($senderEmail) && !empty($message))
{
if(strlen($senderName)>25 || strlen($senderEmail)>25 || strlen($message)>50 )
{
echo 'Maximum length reached for each field';
}
else
{
$to = 'info#courtpiece.com';
$subject = 'Court Piece Rung';
$body = "Name:".$senderName."\n"."Message: ".$message;
$header = 'From'.$senderEmail;
if(#mail($to,$subject,$body,$header))
{
echo 'Thanks for Contacting Us.We\'ll in touch soon. ';
}
else
{
echo 'Sorry an error occured ';
}
}
}
else
{
echo 'All fields are required. ';
}
}
?>
Sometimes this can create a problem..
You are using: if(isset($_POST['senderName']) && isset($_POST['senderEmail']) && isset($_POST['message']) ){
instead of:
if(isset($_POST['sendMessage'])){
if(!empty($_POST['senderName']) && !empty($_POST['senderEmail'])){
CODE HERE
}
}
If not, then probably you miss-confiugred your email sending service.
try a test on the email sending.
mail()
You will need to supress the default behaviour of your form so it doesnt also send a request to your server. You do this by calling the prevendDefault function of your event parameter .submit(function(e)....
if ($("#contactForm")[0]) {
$('#contactForm').submit(function (e) {
e.preventDefault(); //to suppress the behaviour of your Form -> you will send data manually with $.post
$('#contactForm .error').remove();
$('#contactForm .requiredField').removeClass('fielderror');
$('#contactForm .requiredField').addClass('fieldtrue');
$('#contactForm span strong').remove();
var hasError = false;
$('#contactForm .requiredField').each(function () {
if (jQuery.trim($(this).val()) === '') {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>*Please fill out all fields.</strong>');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>Is incorrect your email address</strong>');
hasError = true;
}
}
});
if (!hasError) {
$('#contactForm').slideDown('normal', function () {
$("#contactForm #sendMessage").addClass('load-color');
$("#contactForm #sendMessage").attr("disabled", "disabled").addClass("btn-success").val('Sending message. Please wait...');
});
var formInput = $(this).serialize();
$.post("email_send.php", formInput, function (data) {
$('#contactForm').slideUp("normal", function () {
$(this).before('<div class="notification-box notification-box-success"><p><i class="fa fa-check"></i>Thanks!</strong> Your email was successfully sent. We check Our email all the time.</p></div>');
});
});
}
return false;
});
}
I have to say that there is room for improvement in the way you have built up this validation.
Try running the form again with the additions I made.
Report back!

Not able to send form parameters to the server

We are getting a issue wherein while submitting a form via javascript one of the parameters (invoiceCodes) is not sent to the server. Below is the snippet of the javascript code.
The flow is as follows. When user clicks on "Print" button validateTransition() method is called in which we make a ajax call. After response of that ajax we call couponPopup(url, invoiceCodes). In this function we submit newWinForm but sometimes invoiceCodes parameter is sent empty.
Also checkForInvoiceCode is true in this case which require user to input invoice codes
Is there anything wrong in the manner in which we are putting values in the form which may lead to invoiceCodes being not sent sometimes.
function couponPopup(url, invoiceCodes)
{
var selectedOrders = '';
$(".selectedOrder:checked").each(function() {
selectedOrders += $(this).val() + ',';
});
var frm = document.forms["newWinForm"];
frm.action = url;
frm.selectedShipments.value= selectedOrders;
frm.invoiceCodes.value = invoiceCodes;
console.log("Selected orders are "+selectedOrders);
console.log("Invoice codes with them in order are "+invoiceCodes);
document.getElementById("hiddenInvoiceCodes").value=invoiceCodes;
document.getElementById("hiddenselectedShipments").value=selectedOrders;
frm.submit();
return false;
}
function validateTransition() {
$('#statusChangeSuccess').hide();
$('#statusChangeFail').hide();
var selectedOrders = '';
var invoiceCodes = '';
var flag = 0;
var spaceError = 0;
var commaError = 0;
$(".selectedOrder:checked").each(function() {
selectedOrders += $(this).val() + ',';
<c:if test="${checkForInvoiceCode}">
var emptyPattern = /^\s*$/;
var commaPattern = /,/;
var inv_code = $("#invoice-code-" + $(this).val()).val().trim();
if (emptyPattern.test(inv_code)) {
spaceError = 1;
flag = 1;
}
if (commaPattern.test(inv_code)) {
commaError = 1;
flag = 1;
}
invoiceCodes += inv_code + ",";
</c:if>
});
if(selectedOrders=='') {
alert('Please select at least one order');
return false;
}
if ( flag ) {
if ( commaError ) {
alert('One or more specified codes have comma, please remove comma from them');
}
if ( spaceError ) {
alert('One or more specified codes has been left blank, please fill them up');
}
if ( !commaError && !spaceError ) {
alert('Please contact tech');
}
return false;
}
var inputdata = {"selectedShipments" : selectedOrders,
"statusCode" : "PRINT"
};
//this is where we are making an ajax call
jQuery(function($){
setTimeout(function(){
var ajaxUrl = '/product/update/';
$.ajax({url:ajaxUrl, type: "POST", dataType: 'json', data:inputdata , success: function(data) {
if(data['status'] == 'success') {
//couponPopup function is called where form is submitted
couponPopup("${path.http}/product/print/", invoiceCodes);
$('#statusChangeSuccess').html(data['message']).show();
$(".selectedOrder:checked").each(function() {
$("#row-" + $(this).val()).remove();
});
} else{
$('#statusChangeFail').html(data['message']).show();
}
}});
}, 10 );
});
return false;
}
<form id="newWinForm" name="newWinForm" action="" method="post" target="_blank" >
<input type="hidden" id="hiddenselectedShipments" name="selectedShipments" value="" />
<input type="hidden" id="hiddenInvoiceCodes" name="invoiceCodes" value="" />
</form>
Controller for the form. Invoice codes is sometimes empty even when we are sending it from client side.
#RequestMapping("/product/print")
public void printSelectedPendingOrders(#RequestParam("selectedShipments") String selectedShipments,
#RequestParam(defaultValue = "", value = "invoiceCodes", required = false) String invoiceCodes, ModelMap modelMap, HttpServletResponse httpResponse)
throws IOException, DocumentException, ParserConfigurationException, SAXException {

AJax + PHP + MYSQL Newsletter subscriber

Currently I am able to add a new email address to my newsletter table, however I am struggling with the AJAX part of the query, ie. the validation.
Below is my Signup.php file:
<?php
require_once('required/init.php');
require_once('required/settings.php');
require_once('required/database.php');
require_once('required/class.phpmailer.php');
require_once('required/globals.php');
$email = trim($_REQUEST["email"]);
// Check if subscriber exists
$SQL= "select email from tblnewsletter where email='".$email."'";
$result = mysql_query($SQL);
if(!$result) {die('Problem in SQL: '.$SQL);} //just checking if there was a problem with your query
if (mysql_num_rows($result)==1) { // he was subscribed already
echo 'You are subscribed.'; // Change the message if you want.
}
else { // does not exist ==> add to the table
$SQL2= "INSERT into tblnewsletter (email) VALUES ('".$email."')";
mysql_query($SQL2);
echo 'Thank you for subscribing'; // Change the message if you want.
}
?>
and here is my Javascript:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#nlsubmit').on('click', function() {
signup();
return false;
});
});
function trim(str) {
str = str.replace(/^\s*$/, '');
return str;
}
function signup()
{
var emailentered = $("#email").val();
var email = trim(emailentered);
//EMAIL VALIDATION
var goodEmail = email.match(/\b(^(\S+#).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.info)|(\.sex)|(\.biz)|(\.aero)|(\.coop)|(\.museum)|(\.name)|(\.pro)|(\.arpa)|(\.asia)|(\.cat)|(\.int)|(\.jobs)|(\.tel)|(\.travel)|(\.xxx)|(\..{2,2}))$)\b/gi);
var apos = email.indexOf("#");
dotpos = email.lastIndexOf(".");
lastpos = email.length - 1;
var badEmail = (apos < 1 || dotpos - apos < 2 || lastpos - dotpos < 2);
if (email == "" || !goodEmail || badEmail)
{
//Email address fails
$('myResponse').style.display = 'inline';
$('myResponse').style.color = 'red';
alert('Please enter a valid email');
$('email').focus();
return false;
}
else
{
email = encodeURIComponent(email);
//Email address succeeds
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});
}
}
function showResponse(req) {
$("loading").hide();
$("myResponse").innerHTML = req.responseText;
$("myResponse").style.display = "inline";
$("myResponse").style.color = "blue";
$("submit").show();
$("email").invoke('clear');
}
function showException(req) {
$("myResponse").innerHTML = req.responseText;
alert("An error occured while talking to the server. Please try again.");
$("loading", "myResponse").invoke('hide');
$("submit").show();
$("email").invoke('clear');
}
</script>
The form that is calling all this is as follows:
<form method="post" name="subform" id="subform" action="">
<input type="text" id="email" name="email" value="">
<input type="submit" id="nlsubmit" name="submit" value="Sign up">
<div id="myResponse" style="display:none;"></div>
<div id="loading" style="display:none;"><img src="/images/wait.gif" alt=""></div>
</form>
Like I said the newsletter table is updated great, though I'm needing the user to be notified on the same page if they are already present, if the email is invalid etc.
In your function:
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});
'result' refers to whatever was echoed on signup.php, so if result=="You are subscribed." that means that the email address already exists in the database, otherwise if result=="Thank you for subscribing" the email address is new to the database and the new user subscribed. So the function should look something like this:
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
if(result=="You are subscribed.")
{
// notify user that email address already exists
}
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});

Categories