AJAX form submission issue in Internet Explorer - ajax

For some reason the newsletter sign-up form bar I'm creating is not working as it should in IE. In fact, it's not working at all. If you visit the link below in Chrome or Firefox it works like it should, but in any version of IE it doesn't.
Anyone have any leads to fix this?
Here's the code, summarized:
$(function() {
$('#name').textboxhint({
hint: 'First Name'
});
$('#email').textboxhint({
hint: 'Email Address'
});
$("#submitButton").click(function() {
// VALIDATE AND PROCESS FORM
var name = $("#name").val();
var email = $("#email").val();
var dataString = 'name='+ name + '&email=' + email;
// HANDLE DATA: SHOW ERROR IF FIELDS ARE BLANK
if (name=='' || name=='First Name' ){
$('.errorIconName').show();
return false;
}
if (email=='' || email=='Email Address'){
$('.errorIconEmail').show();
return false;
}
else {
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(){
$('#signupWidget').fadeOut(400).hide();
$('#thankyouText').fadeIn(700).show();
$('.errorIcon').fadeOut(200).hide();
$('#signupWrap').delay(3000).fadeOut(800);
}
});
}
return false;
});
});
and...
<form action="" method="post">
<span id="sprytextfield1" class="pr20">
<input name="name" id="name" type="text"/>
<div class="errorIconName" style="display:none"></div>
</span>
<span id="sprytextfield2" class="pr20">
<input name="email" id="email" type="text"/>
<div class="errorIconEmail" style="display:none"></div>
</span>
<span>
<input type="submit" name="widgetButton" id="submitButton" value="SUBMIT"/>
</span>
</form>

Related

variable is not found inside ajax

<div class="modal-body">
<form>
<div class="form-group">
<label for="email" class="col-form-label">Email address:</label>
<input type="email" class="form-control" id="signUpEmail" name="email">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Password:</label>
<input type="password" class="form-control" id="signUpPassword" name="password" onchange="check_pass()">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Confirm Password:</label>
<input type="password" class="form-control" id="signUpConPassword" name="password" onchange="check_pass()">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="signUpSubmit" disabled="true" >Sign Up</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function check_pass()
{
//alert(document.getElementById('signUpPassword').value);
if (document.getElementById('signUpPassword').value ==
document.getElementById('signUpConPassword').value) {
document.getElementById('signUpSubmit').disabled = false;
}
else
{
document.getElementById('signUpSubmit').disabled = true;
}
}
$('#signUpSubmit').click(function()
{
//alert("signup completed");
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: $email,
password: $password
},
success: function() {
alert('Email Sent');
}
});
});
</script>
This code snippet shows ReferenceError: $email is not defined when I click on the signupSubmit button although I defined the variable inside the function.
I also try
var email=document.getElementById('signUpEmail').value;
var password = document.getElementById('signUpPassword').value;
but, same error. I guess there is a problem in variable declaration. What is the correct form of variable declaration inside the function?
You have to change the $email and $password to email ,password
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: email,
password: password
},
success: function() {
alert('Email Sent');
}
});
Remove the $
data: {
email: $email,
password: $password
},
The data being passed has two properties - "email" and "password", the values of the properties are stored in the variables email and password.
Your code should look like this:
/* Remove these two lines */
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
...
data: {
"email": $("#signUpEmail").val(),
"password": $("#signUpPassword").val()
}
The $ is the jQuery function call, and the "#signUpEmail" is the selector for the element with an id of "signUpEmail". The val() method will return the value of the input.
document.getElementById("something").value
is the same as
$("#something").val()
If you're using jQuery for the Ajax, you might as well use it to get the values.

Node JS Form Sumit using Ajax

I am new in Node JS , I want to submit a form using ajax like all we are doing in PHP/CakePHP but here i am facing a problem.
HTMl code
<form role="form" action="javascript:;" id="myform">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-default" id="enter">Submit</button>
</form>
My AJAX code is
$('.btn').click(function(e){
e.preventDefault();
var data = $('#myform').serialize();
$.ajax({
url: '/ajax',
type: 'POST',
cache: false,
data: JSON.stringify(data),
contentType: 'application/json',
success: function(data) {
console.log(data);
console.log(JSON.stringify(data));
},
error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err);
}
})
});
app.js code
app.post('/ajax', bodyParser(), function (req, res){
var obj = {};
console.log('body: ' + JSON.stringify(req.body));
var input = JSON.stringify(req.body);
var data = {
name : input.name,
email : input.email
};
var query = db.query("INSERT INTO users set ?",data, function(err, rows){
console.log(query.sql);
if (err)
console.log("Error inserting : %s ",err );
res.send({'success' : true, 'message' : 'Added Successfully'});
});
});
But when i submit this form then it generate an error in node console like
SyntaxError: Unexpected token "
at parse (D:\man_node\node_modules\body-parser\lib\types\json.js:83:15)
I think that, I am not 100% sure, that you should replace var data = $('#myform').serialize(); with var data = $('#myform').serializeArray();

