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.
Related
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
Firstly I have searched previous answers and (as far as I'm aware) none of the answers seemed to fit my question - though I'm sure it's been answered somewhere in the past - so forgive me.
I have 3 pages, which work together to submit a HTML form and save it in a MySQL database.
The pages are as follows;
idea.php (contains the form, includes the below idea_js.js file in a <script></script> tag).
idea_js.js (checks the submitted form for errors and submits via ajaxSubmit to ideaSubmit.php)
ideaSubmit.php (assigns POST'd variables and submits to database.)
My problem is that when the form is submitted, ideaSubmit recieves no POST'd variables.
I've come to this conclusion with a check;
if (!empty($_POST)){
echo "empty!"; }
and my page loads (with a bunch of unassigned variable errors and the message);
empty!
Can you fill me in as to why this is happening? Included are the three files.
idea.php:
<script type="text/javascript" src="js/jquery-2.1.0.js"></script>
<script type="text/javascript" src="js/idea_js.js"></script>
<!DOCTYPE html>
<html>
<head>
<?php include 'headIncludes.php'; ?>
</head>
<body>
<?php include 'includes/userInterface.php'; ?>
<div id="mainContent">
<div class="mainContentContainer">
<div id="home" >
<section id="content-wrapper">
<br>
<br>
<form id="submit_idea" action ="submitIdea.php" method="POST">
<fieldset>
<legend>Idea submission</legend>
<label for="title">Title</label>
<input type="text" name="title"/>
<br>
<label for="brief">Brief</label>
<input type="text" name="brief"/>
<br>
<label for="problem">Problem</label>
<input type="text" name="problem"/>
<br>
<label for="solution">solution</label>
<input type="text" name="solution"/>
<br>
<label for="audience">audience</label>
<input type="text" name="audience"/>
<br>
<label for="prediction">prediction</label>
<input type="text" name="prediction"/>
<br>
<label for="constraints">constraints</label>
<input type="text" name="constraints"/><br>
<button type="submit" onclick="processIdea();">Submit</button>
<div style="clear:both;"></div>
</fieldset>
</form>
</section>
</div>
</div>
</div>
</body>
</html>
idea_js.js;
$("document").ready(function() {
$("#submit_idea").submit(function() {
processIdea();
return false;
});
});
function processIdea() {
var errors = '';
// Validate title
var title = $("#submit_idea [name='title']").val();
if (!title) {
errors += ' - Please enter a title\n';
}
// Validate brief
var brief = $("#submit_idea [name='brief']").val();
if (!brief) {
errors += ' - Please enter a short idea brief\n';
}
// Validate Problem
var problem = $("#submit_idea [name='problem']").val();
if (!problem) {
errors += ' - Please discribe the problem you want to solve\n';
}
//Validate Solution
var solution = $("#submit_idea [name='solution']").val();
if (!solution) {
errors += ' - Please discribe your solution to the above problem\n';
}
//Validate Audience
var audience = $("#submit_idea [name='audience']").val();
if (!audience) {
errors += ' - Please discribe the audience your solution targets\n';
}
//Validate Prediction
var prediction = $("#submit_idea [name='prediction']").val();
if (!prediction) {
errors += ' - Please discribe the prediction you want to solve\n';
}
//Validate constraints
var constraints = $("#submit_idea [name='constraints']").val();
if (!constraints) {
errors += ' - Please discribe the constraints of your solution\n';
}
if (errors){
errors = 'The following errors occurred:\n' + errors;
alert(errors);
return false;
} else {
// Submit our form via Ajax and then reset the form
$("#submit_idea").ajaxSubmit({success:showResult});
return false;
}
}
function showResult(data) {
if (data == 'save_failed') {
alert('Form save failed, please contact your administrator');
return false;
} else {
$("#submit_idea").clearForm().clearFields().resetForm();
alert('Form save success');
return false;
}
}
submitIdea.php;
<?php
//Starts session
include_once '/includes/db_connect.php';
include_once '/includes/functions.php';
sec_session_start();
if(login_check($mysqli) == true) {
// Retrieve form data
if (!empty($_POST)){
echo "empty!"; }
if(isset($_POST['submit_idea'])){
if(isset($_POST['title'])){ $title = $_POST['title']; }
if(isset($_POST['brief'])){ $brief = $_POST['brief']; }
if(isset($_POST['problem'])){ $problem = $_POST['problem']; }
if(isset($_POST['solution'])){ $solution = $_POST['solution']; }
if(isset($_POST['audience'])){ $audience = $_POST['audience']; }
if(isset($_POST['prediction'])){ $prediction = $_POST['prediction']; }
if(isset($_POST['constraints'])){ $constraints = $_POST['constraints']; }
if (!$title || !$brief || !$problem || !$solution || !$audience || !$prediction || !$constraints) {
echo "save_failed";
return;
}
// Clean variables before performing insert
$clean_title = mysql_real_escape_string($title);
$clean_brief = mysql_real_escape_string($brief);
$clean_problem = mysql_real_escape_string($problem);
$clean_solution = mysql_real_escape_string($solution);
$clean_audience = mysql_real_escape_string($audience);
$clean_prediction = mysql_real_escape_string($prediction);
$clean_constraints = mysql_real_escape_string($constraints);
// $clean_categories_list = mysql_real_escape_string($categories_list);
}
else {
// Perform insert
$now = time();
$user_id = $_SESSION['user_id'];
$mysqli->query("INSERT INTO idea_thread (user_id, time, title, Brief, problem, solution, audience, prediction, constraints) VALUES ('{$user_id}', '{$now}', '{$clean_title}', '{$clean_brief}', '{$clean_problem}', '{$clean_solution}', '{$clean_audience}', '{$clean_prediction}', '{$clean_constraints}')");
// if (#mysql_query($sql, $link)) {
echo "success";
}
// return;
//} else {
// echo "save_failed";
// return;
//}
} else {
echo "How did you get here? Please log in first!";
header("Location: ../signup.php");
exit;
}
?>
Thanks, all help appreciated!
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.
Can someone please take a look at these, it just is not happing for me its a html form, a php file to process it and a javascript file, errors in the from browser show things like U+12AF phantom illegal characters in the JScript file, been going at it for 1.5 hours and am at my wits end.
--submit.js--
$(document).ready(function() {
$(function() {
$('#paycheck').bind('submit', function() {
$.post('Paycheck.php', $("#paycheck").serialize(), function(data) {
$('#result').html(data);
});
});
});
});
--Paycheck.html--
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<pre><title>Weekly Gross Paycheck Calculator</title></pre>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="submit.js"></script>
</head>
<body>
<h2 style = "text-align:center">PayCheck</h2>
<form name="paycheck" id="paycheck" action="" method="POST">
<p>Number of Hours: <input type="text" name="numHours"/></p>
<p>Hourly Wage $<input type="text" name="hourlyWage"/></p>
<p><input type="reset" value="Clear Form" />
<input type="submit" name="submit" value="Send Form" /></p>
</form>
<!-- Form and javascript will output the results here -->
<div id="result"></div>
</body>
</html>
--Paycheck.php--
<?php
function validateInput($data, $fieldName){
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field.<br/>\n";
++$errorCount;
$retval = "";
} else { // Only clean up the input if it isn't empty
if (!is_numeric($data)){
echo "\"$fieldName\" must be numeric.<br/>\n";
++$errorCount;
$retval = "";
}else{
$retval = trim($data);
$retval = stripslashes($retval);
}
return($retval);
} // end validateInput()
}
$ShowForm = TRUE;
$errorCount = 0;
$numHours = "";
$hourlyWage = "";
$wage = "";
if (isset($_POST['Submit'])) {
$numHours = validateInput($_POST['numHours'],"Number of Hours");
$hourlyWage = validateInput($_POST['hourlyWage'],"Hourly Wage");
if ($errorCount==0)
$ShowForm = FALSE;
else
$ShowForm = TRUE;
}
echo $numHours ." " . $hourlyWage;
if ($ShowForm == TRUE) {
if ($errorCount > 0)// if there were errors
print "<p>Please re-enter the form information below.</p>\n";
} else {
//If hours are over 40 then use time and a half
if($numHours > 40) { $wage = ((($numHours - 40) * 1.5) * $hourlyWage) + ($hourlyWage * 40); }
//otherwise use normal multiplication.
else { $wage = $numHours * $hourlyWage; }
print "<p>Your weekly gross salary is $". $wage . ".</p>\n";
}
?>
A few things:
You have an extra nested lambda function in your js which is not required.
$(document).ready($(function() {
$('#paycheck').bind('submit', function() {
$.post('Paycheck.php', $("#paycheck").serialize(), function(data) {
$('#result').html(data);
});
});
});
There is no action on your form, change to action="Payment.php"
Also in the php script line 27 should be if (isset($_POST['submit'])) { (with a lower case s in submit).
After these changes everything seems to work as intended.
Are you sure about the last line in your php script? I mean, shouldn't the dollar sign be escaped like in:
print "<p>Your weekly gross salary is \$". $wage . ".</p>\n";
Comments are right btw:
1)
$(document).ready(function() {
// don't double wrap
$('#paycheck').bind('submit', function() {
$.post('Paycheck.php', $("#paycheck").serialize(), function(data) {
$('#result').html(data);
});
});
});
2)
<head>
<title>Weekly Gross Paycheck Calculator</title>
<!-- no pre tags -->
<script type=...
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