Unable to send email via ajax [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I need help to find what mistake I am doing , because I'm trying to develop a function that send email from a HTML form using php and ajax , the problem I'm facing is whenever I click on submit bouton the page is refreshing , usually as we can see in the javascript script , I'm supposed to receive a message that shows that it was successfully send
Best regards,
PHP File :
<?php
if (isset($_REQUEST['email'])) {
//Email information
$admin_email = "basselbizri#gmail.com";
$name = $_REQUEST['first_name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
//send email
if (mail($admin_email, $name, $message, "From:" . $email)) {
echo 1;
}
else {
echo 0;
}
}
?>
HTML Form :
<form class="inline" id="contactForm" method="post" >
<div class="row">
<div class="col-sm-6 height-contact-element">
<div class="form-group">
<input type="text" name="first_name" class="form-control custom-labels" id="name" placeholder="FULL NAME" required data-validation-required-message="Please write your name!"/>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-sm-6 height-contact-element">
<div class="form-group">
<input type="email" name="email" class="form-control custom-labels" id="email" placeholder="EMAIL" required data-validation-required-message="Please write your email!"/>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-sm-12 height-contact-element">
<div class="form-group">
<input type="text" name="message" class="form-control custom-labels" id="message" placeholder="WHAT'S ON YOUR MIND" required data-validation-required-message="Please write a message!"/>
</div>
</div>
<div class="col-sm-3 col-xs-6 height-contact-element">
<div class="form-group">
<input type="submit" class="btn btn-md btn-custom btn-noborder-radius" value="Send It"/>
</div>
</div>
<div class="col-sm-3 col-xs-6 height-contact-element">
<div class="form-group">
<button type="button" class="btn btn-md btn-noborder-radius btn-custom" name="reset">RESET
</button>
</div>
</div>
<div class="col-sm-3 col-xs-6 height-contact-element">
<div class="form-group">
<div id="response_holder"></div>
</div>
</div>
<div class="col-sm-12 contact-msg">
<div id="success"></div>
</div>
</div>
</form>
JS Script :
$('#contactForm').on('submit', function(e){
e.preventDefault();
e.stopPropagation();
// get values from FORM
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var goodToGo = false;
var messgaeError = 'Request can not be send';
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][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if (name && name.length > 0 && $.trim(name) !='' && message && message.length > 0 && $.trim(message) !='' && email && email.length > 0 && $.trim(email) !='') {
if (pattern.test(email)) {
goodToGo = true;
} else {
messgaeError = 'Please check your email address';
goodToGo = false;
}
} else {
messgaeError = 'You must fill all the form fields to proceed!';
goodToGo = false;
}
if (goodToGo) {
$.ajax({
data: $('#contactForm').serialize(),
beforeSend: function() {
$('#success').html('<div class="col-md-12 text-center"><img src="images/spinner1.gif" alt="spinner" /></div>');
},
success:function(response){
if (response==1) {
$('#success').html('<div class="col-md-12 text-center">Your email was sent successfully</div>');
window.location.reload();
} else {
$('#success').html('<div class="col-md-12 text-center">E-mail was not sent. Please try again!</div>');
}
},
error:function(e){
$('#success').html('<div class="col-md-12 text-center">We could not fetch the data from the server. Please try again!</div>');
},
complete: function(done){
console.log('Finished');
},
type: 'POST',
url: 'js/send_email.php',
});
return true;
} else {
$('#success').html('<div class="col-md-12 text-center">'+messgaeError+'</div>');
return false;
}
return false;
});
});

In your success() method you're reload()'ing the page.
if (response==1) {
$('#success').html('<div class="col-md-12 text-center">Your email was sent successfully</div>');
window.location.reload(); // <----- remove this; it's causing the page to reload
}
So when your mail() function resolves true, in your PHP file (send_email.php), you're returning 1 to your AJAX response which is allowing the if (response == 1) to satisfy, and then you're using window.location.reload() to reload the page. Removing window.location.reload(); will keep the page from reloading.

Related

JQuery post to submit HTML form data to php file not working