Stop codeigniter from redirection

Is it possible to make codeigniter not to redirect after a failed login attempt and show a message on the same login box.
My login box is a popup type, which appears after I have clicked on the login button and disappears after clicking on the background.
Controllers
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required|trim|callback_validate_credentials');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run()){
$data=array(
'email' => $this->input->post('email'),
'is_logged_in' => 1
);
$this->session->set_userdata($data);
redirect('site/members');
}else {
$this->main();
}
}
public function validate_credentials(){
$this->load->model('model_users');
if($this->model_users->can_log_in()){
echo 'success';
} else {
echo 'failed';
}
}
I was trying to change elses with error messages but it still redirected to another page.
Html:
<div id="login-box" class="login-popup">
<input id="username" name="email" value="" type="text" autocomplete="on" placeholder="Username">
<input id="password" name="password" value="" type="password" placeholder="Password">
<button name="login_submit" class="submitbutton" onclick="checkFormData()">Login</button>
</div>
<script>
function checkFormData(){
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>site/validate_credentials",
data: {
email: $("#email").val(),
password: $("#password").val()
},
success: function(response) {
if(response == 'success'){
location.href = 'site/members';
} else {
$("#errors").show();
}
}
});
}
</script>
If you want to have the alert in the modal, you'll want to check the data with ajax (javascript or jquery). For example you'd have something like this:
function checkFormData(){
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>your_controller/validate_credentials",
data: {
email: $("#email").val(),
password: $("#password).val()
},
success: function(response) {
if(response == 'success'){
location.href = <where you want to send them>;
} else {
$("#errors").show();
}
}
});
}
And your HTML would look something like:
<div class="hide" id="errors">Incorrect username/password.</div>
<input type="email" id="email" />
<input type="password" id="password" />
The class="hide" is meant to be something CSS related where you would have something like "display: none;".
Then in your controller you'd check like this:
if($this->model_users->can_log_in()){
echo 'success';
} else {
echo 'failed';
}
The echoed response is what will be sent to your ajax success function.
Edit:
You need to not use the form submission for the above to work, because with that method we don't want to submit the form, we want to pass the data from it.
<div id="login-box" class="login-popup">
<input id="username" name="email" value="" type="text" autocomplete="on" placeholder="Username">
<input id="password" name="password" value="" type="password" placeholder="Password">
<button name="login_submit" class="submitbutton" onclick="checkFormData()">Login</button>
</div>
I've also changed the javascript function above to be viewed as a function.
use
window.location.href = '/redirectpage'

Passing checkbox value in ajax

Please, I need help in passing the check box value through ajax to other php file
This is my form :
<form class="form-horizontal" onsubmit="Javascript:return validate();" method="post" id="form">
<b>Jawwal Number</b>
<input name="msisdn" type="text" id="msisdn" class="form-control" required="" autofocus="" style="margin-top: 10px;margin-bottom: 10px" >
<b>Username</b>
<input name="username" type="text" id="username" class="form-control" required="" autofocus="" style="margin-top: 10px;margin-bottom: 10px" >
<b>Add Extra Security (Activation Code)</b>
<input type="checkbox" name="security" id="security">
<input type="submit" value="submit" class="btn btn-primary">
</form>
And this is my Ajax code :
$("#form").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* set all the vars you want to post on here */
var parameters = {
'msisdn': $('input[name="msisdn"]').val(),
'username': $('input[name="username"]').val(),
**'security':$('input[name="security"]').val(),**
'submit': $('input[name="submit"]').val()
};
$.ajax({
url: '/bulk2/admin/process/add_user.php',
method:'POST',
data: parameters,
success: function(msg) {
$('#test').append(msg);
}
})
});
What should I do so that I can pass the checkbox value to the other page ?
You can also use checkbox checked method.
var security = $('input[name="security"]').prop('checked'); /* it will return true or false */
and update your code
var parameters = {
'msisdn': $('input[name="msisdn"]').val(),
'username': $('input[name="username"]').val(),
'security':security,
'submit': $('input[name="submit"]').val()
};
Use the method is() with property :checked.
var parameters = {
'security':$('input[name="security"]').is(':checked'),
};
This works for me.

My Jquery tools Ajax modal login is not working in IE 7 and 8

