I'm making a registration form where the script is executed in a seperate file that is used thru AJAX.
I have tried using the script directly by doing <form action="assets/php/action.php?action=register method="post" id="registration-form"> And it works that way however I would like to use AJAX to do this.
The problem with that is that if I use AJAX the POST data is not sent to the action.php file.
I have tried debugging my code but I cannot find what is causing the issue.
My registration form:
<form action="#" method="POST" class="user" id="register-form">
<div id="regAlert"></div>
<div class="form-group row">
<div class="col-sm-12 mb-3 mb-sm-0">
<input type="text" name="name" id="name" class="form-control form-control-user"
placeholder="Name" required>
</div>
</div>
<div class="form-group">
<input type="email" class="form-control form-control-user" id="remail" name="email"
placeholder="Email Address" required>
</div>
<div class="form-group row">
<div class="col-sm-6">
<div id="passError" class="text-danger font-weight-bold"></div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<input type="password" class="form-control form-control-user"
id="rpassword" name="password" placeholder="Password" required minlength="8">
</div>
<div class="col-sm-6">
<input type="password" class="form-control form-control-user"
id="cpassword" name="cpassword" placeholder="Repeat Password" required minlength="8">
</div>
</div>
<input type="submit" value="Register Account" id="register-btn" name="register" class="btn btn-primary btn-user btn-block">
<hr>
</form>
My AJAX script: (Sorry about the comments that are not in English)
<script type="text/javascript">
$(document).ready(function() {
//Register Form Ajax Request
$("#register-btn").click(function(e) { //Kui registreerimis nuppu vajutatakse, siis
if($("#register-form")[0].checkValidity()) { //Kontrolli formi õigsust
e.preventDefault();
$("#register-btn").val('Creating Account...'); //Muudab registreerimis nupu teksti
if($("#rpassword").val() != $("#cpassword").val()) { //Kui paroolid ei ole samad siis näitab errori
$("#passError").text('* Passwords did not match!'); //Paroolide mitte sama olemise error
$("#register-btn").val('Register Account'); //Muudab registreerimis nupu teksti
} else { //Kui paroolid kattusid, siis
$("#passError").text(''); //Eemaldab paroolide mitte sama olemis errori kirja
$.ajax({
url: "assets/php/action.php",
method: 'POST',
data: $("register-form").serialize()+'&action=register',
success:function(data) {
$("#register-btn").val('Register Account'); //Muudab registreerimis nupu teksti
if(data === 'register') {
window.location = 'home.php';
} else {
$("#regAlert").html(data);
}
}
});
}
}
});
});
</script>
My action.php file:
<?php
session_start();
require_once 'auth.php';
$user = new Auth();
if(isset($_POST['action'])) {
if($_POST['action'] == 'register') {
$name = $user->test_input($_POST['name']);
$email = $user->test_input($_POST['email']);
$pass = $user->test_input($_POST['password']);
$hpass = password_hash($pass, PASSWORD_DEFAULT);
echo $name;
echo $email;
echo $pass;
if($user->user_exist($email)) { //Kontrollib kas selle meiliaadressiga on konto juba registreeritud, kui on siis
echo $user->showMessage('warning', 'This email is already registered'); //Saadab inimesele kirja, et selle emailiga on konto juba registeeritud, 'warning' tähendab teate tüüpi, teine tekst on kiri, mida saadab
} else { //Kui selle meiliaadressiga pole kasutajat veel registeeritud, siis
if($user->register($name, $email, $hpass)) {
echo 'register';
$_SESSION['user'] = $email;
} else {
echo $user->showMessage('danger', 'Something went wrong! Please try again later or contact support.');
}
}
print_r($_POST); //This only outputs that the action is register, no POST values are outputted
die();
}
}
?>
Thanks,
Nimetu.
Don't use AJAX. Use fetch instead, you don't need external libraries like jQuery and more efficient. This is an example:
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
More information here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Related
I am new to the PHP. I am trying to code a project using PHP and Ajax to logging into another page. But in Ajax query some parts are not executing that means it check every thing inside the Ajax query part but shows always "Wrong combination" in alert whenever it success.
Here is the code that I tried:
Logging page HTML would be:
form method="POST" class="form-signin">
<div class="account-logo">
<img src="assets/img/logo-dark.png" alt="">
</div>
<div class="form-group">
<label> Email</label>
<input type="email" name="email" id="email" autofocus="" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" id="password" class="form-control">
</div>
<div class="form-group text-right">
Forgot your password?
</div>
<div class="form-group text-center">
<input type="button" onClick="sendContact();" class="btn btn-primary account-btn" name="login" value="DO LOGIN" id="login_button">
<!-- <button type="submit" class="btn btn-primary account-btn">Login</button> -->
</div>
<div class="text-center register-link">
Don’t have an account? Register Now
</div>
</form>
The Ajax part would be:
function sendContact() {
var email = $('#email').val();
var password = $('#password').val();
var data = {
"email": email,
"password": password,
};
jQuery.ajax({
data: data,
url: "auth/log.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
success: function(data)
{
if(data==='success'){
window.location.replace('index.php');
}
else{
alert('Wrong combination');
}
}
});
// window.location.replace('index.php');
}
The log.php page would be
<?php
include "dbconnection.php";
session_start();
// $email=$_POST['email'];
// $password=$_POST['password'];
$select_data="select * from users where email='". $_POST['email']."' and password='".$_POST['password']."'";
$results= $conn->query($select_data);
if($results->num_rows>0){
$_SESSION["loggedin"] = true;
$_SESSION["user"] = $email;
echo 'success';
}else{
echo 'fail';
}
?>
Can some here help me.
I tried this code to use for login but it does not work. when I click on submit, nothing happens. When I tried to login I am always getting a wrong password error, but my password is correct. what should I do?
my HTML
<form class="form-horizontal" id="loginform" method="post">
<div class="form-group">
<label for="userid" class="col-sm-3 control-label">User ID</label>
<div class="col-sm-9 has-feedback">
<input type="text" class="form-control" id="userid" name="userid" placeholder="Enter Your User ID" required>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-3 control-label">Password</label>
<div class="col-sm-9 has-feedback">
<input type="password" class="form-control" id="password" name="password" placeholder="Enter Your Password" required>
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
</div>
<div class="form-group">
<div class="col-xs-4 col-xs-offset-8">
<button type="submit" id="submit" class="btn btn-danger btn-block btn-flat">Sign In</button>
</div>
</div>
</form>
my Php
<?php
$userid = security($_POST['userid']);
$password = security($_POST['password']);
$query = mysqli_query($link,"SELECT * FROM user WHERE USER_USERNAME = '".$userid."' AND USER_PASSWORD = '".$password."'");
$numrows = mysqli_num_rows($query);
if ($numrows!==0)
{
while($row = mysqli_fetch_assoc($query))
{
#$_SESSION['session_userid'] = $row['USER_USERNAME'];
#$_SESSION['session_accounttype'] = $row['ACCESS_ID'];
}
//Location Depends on the User Type
if($_SESSION['session_accounttype']=="1")
{
echo 'true';
}
}
else
{
echo 'false';
}
?>
My JS
$(document).ready(function(){
$("#add_err").css('display', 'none', 'important');
$("#submit").click(function(){
username=$("#userid").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "../basefunction/login.php",
data: "userid="+username+"&password="+password,
success: function(html){
if(html=='true') {
//$("#add_err").html("right username or password");
window.location="admin";
}
else {
$("#add_err").css('display', 'inline', 'important');
$("#add_err").html("<img src='images/alert.png' />Wrong username or password");
}
},
beforeSend:function()
{
$("#add_err").css('display', 'inline', 'important');
$("#add_err").html("<img src='images/ajax-loader.gif' /> Loading...")
}
});
return false;
});
});
Why other answers talk the salt for password?question asks why password was wrong.
I think this code have questions
if($_SESSION['session_accounttype']=="1")
The session_accounttype may be not eq 1?
Can't comment so...
There is many problems with this example.
The submit button is going to submit your form automatically to "/". Look into preventdefault in javascript to solve that problem.
You are using ajax post with a query string. This would be done using the 'data' property in jquery data: {'userid' : username ,'password':password}. Then use $_POST['userid] and $_POST['password'] in php to get the values;
Sql inject will become a problem. But i can see you are learning and hope this is just a test to better your understanding of databasing.
Hash passwords
i am using the id of modal box button for submitting values to login.php. My jquery code is:
$('#login1').on('click', function () {
$.post('login.php', {
'u': $('#email').val(),
'p': $('#password').val(),
'r': $('#role').val()
}, function (data) {
if (data == 'success') {
$('#myModal1').modal('show');
}
else {
$('#myModal2').modal('show');
}
});
return false;
});
login.php
<?php
$u=$_POST['u'];
$p=$_POST['p'];
$r=$_POST['r'];
$p=md5($p);
$mysqli=new mysqli('localhost','root','password','user_details');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$q=$mysqli->query("select * from register_info where Email='{$u}' , Password='{$p}' and Role='{$r}'");
$e=$q->num_rows;
if($e>0)
{
$loggedIn=true;
$result='success';
$_SESSION['logged_in']=true;
header('location: profile.php?email='.$u);
}
else
{
$loggedIn=false;
$result='fail';
}
?>
modal form code:
<div class="modal-body">
<form class="form-horizontal" action='login.php' method="POST">
<br>
<fieldset>
<div id="legend">
<legend class="">Login Details</legend>
</div>
<div class="control-group">
<!-- Username -->
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="text" id="email" name="email" placeholder="Enter Email" class="input-xlarge">
</div>
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="password" name="password" placeholder="Enter Password" class="input-xlarge">
</div>
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="role">Role</label>
<div class="controls">
<select name="role" class="form-control input-sm" id="role" placeholder="Enter role">
</select>
</div>
</div>
<br>
<br>
<button type="button" class="btn btn-success btn-lg" id="login1" data-dismiss="modal">Login</button>
</fieldset>
</form>
</div>
</div>
<div class="modal-footer">
</div>
</div>
I want that when I click on the button of login modal box on successfully checking the email and password it should redirect me to the profile.php page. Please help me correct the code
your trying to send data from a form to a database. There is no returning values from your php code. its redirect to another page while user logged . hence i modified the php code that may help you...
<?php
$u=$_POST['u'];
$p=$_POST['p'];
$r=$_POST['r'];
$p=md5($p);
$mysqli=new mysqli('localhost','root','password','user_details');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$q=$mysqli->query("select * from register_info where Email='{$u}' , Password='{$p}' and Role='{$r}'");
$e=$q->num_rows;
if($e>0)
{
$loggedIn=true;
$result='success';
$_SESSION['logged_in']=true;
}
else
{
$loggedIn=false;
$result='fail';
}
echo $result; // based on this open your modal window
?>
You encountered one issue in the SQL query.
The other issue is that your jQuery needs to follow the redirection from the ajax post response, the following is untested code:
$('#login1').on('click', function () {
$.post('login.php', {
'u': $('#email').val(),
'p': $('#password').val(),
'r': $('#role').val()
}, function (e, xhr) {
location.href = '/profile.php';
});
return false;
});
I got an ajax issue I can't get my head around. I'm using a ajax post method to send an email. But everytime I send one the post happens 2 times. I've tried adding preventDefault and stopPropagation but it doesn't seem to do the trick.
Jquery
$(document).ready(function()
{
$("#submit_btn").click(function(event)
{
event.preventDefault();
event.stopPropagation();
var proceed = true;
var submit = $('#submit_btn');
$("#contact_form input, #contact_form textarea").each(function () {
$(this).closest("div").removeClass('has-error');
if(!$.trim($(this).val())) {
$(this).closest("div").addClass('has-error');
proceed = false;
}
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).closest("div").addClass('has-error');
proceed = false;
}
});
if(proceed){
post_data = {
'user_name' : $('input[name=name]').val(),
'user_email' : $('input[name=email]').val(),
'subject' : $('select[name=subject]').val(),
'msg' : $('textarea[name=message]').val()
};
$.ajax({
type: 'POST',
url: "./mail.php",
data: post_data,
beforeSend: function() {
submit.html('Sending...');
},
success: function(data){
output = '<div class="alert alert-success" role="alert">Hi ' + $('input[name=name]').val() + ' Thank you for your email</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
},
error: function(){
output = '<div class="alert alert-danger" role="alert">Something went wrong. Please try again</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
}
});
return false;
}
else{
output = '<div class="alert alert-danger" role="alert">Please fill in the required fields so I can get back to you !</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
}
});
$("#contact_form input, #contact_form textarea").keyup(function() {
$(this).closest("div").removeClass('has-error');
$("#contact_form").find("#contact_results").slideUp();
});
});
HTML
<div class="clear" id="contact">
<h3>Contact Me</h3>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<form role="form" id="contact_form" action="">
<div class="form-group">
<label for="name">Name</label><input name="name" type="text" placeholder="Name" class="form-control" id="name" />
</div>
<div class="form-group">
<label for="email">Email address</label>
<input name="email" type="email" placeholder="E-Mail" class="form-control" id="email" />
</div>
<div class="form-group">
<label for="subject">Subject</label>
<select name="subject" class="form-control" id="subject">
<option value="General Question">General Question</option>
<option value="Hire me!">Hire me !</option>
<option value="Partner with me!">Partner with me !</option>
</select>
</div>
<div class="form-group">
<label for="message">Message</label><textarea name="message" placeholder="Message" id="message" class="form-control" rows="5"></textarea>
</div>
<button type="submit" class="btn btn-default" id="submit_btn">Send</button>
<div id="contact_results"></div>
</form>
</div>
</div>
</div>
</div>
If someone could point me in the right direction that would be much appreciated.
Try changing $("#submit_btn").click(function(event) to $("#submit_btn").one('click',function(event)
If that doesn't work, check that the JS is not being loaded twice
I have a registration form for my website, and it is showing username, password and password confirmation required although i am providing all of these. This is the controller code:
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]|xss_clean');
$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_rules('pass1','Password','trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('pass2','Password Confirmation','trim|required|matches[pass1]');
if ($this->form_validation->run() === FALSE)
{
$password = $this->input->post('pass1');
echo json_encode(array('error' => '1', 'message' => validation_errors('<div class="alert alert-error"><strong>Error!</strong> ', '</div>')));
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('pass1');
$email = $this->input->post('email');
$date = date('Y/m/d H:i:s');
$this->load->model('ui_model');
$this->ui_model->register_user($username,$password,$email,$date);
echo json_encode(array('error' => '0', 'message' => '<div class="alert alert-success"><strong>Success!</strong> You have been registered!</div>'));
}
and this is the view code:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Registration</h3>
</div>
<div class="modal-body">
<div id="registerModalerror" style="display: none;"></div>
<?php
$attributes = array('class' => 'form-horizontal','id' => 'registerModalform');
echo form_open('',$attributes);
?>
<div class="control-group">
<label class="control-label" for="Username">Username</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" id="inputUser" placeholder="Username" name="username" value ="" >
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-envelope"></i></span>
<input type="text" id="inputEmail" placeholder="email" name="email" value = "">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" id="inputPassword" placeholder="Password" name="pass1" value = "">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword2">Retype Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" id="inputPassword2" placeholder="Retype Password" name="pass2" value = "">
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn">Register</button>
</div>
</div>
</div>
<?php echo form_close(); ?>
<div class="modal-footer">
</div>
</div>
<script>
$(document).ready(function() {
$('#myModalReg').removeData('modal');
$('#myModalReg').hide();
$('#registerModalform').submit(registerUser);
});
function registerUser(event)
{
//Stop the form from submitting
event.preventDefault();
//Collect our form data.
var form_data = {
username : $("[name='username']").val(),
password1 : $("[name='pass1']").val(),
password2 : $("[name='pass2']").val(),
email : $("[name='email']").val()
};
//Begin the ajax call
$.ajax({
url: "http://localhost/fys/index.php/ui/do_register",
type: "POST",
data: form_data,
dataType: "json",
cache: false,
async : false,
success: function (json) {
// alert(json.pass);
if (json.error==1)
{
$('#registerModalerror').html(json.message).show();
}
else {
//Hide our form
$('#registerModalform').slideUp();
//Show the success message
$('#registerModalerror').html(json.message).show();
}
},
error: function(json)
{
alert(json.message);
}
});
}
</script>
I am not sure where it went wrong, and it is bugging me for almost 24 hours. Can anyone provide some help?
Thanks!
Your POST object is
{
username : $("[name='username']").val(),
password1 : $("[name='pass1']").val(),
password2 : $("[name='pass2']").val(),
email : $("[name='email']").val()
}
But your Controller's POST name is pass1 and pass2. You're passing up password1 and password2
:P