I want validate my form using ajax , but the errors are not showing properly.
Here is my code:
Html
<body ng-app="app" ng-controller="dkController">
<form ng-submit="dk()">
<label>Username</label>
<input type="text" name="username" ng-model="formdata.user">
{{errorName}}
<label>Password</label>
<input type="text" name="password" ng-model="formdata.pass">
<label>Email</label>
<input type="text" name="email" ng-model="formdata.email">
<button type="submit" >Submit</button>
{{message}}
</form>
</body>
Js
function dkController($http,$scope){
$scope.formdata={};
$scope.dk = function(){
$http({
method:"POST",
url:"dk.php",
data:$.param($scope.formdata)
})
.then(function(response){
$scope.errorName = response.data.errors.username;
})
and PHP
$conn= new mysqli('localhost','root','','dangky');
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$sql="SELECT *FROM dangky where username='$username'";
$result= mysqli_query($conn,$sql);
$errors=array();
$data=array();
if(empty($username))
$errors['username']='user name is required';
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_assoc($result);
if ($row['username'] == $username){
$errors['check'] = 'Tên đăng nhập đã tồn tại';
}
}
if(!empty($errors)){
$data['success']=false;
$data['errors']=$errors;
}
echo json_encode($data);
Error username is showing but errors check not showing .
This is the php output
{"success":false,"errors":{"username":"user name is required"}} .
The problem is youu passed $scope.formdata which contains
{ user : 'someone', pass: 'abc123!', email: 'me#medotcom' }
Your PHP script is looking for post data { username: 'someone' }
So rename your ng-model to ng-model="formdata.username" or change your PHP to find $_POST['user']. Your choice but they must match.
Related
Here is my below code I'm just trying to send a message form with php script but the message is submitted well. but when it comes to showing success message I'm having trouble page submits the data but shows no code.
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#send").click(function(event){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "process.php",
data:{
name: name,
email: email,
message: message,
},
success:function(data) {
$('#msg').html(data);
}
});
});
});
</script>
Below is php and html code:
<?php
include 'db.php';
$name=$_POST["name"];
$email=$_POST["email"];
$message=$_POST["message"];
$query = mysqli_query($con, "INSERT INTO test(name, email, message) VALUES ('$name', '$email', '$message')");
if($query){
echo "Your message has been sent successfully!";
}
else{
echo "Your message has been not sent successfully!";
}
mysqli_close($con);
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="text" class="form-control" id="name" name="name">
<input type="text" class="form-control" id="email" name="email">
<textarea class="form-control" rows="5" id="message" name="message"></textarea>
<button id="send" type="submit" class="btn btn-primary">Send</button>
</form>
<div id="msg" class="alert alert-success hidden"><strong></strong></div>
It is because your form will be submitted as the button has the type submit. By changing the type to button the ajax should be working.
Change type="submit" to type="button"
I hope this will help!
here's the code guys please help me
if mysqli_num_rows==false Than code works but why num rows doesn't work i can't get it i tried everything but same error appears
<?php
//Start session
session_start();
//Include database connection details
require_once('db.php');
if(isset($_POST['submit'])){
$username=$_POST['username'];
$password=$_POST['password'];
$query="SELECT * FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($con,$query);
if($row=mysqli_num_rows($result)==1){
mysqli_fetch_array($con,$result);
echo 'Logged in';
header('location:profile.php');
}
else{
echo 'error occured';
}
}
?>
<form method="POST">
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">
<input type="submit" name="submit">
</form>
<form method="POST">
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">
<input type="submit" name="submit">
</form>
<?php
error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those errors
session_start();
require_once('db.php');
if(!empty(trim($_POST['username'])) && !empty(trim($_POST['password']))){ // check with posetd value
$user_name = trim($_POST['username']);
$password = md5(trim($_POST['password']));
$query = "SELECT * FROM users where username='$username' and password = '$password'"; // don't use plain password, use password hashing mechanism
$result = mysqli_query($con,$query); // run the query
if(mysqli_num_rows($result)>0){ // if data comes
// here do some data assignment into session
header('location:profile.php'); // go to other page
}else{
echo "Login creadentials are not correct"; // else no user is there with the given credentials
}
}else{
echo "please fill the form value";
}
?>
Note:-
Read and use prepared statements to prevent your code from SQL Injection. :-http://us.php.net/manual/en/mysqli-stmt.prepare.php
Above file extension must be .php
Many thanks to everyone. The html is fine, i believe the javascript is a problem still, and php looks ok, but I need a few more pointers. I have edited my code as follows...
html:
<input name="uname" type="text" placeholder="please enter a user name" required><br />
<input name="upassword" type="text" placeholder="please enter a password or passphrase" required><br />
<input id="register" name="register" type="submit" class="btn btn-primary btn-lg outline" onclick="register();"/>
function register() {
javascript
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "register.php",
data: { name: "uname", password: "password"},
success: function (result) {
alert("success");
}
});
}
And my biggest problem, php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', 'Schwinny2156!');
try {
$conn = new PDO("mysql:host=localhost;dbname=users;", USER, PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('INSERT INTO `users` (name, password VALUES (:name,:password)');
$stmt->bindParam(':name', $_POST['uname']);
$stmt->bindParam(':password', $_POST['upassword']);
$stmt->execute()
}
catch(PDOException $e)
{
echo $stmt . "<br>" . $e->getMessage();
}
$stmt = null;
I fixed up whatever looked wrong, not sure if I missed something.
Edit: forgot to mention, lookup password_hash and implement that. Storing password in plaintext is a no go.
Edit 2: Added the password hash function to get your started. Use password_verify to verify passwords on login.
<form onsubmit="return register(this);">
<input name="uname" type="text" placeholder="please enter a user name" required><br />
<input name="upassword" type="text" placeholder="please enter a password or passphrase" required><br />
<input id="register" name="register" type="submit" class="btn btn-primary btn-lg outline"/>
</form>
js
function register(form) {
$.post("register.php", $(form).serialize());
return false;
}
php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', 'password');
try {
$conn = new PDO("mysql:host=localhost;dbname=users;", USER, PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
define('uname', $_POST['uname']);
$passwordHash = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
define('upassword', $passwordHash);
$sql = 'INSERT INTO `users` (name , password) VALUES (?, ?)';
$conn->prepare($sql)->execute([uname, upassword]);
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Your Using GET method to Send Data From jQuery $.get("register.php");AND your accessing data from POST from PHP. Use $.post("register.php"); in jQuery or use $_GET in PHP
I want to have server side validation. Is there a way how can I have the alert like this image whenever the user input the data like email that exist in my database, the alert will appear when I hit the sumbit button. Thanks in advance. :D
Here's my create_acc.html
<form action="create_acc.php" method="POST" id="fieldform">
<dl>
<p><dt>Email Address:</dt>
<dd>
<input type="text" name="e-mail" id="e-mail" class="text" placeholder="Your Email will be your log in" autocomplete="off">
</dd>
</p>
<p><dt>Create Password:</dt>
<dd>
<input type="password" name="password" id="password" class="text" placeholder="Remember your password" autocomplete="off">
</p>
<p>
<p><dt>Your Complete name:</dt>
<dd>
<input type="text" name="name" id="name" class="text" placeholder="Your Complete name" autocomplete="off">
</p>
<p>
<dt>
<input type="submit" value="Submit">
</dt>
</p>
</dl>
</form>
Here's my create_acc.php
<?php
session_start();
$email = $_POST['e-mail'];
$name = $_POST['name'];
$pass = $_POST['password'];
$hash = hash('sha256',$pass);
function createSalt(){
$text = md5(uniqid(rand(), true));
return substr($text,0,3);
}
$salt = createSalt();
$pass = hash('sha256',$salt.$hash);
$conn = mysqli_connect('localhost','root','','mydb');
$email = mysqli_real_escape_string($conn,$email);
$query = "INSERT INTO customers(Email,Password,Name,salt) VALUES('$email','$pass','$name','$salt')";
mysqli_query($conn,$query);
mysqli_close($conn);
header('Location: index.php');
?>
You could use ajax to do this. When the user submits the form you would send an ajax request with the form data to your php script, the script will then respond with a value that you use to deside if you should display an alert or not, here is a basic example using jquery:
$(document).ready(function() {
// catch submit events for your form
$('#your-form-id').submit(function() {
// make an ajax request to your validation script
$.ajax{(
url:'create_acc.php',
type:'POST',
data:$(this).serialize(),
dataType:'json',
success:function(response) {
if(!response.success) {
alert('Something went wrong!');
}
}
});
return false;
});
});
Then in your php script you return a code telling the client how it went:
// create_acc.php
// I assume the form only has one value 'email'
$success = false;
if(isset($_POST['email'])) {
// here you would check if the email already
// exists in the database
$query = "SELECT * FROM <table> WHERE email = ?";
$stmt = $con->prepare($query);
$stmt->bind_param('s', $_POST['email']);
// execute the query and check if a row was returned
}
// if everything went fine you should change success to true
// return json response to client
$response = array('success' => $success);
print json_encode($response);
exit;
How to check sign using javascript and php , Like this ?
First, user will fill data in to input username and password
If username and password correct, It's will be alert SUCCESS
But username or password incorrect, It's will be alert FAIL
I tested my code, But not work. How can i do that ?
HTML
<form method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);" id="sign_in_fid">
<label>
Your Username
</label>
<input type="text" name="username" id="username">
<br>
<label>
Your Password
</label>
<input type="password" name="password" id="password">
<br>
<br>
<input name="submit" type="submit" value="Sign in"/>
</form>
JAVASCRIPT
<script language="JavaScript" type="text/javascript">
function checkform ( form )
{
var username_val = document.getElementById("username").value;
var password_val = document.getElementById("password").value;
</script>
<?PHP
include("connect.php");
$strUsername = "<script>document.writeln(username_val);</script>";
$strPassword = "<script>document.writeln(password_val);</script>";
$sql = "SELECT * FROM av8_users WHERE BINARY username = '$strUsername' and password = '$strPassword'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);
if($count==1)
{
?>
<script>
alert("SUCCESS");
</script>
<?PHP
}
else
{
?>
<script>
alert("FAIL");
</script>
<?PHP
}
?>
<script>
return true ;
}
</script>
The reason your code is failing is you are using JavaScript inside php code.
Try changing your
$strUsername = "<script>document.writeln(username_val);</script>";
$strPassword = "<script>document.writeln(password_val);</script>";
To
$strUsername = $_POST['username'];
$strPassword = $_POST['password'];