Before i proceed, i would like to say i am a beginner and i am trying to validate a form using ajax, for username availability. Validations are done. But, everytime the page gets redirected to the form action page (Even if there are errors). I want, if there are errors i get a alert message and if no errors then data is written to db. I have been trying this for quite some time but i think i messed up and i dont understand what is wrong. Please, correct my mistakes. I am just trying to learn. What i am doing wrong here and what should i do?
registration.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--<link rel="stylesheet" type="text/css" href="css/style.css"/>-->
<title>Using AJAX</title>
<script type="text/javascript" src="jquery-2.1.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#txtUsr').on('keyup', function(){
var username=$("#txtUsr").val();
var user_name_avail_result=$('.check');
var userCorrect=true;
if(username.length>2)
{
$.ajax({
type : 'POST',
cache:'false',
data : "username="+username,
url : "usr_available.php",
beforeSend: function()
{
user_name_avail_result.fadeIn(1000).html('<img src="green_ajax-loader.gif" /> ');
},
success: function(responseText) {
if(responseText == 200)
{
$(".check").html("<img src='available.png'/><span style='color:#59b200;'>Username available</span>");
}
else if(responseText ==201)
{
$(".check").html("<img src='not-available.png'/><span style='color:#ff0033;'>Username not available</span>");
userCorrect=false;
}
else if(responseText==202)
{
$(".check").html("Username too short");
userCorrect=false;
}
}
});
}
else
{
user_name_avail_result.html('<span style="color:#e50000;">Name too Short!</span>');
userCorrect=false;
}
if(username.length == 0) {
user_name_avail_result.html("");
userCorrect=false;
}
var exprUsr=/(^[A-Za-z][A-Za-z0-9]*([._-][a-z0-9]+){3,15})$/;
if(!exprUsr.test(username))
{
userCorrect=false;
}
});
$("#txtPwd").on('keyup',function(){
var regPwd=/^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{6,12})+$/;
var passTxt=$('#txtPwd').val();
var pwdCorrect=true;
if(!regPwd.test(passTxt))
{
$(".chkPwd").html('<div style="width:200px; height:80px; margin-left:190px; margin-top:-20px; text-align:left;"><span style="font-size:small; color:#ff0033;">Password must contain at least one digit, one lowercase, one uppdercase and one special character</span></div>');
pwdCorrect=false;
}
else
{
$(".chkPwd").html("");
}
if(passTxt.length==0)
{
$(".chkPwd").html("You Must Enter a Password");
pwdCorrect=false;
}
});
$("#txtUsr,#txtPwd,#txtMob").keydown(function(e) { <!-- Dont allow users to enter spaces for their username and passwords and Mobile Number-->
if (e.which == 32) {
return false;
}
});
$("#txtMob").keydown(function(e){<!--No other keys except number keys and backspace and tab work-->
if(e.which==8 || e.which==9)
return true;
if(e.which<48 || e.which>57)
return false;
});
$("#txtMob").on('keyup',function(){
var exprMob=/^[789]\d{9}$/;
var mobNum=$('#txtMob').val();
var mobCorrect=true;
if(!exprMob.test(mobNum))
{
if(mobNum.length<10)
{
$("#span3").html("Number must be minimum 10 characters long");
mobCorrect=false;
}
else
{
$("#span3").html("Number in wrong format");
mobCorrect=false;
}
}
else
{
$("#span3").html("");
}
});
function Validation(n){
if(userCorrect==false || pwdCorrect==false || window.mobCorrect==false)
{
alert("One or More field(s) is/are unfinished/empty. Please re-check.");
return false;
}
else
{
return true;
}
}
});
</script>
<script type="text/javascript">
function clearAll()
{
document.getElementById("txtUsr").value="";
document.getElementById("txtPwd").value="";
document.getElementById("txtMob").value="";
}
</script>
<style>
.chkPwd
{
margin-left:80px;
}
.check
{
margin-left:90px;
}
.form
{
margin:auto;
text-align:center;
font-family:Consolas;
font-size:medium;
}
.texts
{
font-family:Consolas;
}
#userDiv
{
background-color:#ccdbff;
height:320px;
width:500px;
border-radius:10px;
opacity:0.8;
}
#mainBody
{
background-color:#7a7acc;
width:100%;
height:100%;
}
</style>
</head>
<body class="form" id="mainBody">
<h1 style="color:#bfff00;">Registration</h1><br>
<form class="form" id="regForm" action="registration_success.php" method="POST" onsubmit="return Validation(this)">
<div class="form" id="userDiv"><br><br>
Username: <input class="texts" id="txtUsr" name="txtUsr" type="text" placeholder="Type user name here" autocomplete="off" maxlength="15" autofocus="autofocus" title="Please dont enter an aweful username!"/><br>
<span id="span1" class="check" style="font-size:small; color:"></span>
<br>
Password: <input type="password" id="txtPwd" class="texts" name="txtPwd" placeholder="Type password here" autocomplete="off" maxlength="12" title="Password must contain at least one digit, one lowercase, one uppdercase and one special character"/><br>
<span id="span2" class="chkPwd" style="font-size:small; color:red;">Min 6 and Max 12 Characters</span><br>
MobileNo.:<input type="text" maxlength="10" id="txtMob" class="texts" name="txtMob" placeholder="Enter your mobile number here" autocomplete="off" title="Please enter numbers only"/><br>
<span id="span3" class="chkMob" style="font-size:small; margin-left:10px; color:#ff0033; font-size:small;"></span><br>
<pre class="texts"> <input type="button" value="Back To LogIn" id="register" class="texts" name="register"/> <input type="submit" value="Submit" id="submit" class="texts" name="send"/> <input type="button" value="Reset" id="clear" onclick="clearAll()"/></pre>
</div>
</form>
</body>
</html>
user_available.php
<?php
if($_SERVER['REQUEST_METHOD']==='POST'){
if(!empty($_POST['username'])){
mysql_connect("localhost", "root","") or die ("Oops! Server not connected"); // Connect to the host
mysql_select_db("db_chkAJAX") or die ("Oops! DB not connected"); // select the database
// Check for the username posted
$username= mysql_real_escape_string($_POST["username"]); // Get the username values & prevent SQL-Injection
if(strlen($username)>2){
$check_query= mysql_query('SELECT Username FROM LoginRecord WHERE Username = "'.$username.'" ') or die("Cannot get data from table"); // Check the database
if(mysql_num_rows($check_query)<1){ // check num or rows 0 or greater than 0
echo 200;//Username doesnot exist in database
}
else{
echo 201;//Username exists in databse
}
} else {
echo 202;//Too short username
}
}
mysql_close($link);
return;//Stop execution
}
?>
registration_success.php
<!--Writing to the database-->
<?php
if(isset($_POST['send']) && !empty($_POST['txtUsr']) && !empty($_POST['txtPwd']) && !empty($_POST['txtMob']))
{
//Connecting to databse
$usr_name=test_input(strtolower($_POST['txtUsr']));
$pwd=$_POST['txtPwd'];
$mob=test_input($_POST['txtMob']);
$db_host='localhost';
$db_user='root';
$db_pwd='';
$conn=mysql_connect($db_host, $db_user, $db_pwd,true);
if(!$conn)
{
echo "Database connection Unsuccessful".mysql_error($conn)."<br>";
}
else
{
echo "Database connection Successful"."<br>";
}
//Creating a new database
$sql="CREATE DATABASE IF NOT EXISTS db_chkAJAX";
if (mysql_query($sql,$conn))
{
echo "Database db_student created successfully"."<br>";
}
else
{
echo "Error creating database: "."<br>";
}
//Creating a Table
$dataselect=mysql_select_db("db_chkAJAX",$conn);
if(!$dataselect)
{
die("Database not Selected".mysql_error()."<br>");
}
else
{
echo "Database Selected"."<br>";
}
$sql_create="CREATE TABLE IF NOT EXISTS LoginRecord (Username varchar (50), Password varchar(15), MobileNumber bigint(10))";
$qry=mysql_query($sql_create);
if(!$qry)
{
die("Table not created".mysql_error()."<br>");
}
else
{
echo "Table Created Successfully"."<br>";
}
//Inserting values into table
$data_insert="INSERT INTO LoginRecord(Username, Password, MobileNumber) VALUES('$usr_name', '$pwd', '$mob')";
$data_insert_query=mysql_query($data_insert);
if(!$data_insert_query)
{
die(" Unsuccessful data Insertion into table".mysql_error()."<br>");
}
else
{
echo "Data inserted into table successfully"."<br>";
}
//Closing the connection
mysql_close($conn);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
One problem, you are using html comments in your javascript instead of javascript comments, use //
http://www.jshint.com
Also, It looks like you need to set the check variables as global, since you are validating outside of the function that checks if they are valid.
I don't think you need to put this inside of Validate()
http://www.w3schools.com/js/js_form_validation.asp
Related
While testing some Ajax and PHP code I stumbled an issue with AJAX's responseText. When I use it without trim() a comparison in inside the function registration (see js.js) fails. I have verified if the response of the php code does not include a newline (see registration.php).
form.php
<?php?>
<html>
<head>
<script type="text/javascript" src=".js"></script>
</head>
<body>
<div>
<form>
<div>
Name : <input type="text" id="name"><br />
LastName : <input type="text" id="lastname"><br />
<input type="button" value="send" onclick="registration()">
<div id="message"></div>
</div>
</form>
</div>
</body>
</html>
js.js
function getRequestHttp()
{
var requestHTTP;
if(window.XMLHttpRequest)
{
requestHttp=new XMLHttpRequest();
if(requestHttp.overrideMimeType)
requestHttp.overrideMimeType('text/xml');
}
return requestHttp;
}
function getDataForm() {
var name,lastname,all;
name = document.getElementById('name').value;
lastname = document.getElementById('lastname').value;
all = "name="+name+"&lastname="+lastname;
return all;
}
function registration()
{
req.open('POST','inscription.php',false);
req.setRequestHeader('Content-Type','application/x-www-form-
urlencoded');
req.send(getDataForm());
if(req.readyState==4)
{
if(req.status==200)
{
//alert(req.responseText);
document.getElementById('message').innerHTML = "";
if (req.responseText.trim()=="no")
document.getElementById('message').innerHTML = "already exists";
else if (req.responseText.trim()!="no")
{
document.getElementById('message').innerHTML = "registration succeeded";
}
else
document.getElementById('message').innerHTML = "problem ";
}
else
alert("Error :"+req.status+",wrong request");
}
return true;
}
registration.php
<?php
header("Content-type: text/plain");
$conn=pg_connect("host=localhost dbname=data user=user password=pass")
or die ("Connexion Impossible".pg_last_error());
$name= $_POST['name'];
$lastname=$_POST['lastname'];
$request="SELECT registration('$name','$lastname')";
$res=pg_query($conn,$request) or die('damn ' . pg_last_error());
$code=pg_fetch_row($res)[0];
if ($code==0) echo "no"; else echo $code;
?>
Because some times the spaces are being concatenated and your condition doesn't fulfill what you want. so for we use trim to avoid white spaces from both sides of results. Lets say we got success message from ajax request and we wrote condition like this :
if(response.message == "success"){
//do this
}else{
//do this
}
So in this case the response messages sometime comes with some white spaces appended thats why we use trim.
var response_msg = response.message;
if(response_msg.trim() == "success"){
//do this
}else{
//do this
}
This was the whole scenario i faced. If i am wrong, please correct me.
I am currently using this php form to submit into our mySQL database with a "chip_number" and "order_number" also with a date and time stamp. We want to use this with no keyboard or mouse, just a scanner. Currently it tabs the first field and when the second field is scanned the form is submitted, which is working as intended but it completely starts the form over, i would like it to keep the first field (order_number) after submitting so we can scan multiple "chip_numbers" on the same "order_number" then have a Master submit button if you will to send it all through when the employee is done with that order number and start with a blank form. This is the script i am using. thanks to all in advance!
<!-- Insert -->
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MICROCHIP_TBL (chip_number,order_number)
VALUES
('$_POST[chip_number]','$_POST[order_number]')";
IF (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: TRY AGAIN HUMAN!";
}
mysqli_close($conn);
?>
<html>
<head>
<!-- Validate form function -->
<!--<script type="text/javascript">
// function validateForm()
// {
// var x=document.forms["chip_insert"]["order_number"].value;
// var y=document.forms["chip_insert"]["chip_number"].value;
// if (x==null || x=="")
// {
// alert("Please enter an Order Number.");
// document.forms["chip_insert"]["order_number"].focus();
// return false;
// }
// if (y==null || y=="")
// {
// alert("Please enter a Microchip Number.");
// document.forms["chip_insert"]["chip_number"].focus();
// return false;
// }
// }
</script>
-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
</script>
</head>
<body onLoad="document.chip_insert.order_number.focus();">
<center>
<h1>Jeffers HomeAgain Microchip Entry</h1>
<form name="chip_insert" id="chip_insert" action="<?php echo $PHP_SELF;?>" onsubmit="return validateForm()" method="post">
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
Tag Number: <input tabindex="2" maxlength="15" type="text" name="chip_number" id="chip_number" required="required" /><br /><br />
<input tabindex="7" type="submit" />
</center>
</form>
header('Location: http://JVSIntranet/microchip/homeagain.php');
This code redirects back to the form, I guess. You should add the ordernumber so it can be picked up by the form.
$ordernr = $_POST['order_number'];
header("Location: http://JVSIntranet/microchip/homeagain.php?order_number=$ordernr"); //mark the double quotes
in your form code you will have to use something like
<?php $value = (isset($_GET['order_number'])) ? " value=$_GET['order_number'] " : ""; ?>
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" <?php echo $value; ?> required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
I finally got it. i had to take out the Return function from my form and i added this to my script:
$value = "";
if( isset( $_POST ["order_number"] )) $value = $_POST ["order_number"];
then i put this in my input line and it works fine:
value="<?php echo $value; ?>"
This is my code to connect a page to a database (MySQL):
<html>
<body>
<title>Home</title>
<script language="javascript">
function checkTextField(field) {
if (field.value == '') {
alert("Field is empty");
}
}
function a(id) {
var ay = document.getElementById(id).value;
var pattern = /\d{4}-\d{2,4}/;
if(pattern.test(ay))
{
ay.style.backgroundColor="#52F40C";
return true;
}
else
{
window.alert ("Enter in YYYY-YY or YYYY-YYYY format");
ay.style.backgroundColor="red";
ay.focus();
ay.value="";
return false;
}
}
function c()
{
var n=document.getElementById("name");
var re=/^[a-zA-Z]+ ?[a-zA-Z]*$/;
if(re.test(n.value))
{
n.style.backgroundColor="#52F40C";
}
else
{
window.alert("Invalid place name");
n.style.backgroundColor="#F40C0C";
n.focus();
n.value="";
}
}
function d()
{
var n= document.getElementById("date");
var re=/^(?:(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2})$/;
if (re.test(n.value))
{
n.style.backgroundColor="#52F40C";
}
else
{
window.alert("enter in MM DD YYYY format");
n.style.backgroundColor="#F40C0C";
n.focus();
n.value="";
}
}
</script>
<body style="background-color:#708090;">
<?php
if (isset($_POST['submit']))
{
$mysqli= new mysqli("localhost","admin","admin", "nba" );
if($mysqli === false)
{
die("could not connect:" . mysqli_connect_error());
}
if ($inputError != true && empty($_POST['ayear']) )
{
echo 'ERROR: Please enter a valid year';
$inputError = true;
}
else
{
$ayear = $mysqli-> escape_string($_POST['ayear']);
}
if ($inputError != true && empty($_POST['fyear']) )
{
echo 'ERROR: Please enter a valid year';
$inputError = true;
}
else
{
$fyear = $mysqli-> escape_string($_POST['fyear']);
}
if ($inputError != true)
{
$sql="INSERT INTO year VALUES ('$ayear','$fyear')";
if ($mysqli-> query($sql)==true)
{
echo'Added';
}
else
{
echo"ERROR: Could not execute query : $sql. " . $mysqli-> error;
}
}
$mysqli-> close();
}
?>
<h1 style="font-family:Verdana;text-align:center;">National Board of Accrediation <br>of<br> Programme</h1>
<br>
<div id="menu" style="background-color:#800000;height:25px;width:1000px">
<b><font "style="font-family:Verdana">Part I               Part II               Part III               Part IV</font></b>
</div>
</p>
<h4 style="font-family:Verdana;text-align:center;"><b><u>Declaration</u></b></h4>
<form method="post" action="home.html">
<p> (<input type="text" size="9" name="ayear" id="ayear" onChange="a('ayear');" onBlur="checkTextField(this);">) (<input type="text" size="9" name="fyear" id="fyear" onChange="a('fyear');" onBlur="checkTextField(this);">).</p>
<p>Place:<input type="text" size="20" name="name" id="name" onChange="c();" onBlur="checkTextField(this);"></p>
<p>Date:<input type="text" size="10" name="date" id="date" onChange="d();" onBlur="checkTextField(this);">
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
The database connection is not working. How can I fix this? What is the problem with the code?
Unless you've set HTML to be executed like PHP code, none of your dynamic code will work.
Save a copy of that file with a .php extension and test if it works.
Change your file Extension to .php
And furthermore on your Form Action include a PHP extetention. like below
<form method="post" action="home.php">
Besides the other suggestions, I see that you have put a 'space' after -> on several locations;
e.g.
$mysqli-> escape_string($_POST['ayear']);
Should be
$mysqli->escape_string($_POST['ayear']);
Why you are trying to execute your php code in HTMl
Save your file wth .php extension definitely it will work.
I want to check if a user exists in DB, and if exist display some error without reload the page (modify a div). Any idea what is wrong in this code? Or any other idea how to do it? Thank you
HTML:
<div style="width:510px; height:500px;">
<div class="message">
<div id="alert"></div>
</div>
<form id="signup_form" method="post" action="register.php">
<label class="label">username</label>
<p><input class="signup_form" type="text" name="username"></p>
<label class="label">parola</label>
<p><input class="signup_form" type="text" name="password"></p>
<label class="label">name</label>
<p><input class="signup_form" type="text" name="name"></p>
<label class="label">telefon</label>
<p><input class="signup_form" type="text" name="phone"></p>
<label class="label">email</label>
<p><input class="signup_form" type="text" name="email"></p>
<p><input class="signup_button" type="submit" value="inregistrare">
</form>
<div class="clear"></div>
</div>
register.php
<?php
include "base.php";
$usertaken = '<li class="error">username used</li><br />';
$alert = '';
$pass = 0;
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$name = mysql_real_escape_string($_POST['username']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);
$checkusername = mysql_query("SELECT * FROM details WHERE user = '".$username."'");
if(mysql_num_rows($checkusername) == 1)
{
$pass = 1;
$alert .="<li>" . $usertaken . "</li>";
}
else
{
$registerquery = mysql_query("INSERT INTO details (user, pass, name, phone, email) VALUES('".$username."', '".$password."','".$name."','".$phone."', '".$email."')");
if($registerquery)
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
}
if($pass == 1) {
echo '<script>$(".message").hide("").show(""); </script>';
echo "<ul>";
echo $alert;
echo "</ul>";
}
}
?>
SOLUTION (add this in head and hide .message div)
<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#alert',
beforeSubmit: showRequest,
success: showResponse
};
$('#signup_form').ajaxForm(options);
});
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
return true;
}
function showResponse(responseText, statusText) {
}
$.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
</script>
You need to use AJAX to do a dynamic page update.
Take a look here: http://api.jquery.com/jQuery.ajax/ for how to do it with jQuery.
Your current code uses a form submit, which always reloads the page.
You need to use ajax. Write something like this as a JavaScript:
var xmlHttp;
function checkUser(user) {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request.");
return;
}
var url = "check.php"; //This is where your dynamic PHP file goes
url = url + "?u=" + user;
url = url + "&sid=" + Math.random();
xmlHttp.onreadystatechange = getData;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function getData () {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
if (xmlHttp.responseText == 1) {
alert('Username free'); //action if username free
} else {
alert('This username is taken'); //action if its not
}
}
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
//Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
And in your check.php file, just check against your database if the username is taken or not, if not and simply echo('1') if its free, else echo('0') o whatever you want. that single number will be handled as the xmlHttp.responseText. you can also do something fancy instead of the alerts, like an image. also you need to run the check() fumction either when the user is typing, or when the form is submitted, with the username form field as a parameter. Hope this helps.
EDIT: Oh, also I forgot that in the check.php file, the $_GET['u'] variable contains the the entered username. Check that against the database.
If that's all in a single page, you'll have to structure it like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do form retrieval/database stuff here ...
if (error) {
$message = 'Something dun gone boom';
}
}
if ($message != '') {
echo $message;
}
?>
form stuff goes here
i have a simple form to validate if an user exists in the db, and permit the login to another page (yes i remove the password validation to simplify the code, and i test without pass and the script always show Your login is not valid).
Database: emprego, table: users, fields: id, username, email, pass
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#login_form").submit(function () {
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
$.post("ajax_login.php", {
name: $('#name').val(),
}, function (data) {
if (data == 'yes') {
$("#msgbox").fadeTo(200, 0.1, function () {
$(this).html('Logging in.....').addClass('messageboxok').fadeTo(900, 1, function () {
document.location = 'secure.php';
});
});
} else {
$("#msgbox").fadeTo(200, 0.1, function () {
$(this).html('Your login is not valid').addClass('messageboxerror').fadeTo(900, 1);
});
}
});
return false;
});
});
</script>
</head>
<body>
<form method="post" action="" id="login_form">
User Name : <input name="name" type="text" id="name">
<div class="buttondiv">
<input name="Submit" type="submit" id="submit" value="Login" style="margin-left:-10px; height:23px">
<span id="msgbox" style="display:none"></span>
</div>
</form>
file: ajax_login.php
<?php
include("includes/f_banco.php");
conecta ();
$check = mysql_query("SELECT username FROM users WHERE username ='".mysql_real_escape_string($_POST['name'])."'")or die(mysql_error());
$row=mysql_fetch_array($check);
if ($row['username'] == $_POST['name']) {
echo "yes";
$_SESSION['name']=$row['username'];
}else{echo "no";}
?>
EDIT: updated code
what is the possible cause?
i see lots of problems
<?php
//removed the # from the post
$name = mysql_real_escape_string($_POST['name']);
//whys this here?
$row=mysql_fetch_array($check);
//name cant be used (common mistake)
$check = mysql_query("SELECT name FROM users WHERE name ='".$name."'")or die(mysql_error());
$check2 = mysql_num_rows($check);
if ($check2 == 1) {
echo "yes";
$_SESSION['name']=$name;
}
else
echo "no";
?>
try something like this
<?php
session_start();
include("includes/f_banco.php");
conecta ();
if(isset($_SESSION['name'])){echo "yes";}else{
$check = mysql_query("SELECT username FROM users WHERE username ='".mysql_real_escape_string($_POST['name'])."' LIMIT 1")or die(mysql_error());
$row=mysql_fetch_array($check);
if ($row['username'] == $_POST['name']) {
echo "yes";
$_SESSION['name']=$row['username'];
}else{echo "no";}
}
?>
Perhaps the use of the field name "name"? See jQuery issue with live click and input named "name"