I am new to Jquery but I have done a lot with html/php in the past. What I need to do is submit for data from within a popup modal, insert that into a mysql database on localhost and then open teh next popup via javascript. As redirecting to the php page does not allow you to load js, I have looked into using jquery to post the data to my phpfile, which will then insert the data and return a code to the jquery, which will then load the next popup if the post was succesful. I have tried different tutorials, but I just cannot get the code to work. Below is my index.php file, which contains the popup form and jquery code...
<div id="survey1" class="w3-modal">
<div class="w3-modal-content w3-animate-top w3-card-4">
<div class="w3-container w3-padding-16">
<div class="section-heading text-center">
<div class="col-md-12 col-xs-12">
<h1>BASIC <span>DETAILS</span></h1>
<p class="subheading">The basics of your business and your website.</p>
</div>
</div>
<form role="form" class="login-form" method="post" action="http://localhost/basic.php" id="basicForm">
<div class="input-group form-group">
<span class="input-group-addon" id="basic-addon1"><i class="fas fa-envelope"></i></span>
<input type="text" class="form-control" placeholder="Full Name" aria-describedby="basic-addon1" name="name" id="name">
</div>
<div class="input-group form-group">
<span class="input-group-addon" id="basic-addon1"><i class="fas fa-envelope"></i></span>
<input type="text" class="form-control" placeholder="Email" aria-describedby="basic-addon1" name="email" id="email">
</div>
<div class="input-group form-group">
<span class="input-group-addon" id="basic-addon1"><i class="fas fa-envelope"></i></span>
<input type="text" class="form-control" placeholder="Business Name" aria-describedby="basic-addon1" name="bname" id="bname">
</div>
<div class="input-group form-group">
<span class="input-group-addon" id="basic-addon1"><i class="fas fa-envelope"></i></span>
<input type="text" class="form-control" placeholder="Business Type" aria-describedby="basic-addon1" name="btype" id="bemail">
</div>
<div id="response"></div>
<button class="btn" type="submit" id="submit1" name="submit1" style="width:40%; float: right;"></button>
</form>
<script>
$(document).ready(function(){
$('#basicForm').on('submit', function(e){
e.preventDefault();
$('#submit1').prop('disabled', true);
var name = $('#name').val();
var email = $('#email').val();
var bname = $('#bname').val();
var btype = $('#bemail').val();
if(name == '' || email == '' || bname == '' || btype == '')
{
$('#submit1').prop('disabled', false);
}
else
{
$.post(
'http://localhost/TDS/basic.php',
$('#basicForm').serialize(),
function(data)
{
$('form').triggered("reset");
$('#submit1').prop('disabled', false);
}
);
}
});
});
</script>
</div>
</div>
</div>
And this is my php insert file...
<?php
require('connection.php')
if(isset($_POST["name"]))
{
$name = mysqli_real_escape_string($con, $_POST["name"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$bname = mysqli_real_escape_string($con, $_POST["bname"]);
$btype = mysqli_real_escape_string($con, $_POST["btype"]);
$insert_query = "INSERT INTO Details ('Name', 'Email', 'Business Name', 'Businesss
Type') VALUES ('".$name."', '".$email."', '".$bname."', '".$btype."')";
if(mysqli_query($con, $insert_query))
{
echo json_enchode(success => 1);
}
else
{
echo json_enchode(success => 0);
}
}
?>
Any help would be much appreciated!
The code itself is OK, but you need to load jQuery itself.
Put this somewhere in the beginning of your HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
(the tips on how to include jQuery see here: https://www.w3schools.com/jquery/jquery_get_started.asp)
Except this, the code worked for me:
- The form was submitted correctly;
- The PHP endpoint received the correct POST data;
The saving to DB I didn't check, but it looks OK.
Anyways, the PHP part is out of the scope of the question.
Also, a small issue is in the code itself: there's no such method as "$('form').triggered('reset');", use "$('form').trigger('reset');" instead.

Ajax Login Response Error

i'm traying to login with ajax and php, in that situation i'm logging succesfuly actually. But i'm trying to make an alert and refresh the page when logged in.
When i attempt to login, its gives me error and no refreshing. But if i refresh the page, i see i have session in php. I don't understand why.
Here is my code;
<script>
$(document).ready(function(){
$('#login_btn').click(function(){
var email = $('#email').val();
var password = $('#password').val();
if(email == '' || password == ''){
$("#login_error").html("*** Please enter your email / password");
}else{
$('#login_error').html("<strong class='text-success'>Validating...</strong>");
$.ajax({
url: "login.php",
method: "post",
data:{email:email, password:password},
success: function(data){
if (data === 'yes') {
window.location.reload();
}else{
$('#login_error').html("<strong class='text-danger'>ERROR...</strong>");
}
}
});
}
});
});
</script>
login php:
<?php
session_start();
include ('../config/setup.php'); #database connection
if(isset($_POST['email'])){
$q = "SELECT * FROM users WHERE email = '$_POST[email]' AND password = '$_POST[password]'";
$r = mysqli_query($dbc, $q);
if(mysqli_num_rows($r) > 0){
$_SESSION['email'] = $_POST['email'];
echo "yes";
}else{
echo "no";
}
}
?>
Html: (Using login form inside a modal)
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<label for="email" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="email" class="form-control" name="email" id="email" placeholder="Account Email">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-4 control-label">Password</label>
<div class="col-sm-8">
<input type="password" class="form-control" name="password" id="password" placeholder="Account Password" >
</div>
</div>
<div class="form-group">
<div class="col-sm-1"></div>
<div align="center" class="col-sm-10">
<button name="login_btn" id="login_btn" class="btn btn-success btn-block text-center"><span id="loader_before" class="glyphicon glyphicon-log-in" aria-hidden="true"></span><i id="loader" class="fa fa-spinner fa-spin fa-x fa-fw"></i> Log in to Account</button>
</div>
<div class="col-sm-1"></div>
</div>
</div>
<div align="center" class="container-fluid">
<h6><strong class="text-danger">Forgot your password? Click here..</strong></h6>
</div>
<h5><div id="login_error" class="text-warning"></div></h5>
</div>
You just need to update your if block in response as below
`
if (data === 'yes') {
alert("You message here!");
window.location.reload();
}else{
$('#login_error').html("<strong class='text-danger'>ERROR...</strong>");
}
`
When you call echo on php, it will write the value, but not return it. That's the problem.
You are not returning "yes" or "no" from login.php, you're just doing echo, which will only write the value but not return it to the caller.
The ajax call is waiting for a response to process it with the 'success' callback. Since login.php is not returning anything, it will always fall into the else clause.
The solution is to change this on login.php
if(mysqli_num_rows($r) > 0){
$_SESSION['email'] = $_POST['email'];
return "yes";
}else{
return "no";
}

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.....
}

PHP Update Cell Data Error

HeyHeyHey!
I am having this problem, for some reason it won't add the Data to my MYSQL Database and I have no idea why. I looked at a lot of other posts here on StackOverflow, but can't seem to find a post that helps me :)
Here is my code:
<script>
$('.alert-saved-changes-success2').hide();
$(".save-tradelink-profile").click(function() {
$tradelinkvalue = document.getElementById("tradelink").value;
if ($.trim($('#tradelink').val()) == '') {
alert('Tradelink can not be blank');
} else if ($tradelinkvalue.indexOf("https://steamcommunity.com/tradeoffer/new") >= 0) {
<?php //TRYING TO UPDATE DATA
$TradelinkValue = $_POST['GetTradelinkValue'];
mysql_query("UPDATE item-jackpot-users SET tradelink=$TradelinkValue WHERE steam_id=$steamid") or die(mysql_error());
?>
$("#alert-saved-changes-success").slideDown("slow");
} else {
alert('Tradelink has to be valid');
}
});
$(".logout-button-profile").click(function(){
window.location.href = "steamauth/logout.php";
});
</script>
It seems like the php tag gets loaded before everything else, since the
$('.alert-saved-changes-success2').hide();
doesn't load. It finds the error, and then just killing everything else.
Respecting the fact that yes, php is performed before your webbrowser receives the js text, you could use a form, that sends your update information into post(like using a form tag), reload the page, and make the page perform the update with your post data. You could also use ajax.
<form name="login" class="form-horizontal" method="post" action="refer to this file" >
<div class="form-group">
<label class="col-sm-3 control-label">
Username
</label>
<div class="col-sm-2">
<input class="pull-right" type="text" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">
Password
</label>
<div class="col-sm-2">
<input class="pull-right" type="password" name="password" />
</div>
</div>
<div class="form-group">
<div class=" col-sm-offset-3 col-sm-2">
<button type="submit" name="submitbtn" class="btn btn-default pull-right">
Sign in
</button>
</div>
</div>
</form>
<?php
$user = $_POST['username'];
$pwd = $_POST['password'];
//DO SOME SANITIZATION!
//Store $user and $pwd
?>
Ofcourse you could include the php part somewhere else in the file, like inside of a script tag.

login function doesn't work in firefox but works on chrome,IE,safari and opera [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i made a login for my backend web page using jquery.
here is the form:
<form method="post" action="#" autocomplete='off'>
<h1 class="white-text">ADMIN Log in</h1>
<div class="row"><div id="errMsg"></div></div>
<div class="row">
<div class="large-12"><input type="text" placeholder="User ID" name="txtUsername" id="txtUsername"></div>
</div>
<div class="row">
<div class="large-12"><input type="password" placeholder="Password" name="txtPassword" id="txtPassword"></div>
</div>
<div class="row">
<div class="large-12 columns">
<p>Need Help Signing in?</p>
</div>
</div>
<div class="large-12 columns ">
<input type="submit" value="Sign In" class="button right" onclick="validLogin()">
</div>
</form>
here is the jQuery that handles the login:
function validLogin(){
var username=$('#txtUsername').val();
var password=$('#txtPassword').val();
var dataString = 'username='+ username + '&password='+ password;
$("#errMsg").hide();
$.ajax({
type: "POST",
url: "processed.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
if(result=='admin'){
window.location='admin.php';
}else if(result=='Invalid ID or password!') {
$("#errMsg").show(100);
$("#errMsg").html("LOGIN FAILED!: " + result);
}else{
$("#errMsg").fadeIn(100);
$("#errMsg").html(result);
}
}
});
}
and here is the php file from the url of the jquery:
<?php
session_start();
include('include/connection.php');
$message=array();
if(isset($_POST['username']) && !empty($_POST['username'])){
$username=$_POST['username'];
}else{
$message[]='<i class="foundicon-error"></i> username';
}
if(isset($_POST['password']) && !empty($_POST['password'])){
$password=stripslashes($_POST['password']);
}else{
$message[]='<i class="foundicon-error"></i> password';
}
$countError=count($message);
if($countError > 0){
echo "Please enter your ";
for($i=0;$i<$countError;$i++){
if ($i > 0){
$con=" and ";
}else {
$con="";
}
echo $con.$message[$i];
}
}else{
$query="select * from admin_users where username='$username' and password='$password'";
$res = mysqli_query($connect,$query);
while($row = mysqli_fetch_assoc($res))
{
$userlvl = $row['user_level'];
}
$checkUser=mysqli_num_rows($res);
if($checkUser > 0){
$_SESSION['LOGIN_STATUS']=true;
$_SESSION['uname']=$username;
if ($userlvl == 1) {
echo 'admin';
}
else {
echo 'techadmin';
}
}else{
echo "Invalid ID or password!";
}
}
?>
i have no clue why do these codes doesn't work on firefox but it works flawlessly on chrome, IE, opera and safari..
it doesn't go to the page where it is intended to go... it just stays on the login page... no error returns or whatsoever... and also, there are no error logs in the console
function validLogin(){
event.preventDefault();
^
event is not defined, causes javascript abort.
also check a developer console, F12 key, or install a plugin FireBug for Firefox and see what console says.
EDIT
Are you sure that jQuery is enabled?
Can you post a jsfiddle for this case with full scenario?
Check console to see javascript errors, maybe you have parsing error somewhere, developer console will help.
EDIT2
change form
<form method="post" onsubmit="return validLogin();" action="#" autocomplete='off'>
.....
<div class="large-12 columns ">
<input type="submit" value="Sign In" class="button right">
</div>
</form>
and Js to:
function validLogin(){
var username=$('#tx....
.....
.....
return false; // at the end
}
jsfiddle: http://jsfiddle.net/9kcx9/
This should fix your problem. First give form an id:
<form method="post" action="#" autocomplete="off" id="myform">
<h1 class="white-text">ADMIN Log in</h1>
<div class="row"><div id="errMsg"></div></div>
<div class="row">
<div class="large-12"><input type="text" placeholder="User ID" name="txtUsername" id="txtUsername"></div>
</div>
<div class="row">
<div class="large-12"><input type="password" placeholder="Password" name="txtPassword" id="txtPassword"></div>
</div>
<div class="row">
<div class="large-12 columns">
<p>Need Help Signing in?</p>
</div>
</div>
<div class="large-12 columns ">
<input type="submit" value="Sign In" class="button right">
</div>
</form>
validLogin will have a Event passed, catch it using evt as parameter, using evt.preventDefault( ) and return false; (at the end) to prevent the default submit actions. Get your form element and set onsubmit=validLogin.
function validLogin(evt){
evt.preventDefault( );
var username=$('#txtUsername').val();
var password=$('#txtPassword').val();
var dataString = 'username='+ username + '&password='+ password;
$("#errMsg").hide();
$.ajax({
type: "POST",
url: "processed.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
if(result=='admin'){
window.location='admin.php';
}else if(result=='Invalid ID or password!') {
$("#errMsg").show(100);
$("#errMsg").html("LOGIN FAILED!: " + result);
}else{
$("#errMsg").fadeIn(100);
$("#errMsg").html(result);
}
}
});
return false;
}
document.getElementById("myform").onsubmit = validLogin;
tested here, works in firefox and chrome (open the jsbin console to see its working )

Categories

Resources