So I am doing a homework, in which I would like to check the username in real time, as the user types it.
It is working correctly, only when I change the content of the HTML element to "username available or not", it also displays the whole site one again there, but much smaller.
So actually in the cell ehere I want to display "available" or "not available" the whole page appears again. The proble must be the SUCCESS part of the $.ajax function, but I can not see why.
Please help me :)
Here are the codes:
Register.php:
<?php
define("HOSTNAME","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("DATABASE","authentication");
//connect database
$conn = new mysqli(HOSTNAME,USERNAME,PASSWORD,DATABASE);
if($conn->connect_error){
die("Connection failed: " .$conn->connect_error);
}
if(isset($_POST['register_btn'])){
session_start();
$username = $conn->real_escape_string($_POST['username']);
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
$password2 = $conn->real_escape_string($_POST['password2']);
if($password == $password2 && strlen($password) > 5 && strlen($username) > 5 && strlen($email) > 5){
//create user
$password = md5($password); //hash password before storing for security purposes
$sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
if($conn->query($sql)){
echo "New record created successfully";
$_SESSION['message'] = "You are now logged in";
$_SESSION['username'] = $username;
header("location: home.php"); //redirect to home page
}
else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else{
//failed
$_SESSION['message'] = "The two passwords do not match";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<svg viewBox="0 0 500 37">
<path id="curve" d="M 105 33 q 150 -20 300 0" />
<text width="500">
<textPath xlink:href="#curve">az én oldalam lesz</textPath>
</text>
</svg>
<div class="header">
<h1>Register</h1>
</div>
<script type="text/javascript">
function checkUserRealTime(val){
$.ajax({
type:"POST", //type of the request to make
url:"checkUserRealTimeEx.php", //server the request should be sent
data:"username="+val, //the data to send to the server
success: function(data){ //the function to be called if the request succeeds
$("#msg").html(data);
}
});
}
</script>
<form method="post" action="register.php">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" class="textInput" placeholder="username" onkeyup="checkUserRealTime(this.value)"></td>
</tr>
<tr>
<td></td>
<td><p id="msg"></p></td>
<tr>
<td>Email:</td>
<td><input type="email" name="email" placeholder="E-mail address" class="textInput"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" placeholder="Password" class="textInput"></td>
</tr>
<tr>
<td>Password again:</td>
<td><input type="password" name="password2" placeholder="Password again" class="textInput"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="register_btn" class="Register"></td>
</tr>
</table>
</form>
</body>
</html>
checkUserRealTimeEx.php:
<?php
require "register.php";
$username = $conn->real_escape_string($_POST["username"]);
$query = "SELECT * FROM users WHERE username='".$username."'";
$results = $conn->query($query);
$numRows = $results->num_rows;
if($numRows > 0){
echo "Username not available";
}
else{
echo "Username available";
}
?>
So as I said I am pretty sure the proble will be with the data as input value in the success part, but I don't really understand where I pass the value back to the register.php and what value data gets and where it gets from :/ If you could also explain that part to me, I would be very-very thankful :)
The issue is that the form on register.php submits to the register.php, which contains both the registration form and the logic to process the form. When you submit a form to a page (which is what you are doing here), the HTML of that page will be displayed unless you tell it to do otherwise. The cleanest way to handle this would be to have a separate page to handle the registration (as suggested by gibberish in his answer).
However, you could still have the form submit to itself as long as you hide the HTML content when registration has occurred and show some feedback instead (e.g. "Registration successsful!"). The PHP code at the top of register.php knows whether or not the form was submitted and whether or not the registration was successful. You can leverage that by setting a variable when the registration was successful (e.g. $registered=true) and use that variable to decide whether you want to display the registration form or a success message. Again, this isn't as 'clean' as two separate pages, but it is a quick workaround to solve your issue.
This updated version of register.php does what I am describing:
<?php
define("HOSTNAME","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("DATABASE","authentication");
$registered = false;
$username = '';
//connect database
$conn = new mysqli(HOSTNAME,USERNAME,PASSWORD,DATABASE);
if($conn->connect_error){
die("Connection failed: " .$conn->connect_error);
}
if(isset($_POST['register_btn'])){
session_start();
$username = $conn->real_escape_string($_POST['username']);
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
$password2 = $conn->real_escape_string($_POST['password2']);
if($password == $password2 && strlen($password) > 5 && strlen($username) > 5 && strlen($email) > 5){
//create user
$password = md5($password); //hash password before storing for security purposes
$sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
if($conn->query($sql)){
echo "New record created successfully";
$_SESSION['message'] = "You are now logged in";
$_SESSION['username'] = $username;
header("location: home.php"); //redirect to home page
$registered = true; // Set the flag indicating that registration was successful
}
else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else{
//failed
$_SESSION['message'] = "The two passwords do not match";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<svg viewBox="0 0 500 37">
<path id="curve" d="M 105 33 q 150 -20 300 0" />
<text width="500">
<textPath xlink:href="#curve">az én oldalam lesz</textPath>
</text>
</svg>
<div class="header">
<h1>Register</h1>
</div>
<script type="text/javascript">
function checkUserRealTime(val){
$.ajax({
type:"POST", //type of the request to make
url:"checkUserRealTimeEx.php", //server the request should be sent
data:"username="+val, //the data to send to the server
success: function(data){ //the function to be called if the request succeeds
$("#msg").html(data);
}
});
}
</script>
<?php
if (!$registered) {
?>
<form method="post" action="register.php">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" class="textInput" placeholder="username" onkeyup="checkUserRealTime(this.value)"></td>
</tr>
<tr>
<td></td>
<td><p id="msg"></p></td>
<tr>
<td>Email:</td>
<td><input type="email" name="email" placeholder="E-mail address" class="textInput"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" placeholder="Password" class="textInput"></td>
</tr>
<tr>
<td>Password again:</td>
<td><input type="password" name="password2" placeholder="Password again" class="textInput"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="register_btn" class="Register"></td>
</tr>
</table>
</form>
<?php
} else {
?>
<div>Registration Successful for user <?= $username ?></div>
<?php
}
?>
</body>
</html>
You cannot use the same document as the receiver for your ajax code. You must have a separate document.
(See this other answer)[values not updated after an ajax response
Related
I have this code for change password on the personal page of the user on my website. The script working but the problem is that work's only on id "60". how I can take the id from the page and set in this code? my page is like this "www.example.com/area-personale.php?id=60". and why the script start immediately when I enter on the page and i prefer that it starts when I press on submit.
</script>
</head>
<body>
<form name="frmChange" method="post" action=""
onSubmit="return validatePassword()">
<div style="width: 500px;">
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<table border="0" cellpadding="10" cellspacing="0"
width="500" align="center" class="tblSaveForm">
<tr class="tableheader">
<td colspan="2">Change Password</td>
</tr>
<tr>
<td width="40%"><label>Current Password</label></td>
<td width="60%"><input type="password"
name="currentPassword" class="txtField" /><span
id="currentPassword" class="required"></span></td>
</tr>
<tr>
<td><label>New Password</label></td>
<td><input type="password" name="newPassword"
class="txtField" /><span id="newPassword"
class="required"></span></td>
</tr>
<td><label>Confirm Password</label></td>
<td><input type="password" name="confirmPassword"
class="txtField" /><span id="confirmPassword"
class="required"></span></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit"
value="Submit" class="btnSubmit"></td>
</tr>
</table>
</div>
</form>
</body>
</html>
<?php
session_start();
$_SESSION["id_user"] = "60";
$conn = mysqli_connect("x", "x", "x", "x") or die("Connection Error: " . mysqli_error($conn));
?>
<?php
if (count($_POST) > 0) {
$result = mysqli_query($conn, "SELECT password FROM vm_users WHERE id_user='" . $_SESSION["id_user"] . "'");
$row = mysqli_fetch_array($result);
if ($_POST["currentPassword"] == $row["password"]) {
mysqli_query($conn, "UPDATE vm_users set password='" . $_POST["newPassword"] . "' WHERE id_user='" . $_SESSION["id_user"] . "'");
$message = "Password modificata";
} else
$message = "Current Password is not correct";
}
?>
<html>
<head>
<title>Change Password</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script>
function validatePassword() {
var currentPassword,newPassword,confirmPassword,output = true;
currentPassword = document.frmChange.currentPassword;
newPassword = document.frmChange.newPassword;
confirmPassword = document.frmChange.confirmPassword;
if(!currentPassword.value) {
currentPassword.focus();
document.getElementById("currentPassword").innerHTML = "required";
output = false;
}
else if(!newPassword.value) {
newPassword.focus();
document.getElementById("newPassword").innerHTML = "required";
output = false;
}
else if(!confirmPassword.value) {
confirmPassword.focus();
document.getElementById("confirmPassword").innerHTML = "required";
output = false;
}
if(newPassword.value != confirmPassword.value) {
newPassword.value="";
confirmPassword.value="";
newPassword.focus();
document.getElementById("confirmPassword").innerHTML = "not same";
output = false;
}
return output;
}
I used this and now works!
$_SESSION["id_user"] = $_GET["id"]
I have to display the all the records on the screen which are inserted into the database without refreshing the page. I have 3 columns called as Firstname, Lastname, Email and after clicking on the submit button data are inserting in the database using ajax Which is working.
Now I am fetching the records on the same screen without refresh the page but it is not working when I am refreshing the page then it is displaying the last record which is inserted.
Please check below link. You will get an idea what I am asking. Inserted data and display data at the same time.
http://prntscr.com/g953bs
Index.php
<?php
ob_start();
session_start();
include('../../db/connection.php');
$sql = "SELECT * FROM test1";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" id="register" autocomplete="off">
<input type="text" name="fname" id="fname" placeholder="Firstname">
<input type="text" name="lname" id="lname" placeholder="Lastname">
<input type="email" name="email" id="email" placeholder="Email">
<input type="submit" name="submit" value="submit" >
</form>
<table border="1" style="margin-top: 25px;">
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row['id']."</td>
<td>".$row['fname']."</td>
<td>".$row['lname']."</td>
<td>".$row['email']."</td>
</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('#register').submit(function(e){
e.preventDefault(); // Prevent Default Submission
var fname = $("#fname").val();
var lname = $("#lname").val();
var email = $("#email").val();
var dataString = 'fname='+ fname + '&lname='+ lname + '&email='+ email;
$.ajax(
{
url:'process.php',
type:'POST',
data:dataString,
success:function(data)
{
// $("#table-container").html(data);
$("#register")[0].reset();
},
});
});
</script>
</body>
</html>
Process.php
$firstname=$_POST['fname'];
$lastname=$_POST['lname'];
$email=$_POST['email'];
$sql = "INSERT INTO test1 (fname, lname, email) VALUES ('$firstname', '$lastname', '$email')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
$conn->close();
$('#IdTable tr:last').after('<tr><td>id<td>fname<td>lname<td>email</tr>');
Define id to the table
<table border="1" style="margin-top: 25px;" id="myTable">
Changes in ajax call
$.ajax(
{
url:'process.php',
type:'POST',
data:dataString,
success:function(data)
{
$('#myTable tr:last').after('<tr><td>' +fname +'</td><td>'+lname+'</td><td>'+email+'</td></tr>');
$("#register")[0].reset();
},
});
Note: Also you should handle the case if eror while inserting in your code as currently you are only taking positive case.
I hope this will help
First of all I'd like to suggest taking a look at binding parameters with mysqli to make your query saver.
Then in order to add the date without refreshing you could return the data on successful insert. Then append this data to the table.
Example Process.php
if (mysqli_query($conn, $sql)) {
echo "<tr>
<td>".mysqli_insert_id($conn)."</td>
<td>".$firstname."</td>
<td>".$lastname."</td>
<td>".$email."</td>
</tr>";
} else {
As you have only one table then use below code.
$('table tr:last').after('<tr>...</tr><tr>...</tr>');
If you have any class or id then you can modify below syntax as $('selector tr:last')
Use it in success of ajax call
im having problem with the integration of text fields with php by $_post method and i've done almost complete code but it giving me boolean error in line 84 which is
if(mysqli_num_rows ||($run)==0)
and my whole code is
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<h1 align="center">Registration form</h1>
<form action="registration.php" method="post">
<table align="center" border="2">
<tr>
<td>User name</td> <td><input type="text" placeholder="username" name="name" /></td>
</tr>
<tr>
<td>Password</td> <td><input type="password" placeholder="password" name="password" /></td>
</tr>
<tr>
<td>Email</td> <td><input type="email" placeholder="email" name="email" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="submit" name="submit" /></td>
</tr>
</table>
</form>
</body>
</html>
<?php
//connection to database
$servername = "localhost";
$db_username = "user_db_users";
$db_password = "123456789";
$db_name = "users_db";
$conn = new mysqli($servername, $db_username, $db_password, $db_name);
//fatching data from form
if(isset($_POST['submit'])){
$user_name = $_POST['name'];
$user_pass = $_POST['password'];
$user_email = $_POST['email'];
//validatio form
if($user_name==''){
echo "<script>alert('please enter usernmae')</script>";
exit();
}
if($user_pass==''){
echo "<script>alert('please enter password')</script>";
exit();
}
if($user_email==''){
echo "<script>alert('please enter email')</script>";
exit();
}
$check_email = "select * from users where user_email='$user_email'";
$run = mysql_query($check_email);
if(mysqli_num_rows ||($run)==0){
echo "<script>alert('Email $check_email is already exist')</script>";
exit();
}
//Getting values from fields of registration form
$query = "insert into users(user_name, user_pass, user_email) values($user_name, $user_pass, $user_email)";
if(mysql_query($query)){
echo "<script>alert('registration successful')</script>";
}
}
?>
The function mysqli_num_rows() need a mysqli_result parameter and if you want the logic to work correctly the test is actually wrong as well
So change
if(mysqli_num_rows ||($run)==0){
To
if(mysqli_num_rows($run) > 0) {
This query will also fail
$query = "insert into users(user_name, user_pass, user_email)
values($user_name, $user_pass, $user_email)";
All text column variables should be wrapped in quotes like this
$query = "insert into users(user_name, user_pass, user_email)
values('$user_name', '$user_pass', '$user_email')";
But I have to mention that Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements
I have three files, index.html, database.php, and function.js. In my database.php, I have created a form with a delete button to execute the delete sql query on click. My main purpose is to display a table with records displayed and a delete button on each so that whenever I click the delete button, it executes the SQL query and removes that particular row from the database.
It works fine before I added in ajax into the javascript. Now when delete button is clicked, the whole page just refreshes.
How do I execute the delete query on the delete button click using a javascript function that I want to call in my php file without creating/using new files?
I am using vi editor to code so I do not have any means of debugging except IE's developer tools. My javascript file doesn't seem to be working because in the HTML file the form returns a null at
onsubmit="return checkFields()";
as stated from the error I received, but it's probably just because there are errors in my javascript file.
P.S. I am new to PHP, javascript, and ajax so do pardon me if I make any careless or obvious mistakes. I also do not know any jQuery or JSON. Any form of help in the simplest explanation would be greatly appreciated.
Here is the index.html file:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="function.js" type="text/javascript"></script>
</head>
<body>
<form name="infoForm" method="post" onsubmit="return checkFields()" action="">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" maxlength="40"></td>
</tr>
<tr>
<td>Address:</td>
<td><textarea maxlength="45" name="address"id="address" ></textarea></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="phone" id="phone" maxlength="20"><br></td>
</tr>
<tr>
<td>Gender:</td>
<td><input checked type="radio" name="gender" id="male" value="Male">Male
<input type="radio" name="gender" id="female" value="Female">Female</td>
</tr>
<tr>
<td>
Nationality:
</td>
<td>
<select name="nation">
<option value="Singapore">Singapore</option>
<option value="Malaysia">Malaysia</option>
<option value="Thailand">Thailand</option>
<option value="Indoensia">Indonesia</option>
<option value="Philippines">Philippines</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<br><input type="reset" value="Cancel">
<input type="submit" name="result" value="Submit"/>
</td>
</tr>
</table>
</form>
<div id="divTable"></div>
</body>
</html>
Here is the database.php file:
<?php
// Define database parameters //
DEFINE ('DB_USER' ,'iqwe');
DEFINE ('DB_PASSWORD', 'inqwe123');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'hqwdqq');
$table_info = "info";
// Connect to database
$conn = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to Database:'. mysql_error());
#mysql_select_db (DB_NAME) OR die ('Could not select the Database: '.mysql_error());
// Delete Row
if(isset($_POST['delete'])){//java script function somewhere
echo "<script>";
echo "deleteRow()";
echo "</script>";
}
//Check if phone no. is duplicate and if not, insert data
if(isset($_POST['result'])){
$phone = $_POST['phone'];
$query_string = "select phone from $table_info where phone='$phone'";
$result = #mysql_query($query_string);
$num_row = mysql_num_rows($result);
if($num_row){
echo "A same phone number has been found. Please enter a different phone number.";
}else{
$query_string = "insert into $table_info(name, address, phone, gender, nation) values('".$_POST['name']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['gender']."','".$_POST['nation']."')";
$result = #mysql_query($query_string);
}
}
// Display table
$query_string = "select * from $table_info";
$result = #mysql_query($query_string);
$num_row = mysql_num_rows($result);
if($num_row){
echo "<table border=1>";
echo "<tr><th>Name</th><th>Address</th><th>Phone no.</th><th>Gender</th><th>Nationality</th><th>Created</th><th>Modified</th><th>Action</th></tr>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>", $row['name'], "</td>";
echo "<td>", $row['address'], "</td>";
echo "<td>", $row['phone'], "</td>";
echo "<td>", $row['gender'], "</td>";
echo "<td>", $row['nation'], "</td>";
echo "<td>", $row['createdTime'], "</td>";
echo "<td>", $row['modifiedTime'], "</td>";
?>
<!--Delete button-->
<td><form id="delete" method="post" action="">
<input type="hidden" name="deleteRow" value="<?php echo $row['user_id']; ?>"/>
<input type="button" name="delete" value="Delete" onclick="return deleteRow(<?php echo $row['user_id']; ?>);"/></td></form></tr>
<?php
}
echo "</table>";
}
else{
echo "0 results";
}
?>
<form method="post" action="index.html">
<input type="submit" name="goBack" value="Back"/>
</form>
And here is the function.js file:
function checkFields(){
var name = document.getElementById("name");
var address = document.getElementById("address");
var phone = document.getElementById("Phone");
if(confirm('Do you want to submit')){
if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
alert("Please fill in all your details.");
return false;
}
else{
var page = "database.php";
var xmlhttp = new XMLHttpRequest();
if(xmlhttp==null){
alert("Your browser does not support AJAX!");
return false;
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", page, true);
xmlhttp.send(null);
return false;
}
}
else{
return false;
}
}
function deleteRow(id){
if(confirm("Are you sure you want to delete this contact?")){
//$id = $_POST['user_id'];
$query_string = "delete from $table_info where user_id='id';
$result = mysql_query($result) or die ('Could not execute.'. mysql_error());
return false;
}
}
It looks like you're missing a closing double-quote at the end of this line:
$query_string = "delete from $table_info where user_id='id';
It should read:
$query_string = "delete from $table_info where user_id='id'";
There may be other errors as well. You should learn to use your browser's built-in script debugging features (and/or download one if your browser doesn't have one). For example, try Firebug and the Web Developer Toolbar for Firefox.
Following is code for username.php
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<!-- <script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"></script> -->
<script type="text/javascript">
$(document).ready(function(){
$("#username").change(function(){
$("#message").html("<img src='ajax-loader.gif' /> checking...");
var username=$("#username").val();
$.ajax({
type:"post",
url:"check.php",
data:"username="+username,
success:function(data){
if(data==0){
$("#message").html("Username available");
}
else{
$("#message").html("Username already taken");
}
}
});
});
});
</script>
</head>
<body>
<table>
<tr>
<td>Username</td>
<td>:</td>
<td><input type="text" name="id" id="username""/><td>
<td id="message"><td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="text" name="password" id="password" /><td>
</tr>
</table>
</body>
</html>
And the code for check.php
<?php
mysql_connect("localhost","healhmate","healthmate");
mysql_select_db("hmdb");
if(isset($_POST['id']))
$username=$_POST['id'];
$query=mysql_query("SELECT * from user where id='$username' ");
$find=mysql_num_rows($query);
echo $find;
?>
this code gives output as username and password boxes. I have included all the 3 files ajax-loader.gif, username.php and check.php in one single folder.On entering username no validation is performed. Can anyone help me to figure out why is this happening?
<?php
mysql_connect("localhost","healhmate","healthmate");
mysql_select_db("hmdb");
if(isset($_POST['username']))// because in ajax you send username not id
$username=$_POST['username'];
$query=mysql_query("SELECT * from user where id='$username' ");
$find=mysql_num_rows($query);
echo $find;
?>
Use data:"id="+username in Ajax request because that is the POST variable your checking in PHP.
Also on a side note:
Make sure you handle a case where $_POST['username'] is not set.
<?php
mysql_connect("localhost","healhmate","healthmate");
mysql_select_db("hmdb");
if(isset($_POST['username'])) {// because in ajax you send username not id
$username=$_POST['username'];
$query=mysql_query("SELECT * from user where id='$username' ");
$find=mysql_num_rows($query);
echo $find;
} else {
echo "-1";
}
?>
And do not use mysql_* functions. They are deprecated. Use mysqli_* functions or PDO.