I am working on modal login/registration forms. I'm not good with Javascript, but have hacked my way to some working Jquery for my Ajax call, and all is working nicely in Chrome 14.0.835.159 beta-m and in Firefox 5 and 6.0.2 and Opera 11.51. I used Firebug to see the JSON returning correctly and updating the error messages.
In FF/Opera/Chrome if I leave the username and login blank and I click the login button on the modal window, the returns count up the failed logins and display the return.I used firebuggerhttp://www.firebugger.com/ to look at what was going on in On IE 7 and 8.
If you leave the form fields blank, it seems the form is somehow "cached" and the call doesnt go through. None of the returns act on my login javascript to update the loginMsg div. If you change the input each time, "a", "as", "asd", the return counts up the failed logins as intended but still no update on my div
Very odd :-(
The test page is at camarillon.com/testpage.cfm
<!DOCType html>
<html>
<head>
<title>testpage - test ajax login</title>
<!-- include the Tools -->
<script src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"></script>
<!--- add styles --->
<link rel="stylesheet" type="text/css" href="css/loginbox.css" />
<!--- <noscript>This is what you see without javascript</noscript> --->
<CFSET structDelete(session, 'form')>
<cfset session.form.validate_require="username|'Username' is required.;password|'Password' is required.;confirmpassword|'Confirm password' is a required field.;">
<cfset session.form.validate_minlength="username|'Username' must be at least 3 characters long.;password|'Password' must be at least 7 characters long.">
<cfset session.form.validate_maxlength="username|'Username' must be less than 6 characters long.">
<cfset session.form.validate_alphanumeric="username|'Username' must be alphanumeric.">
<cfset session.form.validate_password="confirmpassword|password|'Password' and 'Confirm Password' must both match.">
</head>
<body>
<cfparam name="session.auth.loggedIn" default="false">
<div id="loginMenu">
<cfif session.auth.loggedIn>
Log out
<cfelse>
<button class="modalInput" rel="#login">Login</button>
<button class="modalInput" rel="#register">Register</button>
</cfif>
</div>
<!-- user input dialog -->
<cfif isDefined("session.auth.failedLogins")>
<cfset loginMsg=#session.auth.failedLogins# & " failed logins">
<cfelse>
<cfset loginMsg="Please log in">
</cfif>
<script>
$(document).ready(function() {
var triggers = $(".modalInput").overlay({
// some mask tweaks suitable for modal dialogs
mask: {
color: '#ccc',
loadSpeed: 200,
opacity: 0.5
},
closeOnClick: false,
onClose: function () {
$('.error').hide();
}
});
$("#toomanylogins").overlay({
mask: {
color: '#ccc',
loadSpeed: 200,
opacity: 0.9
},
closeOnClick: false,
load: false
});
$("#loginForm").submit(function(e) {
var form = $(this);
// submit with AJAX
$.getJSON("cfcs/security.cfc?method=processLogin&ajax=1&returnformat=JSON&queryformat=column&" + form.serialize(), function(json) {
// everything is ok. (server returned true)
if (json === true) {
// close the overlay
triggers.eq(0).overlay().close();
$("#loginMenu").html("<a href='logout.cfm'>Log out</a>");
// server-side validation failed. use invalidate() to show errors
} else if (json === "More than five") {
var tempString
tempString = "<h2>Too many failed logins </h2>"
$("#loginMsg").html(tempString);
triggers.eq(0).overlay().close();
$("#toomanylogins").overlay().load();
} else {
var tempString
tempString = "<h2>" + json + " failed logins</h2>"
$("#loginMsg").html(tempString);
}
});
// prevent default form submission logic
e.preventDefault();
});
// initialize validator and add a custom form submission logic
$("#signupForm").validator().submit(function(e) {
var form = $(this);
// client-side validation OK.
if (!e.isDefaultPrevented()) {
// submit with AJAX
$.getJSON("cfcs/security.cfc?method=processSignup&returnformat=JSON&queryformat=column&" + form.serialize(), function(json) {
// everything is ok. (server returned true)
if (json === true) {
// close the overlay
triggers.eq(1).overlay().close();
$("#loginMenu").html("<a href='logout.cfm'>Log out</a>");
// server-side validation failed. use invalidate() to show errors
} else {
form.data("validator").invalidate(json);
}
});
// prevent default form submission logic
e.preventDefault();
}
});
$.tools.validator.fn("[minlength]", function(input, value) {
var min = input.attr("minlength");
return value.length >= min ? true : {
en: "Please provide at least " +min+ " character" + (min > 1 ? "s" : ""),
};
});
$.tools.validator.fn("[data-equals]", "Value not equal with the $1 field", function(input) {
var name = input.attr("data-equals"),
field = this.getInputs().filter("[name=" + name + "]");
return input.val() == field.val() ? true : [name];
});
});
</script>
<!-- yes/no dialog -->
<div class="modal" id="toomanylogins">
<h2>Having problems logging in?</h2>
<p>
If you have forgotten your password you can request a reset.
</p>
<!-- yes/no buttons -->
<p>
<button class="close"> Cancel </button>
</p>
</div>
<div class="modal" id="login">
<!-- login form -->
<form name="loginForm" id="loginForm" autocomplete="off" method="get" action="">
<div id="loginMsg"><h2><cfoutput>#loginMsg#</cfoutput></h2></div>
<p><input type="text" name="username" placeholder="username..." title="Must be at least 8 characters." <!--- required="required" --->></p>
<p><input type="password" name="password" placeholder="password..." title="Try to make it hard to guess" <!--- required="required" --->></p>
<p>
<button type="submit"> Login </button>
<button type="button" class="close"> Cancel </button>
</p>
</form>
</div>
<div class="modal" id="register">
<!-- signup form-->
<form id="signupForm" autocomplete="off" method="get" action="" novalidate="novalidate">
<fieldset>
<p>
<label>firstname *</label>
<input id="firstname" type="text" name="firstname" placeholder="firstname..." required="required"/></p>
<p>
<label>lastname *</label>
<input type="text" name="lastname" placeholder="lastname..." required="required"/></p>
<p>
<label>email *</label>
<input type="email" name="email" placeholder="email..." required="required"/></p>
<p>
<label>username *</label>
<input type="text" name="username" placeholder="username..." required="required"/>
</p>
<p>
<label>password *<br>
<input type="password" name="password" required="required" placeholder="password..." /></label>
</p>
<p>
<label>confirm password *<br>
<input type="password" name="confirmpassword" data-equals="password" placeholder="password..." required="required"/></label>
</p>
<p>
<button type="submit">Sign Up</button>
<button type="button" class="close"> Cancel </button>
</p>
</fieldset>
</form>
</div>
</body>
</html>
Back end is in Coldfusion, but I don't think thats relevant, the JSON returns work just fine in FF etc
Any pointers about what I presume is some bug in my Javascript appreciated, my JQuery kung foo is not strong :-(
Logans solution below is correct ... I also had a trailing comma in here which was wrong only bugging out in IE 5-7
$.tools.validator.fn("[minlength]", function(input, value) {
var min = input.attr("minlength");
return value.length >= min ? true : {
en: "Please provide at least " +min+ " character" + (min > 1 ? "s" : ""),
};
});
should have been
$.tools.validator.fn("[minlength]", function(input, value) {
var min = input.attr("minlength");
return value.length >= min ? true : {
en: "Please provide at least " +min+ " character" + (min > 1 ? "s" : "")
};
});
Instead of using $.getJSON, you can use $.ajax and set the cache option to false. I think that sound fix the issue.
$("#loginForm").submit(function(e) {
var form = $(this);
$.ajax({
type: 'GET',
url: "cfcs/security.cfc?method=processLogin&ajax=1&returnformat=JSON&queryformat=column&" + form.serialize(),
dataType: "json",
cache: false,
success: function(json) {
// everything is ok. (server returned true)
if (json === true) {
// close the overlay
triggers.eq(0).overlay().close();
$("#loginMenu").html("<a href='logout.cfm'>Log out</a>");
// server-side validation failed. use invalidate() to show errors
} else if (json === "More than five") {
var tempString
tempString = "<h2>Too many failed logins </h2>"
$("#loginMsg").html(tempString);
triggers.eq(0).overlay().close();
$("#toomanylogins").overlay().load();
} else {
var tempString
tempString = "<h2>" + json + " failed logins</h2>"
$("#loginMsg").html(tempString);
}
}
});
// prevent default form submission logic
e.preventDefault();
});
// initialize validator and add a custom form submission logic
$("#signupForm").validator().submit(function(e) {
var form = $(this);
// client-side validation OK.
if (!e.isDefaultPrevented()) {
// submit with AJAX
$.ajax({
type: 'GET',
url: "cfcs/security.cfc?method=processSignup&returnformat=JSON&queryformat=column&" + form.serialize(),
dataType: "json",
cache: false,
success: function(json) {
// everything is ok. (server returned true)
if (json === true) {
// close the overlay
triggers.eq(1).overlay().close();
$("#loginMenu").html("<a href='logout.cfm'>Log out</a>");
// server-side validation failed. use invalidate() to show errors
} else {
form.data("validator").invalidate(json);
}
}
});
// prevent default form submission logic
e.preventDefault();
}
});
Did you try out
$.ajaxSetup({
cache: false
});
at the beginning of document ready?
Really looks like a problem with the jQuery Cache. If this helps, it certainly is.

Resources