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.
Related
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
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
I'm pretty new to jQuery and I'm practicing with it. I've this html simple page:
<html>
<head>
<title> Testing jQuery
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js" type="text/javascript"></script>
<link href="mycss.css" rel="stylesheet" type="text/css">
</head>
<body>
<h2 id="myH"> This is a title.</h2>
<br>
<br>
<fieldset>
<legend>Data</legend>
<form name="myForm">
<input type="text" id="firstData" placeholder="Write something in here" \>
<br>
<br>
<input type="text" id="secondData" placeholder="Write something else in here" \>
<br>
</form>
<button id="formButton" value="Confirm">Confirm</button>
</fieldset>
<br><br><br>
<div id="myDiv"></div>
</body>
</html>
This PHP script:
<?php
/* Connection to DB*/
.... CONNECTIONS STUFF.........
$query = " SELECT * FROM table1;";
$results = mysql_query($query);
echo " <table border=\"2\"><tr> <th>ID</th><th>First</th><th>Second</th></tr>";
while($row = mysql_fetch_array($results)) {
?>
<tr>
<td>
<?php echo $row['ID']?>
</td>
<td>
<?php echo $row[ 'First']?>
</td>
<td>
<?php echo $row[ 'Second']?>
</td>
</tr>
<?php
} echo "</table>"; ?>
And finally this js code:
$(function () {
$('#formButton').on('click', function (e) {
var firstData = $('#firstData').val();
var secondData = $('#secondData').val();
var query = 'first=' + firstData + '&second=' + secondData;
// Here I use another php script.
$.get('myData.php', query, function (data) {
$('#myDiv').html(data);
});
});
$('#formButton').on('click', function (e) {
$.ajax({
url: "myquery.php",
type: "POST",
success: function (data) {
$("#myDiv").empty().html(data);
}
});
});
});
Ok , now that I've inserted all the code , the problem is that I can add elements to my database by using myData.php script but I'd like to create a page where in the top you can add elements and when you click on the confirmation button in the bottom (with a query) all the contents of the table are displayed. So I can add elements but I'm not able to display them. I'm new to jQuery and I'm trying to make it work , I've made different researches on the Web but I couldn't find anything that solved my problem. Could please someone help me? Thanks!
You can do both operation by single file myData.php
Put below code right after record inserted in myData.php
$query = " SELECT * FROM table1;";
$results = mysql_query($query);
echo " <table border=\"2\"><tr> <th>ID</th><th>First</th><th>Second</th></tr>";
while($row = mysql_fetch_array($results)) {
?>
<tr>
<td>
<?php echo $row['ID']?>
</td>
<td>
<?php echo $row[ 'First']?>
</td>
<td>
<?php echo $row[ 'Second']?>
</td>
</tr>
<?php
} echo "</table>"; ?>
No need of two ajax call. Remove the second button click jquery code.
On first button click event myData.php file will be called. First record will be inserted in your DB table with your existing code. After it place your code to fetch records from DB. your HTML will be sent in the response and place that HTML in the DIV with your existing jquery code.
you can use jquery load function for it, its very easy for you
http://www.w3schools.com/jquery/jquery_ajax_load.asp
just load a div from there to a div in current page
follow this url for the video tutorial, its very simple, use a div here then enter the id and in the page you are loading, please use another id and load that id into this page div
https://www.youtube.com/watch?v=mtz8MdQXhno
it works in wordpress and will simply work in php
same code
I want to use toggle() in table when i am fetching data from database, but its not working.
The issue is loop which i am using in "id name" because if i remove the loop and give a unique id name, then it works properly, but i am fetching the data and data is more than hundreds and so it is not possible to give unique id name so i have given the id name in loop.
Code is :
<?php
mysql_connect("localhost","root","");
mysql_select_db('new game')or die('database not found');
?>
<!DOCTYPE>
<html>
<head>
<title>Gaming Zone</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#$aa").click(function(){
$("#$bb").toggle(700);
});
});
</script>
</head>
<body>
<div align="right">Add</div>
<table width="735" border="1" align="center">
<tr>
<td width="568">Name</td>
</tr>
<tr>
<?php
$abc=mysql_query("select * from games order by game ASC");
$aa=0;
$bb=0;
while($row=mysql_fetch_array($abc))
{
$aa=$aa+1;
$bb=$bb+1;
?>
<td>
<?php echo $row['game']; ?> <sub>Requirements</sub><br>
<div id="$bb" style="background-color:#FF3; display:none"><?php echo $row['min']; ?><span style="padding-left:50px"><?php echo $row['rec']; ?></span><span style="padding-left:100px"><?php echo $row['max']; ?></span></div>
</td>
</tr>
<?php } ?>
</table>
</body>
</html>
Need for Help for how to give unique id name when data is huge in amount ? Thanks in Advance
This question already has answers here:
undefined index text fields php database?
(2 answers)
Closed 8 years ago.
how exactly ajax jquery working. i am new in ajax and jquery.
i want to delete row my using ajax.
index.php
<head><link rel="stylesheet" type="text/css" href="css/style.css"></head>
<h1>Login Here</h1>
<form name="f1" action="login.php" method="post">
<table border="1">
<tr><td>username</td><td><input type="text" name="t1"></td>
</tr>
<tr><td>password</td><td><input type="password" name="t2"></td></tr>
<tr><td><input type="submit" value="login"></td>
<td class="error"><?php if(isset($_GET['wrong_detial'])){
echo "RE-ENTER username and password !! "; }?>
</td>
</tr>
</table>
</form>
login.php
<head>
<script type="text/javascript" src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript">
function del() {
var info = 'id=' + id;
$.ajax({
type: 'get',
url: 'delete.php',
success: function (result) {
$("#div1").html(result);
}
});
return false;
}
</script>
</head>
<?php
include "db/db.php";
$user=$_POST['t1'];
$pass=$_POST['t2'];
$result=mysql_query("select * from registor where username='$user' and password='$pass' ")or die(mysql_error());
$row=mysql_fetch_row($result);
?>
<h1>Welcome Mr. <?php echo $user;?></h1>
<?php
if(!$user == $row[1] || !$pass ==$row[2]){ //if username or password not matched with database
header("location:account.php?wrong_detial");
}
else{
if($user == 'admin'){ //if admin login
?>
<table border="1">
<tr><td>User ID</td><td>Username</td><td>Password</td><td>Email-ID</td><td>delete</td></tr>
<?php
$admin_result=mysql_query("select * from registor");
while($admin_db=mysql_fetch_row($admin_result)){
?>
<tr>
<td><?php echo $admin_db[0];?></td>
<td><?php echo $admin_db[1];?></td>
<td><?php echo $admin_db[2];?></td>
<td><?php echo $admin_db[3];?></td>
<td id="div1">
Delete <!-- Deleting single record-->
</td>
</tr>
<?php
}
?>
</table>
<?php }
?>
delete.php
<?php
include "db/db.php";
if($_GET['delete']){
$drop=$_GET['delete'];
}
$result=mysql_query("delete from registor where username='$drop'");
if($result){
echo "deleted";
}
?>
what is the solution of this.
is there better way to delete record from database using ajax jquery.
Missing end curly braces in login.php for else block.
</table>
<?php }
?>
should be
</table>
<?php }
}
?>