4

I have a fairly simple login form that is submitted with a jQuery AJAX request. Currently, the only way to submit it is to press the "Login" button, but I would like to be able to submit the form when the user presses "Enter".

I have only ever done form submissions using jQuery AJAX requests, but I'm unsure of what modifications I would need to make in order to have the form also be submitted when the user presses "Enter".

HTML:

<form>

    <label for="username">Username</label>
    <input type="text" id="username" placeholder="Username" />

    <label for="password">Password</label>
    <input type="text" id="password" placeholder="Password" />

</form>

<button id="login">Login</button>

JavaScript:

$(document).ready(function() {

    $('#login').click(function() {

        $.ajax({
            type: "POST",
            url: 'admin/login.php',
            data: {
                username: $("#username").val(),
                password: $("#password").val()
            },
            success: function(data)
            {
                if (data === 'Correct') {
                    window.location.replace('admin/admin.php');
                }
                else {
                    alert(data);
                }
            }
        });

    });

});

Excerpt from login.php:

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->execute(array(
    ':username' => $user,
    ':password' => $pass
));

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$affected_rows = $stmt->rowCount();

if ($affected_rows == 1) {
    //add the user to our session variables
    $_SESSION['username'] = $username;
    echo ('Correct');
} else {
    echo 'Incorrect username/password';
}
Jordan
  • 908
  • 4
  • 17
  • 36

9 Answers9

8

Add an ID to your form and transform your login button into a submit button :

<form id="myform">

<label for="username">Username</label>
<input type="text" id="username" placeholder="Username" />

<label for="password">Password</label>
<input type="text" id="password" placeholder="Password" />

<input type="submit" id="login" value="Login"/>

</form>

Then, instead of using the click event:

$('#login').click(function() {

use the submit event:

$('#myform').submit(function() {
tmuguet
  • 1,165
  • 6
  • 10
  • 2
    don't forgot to return false inside the handler function because you don't want to really submit the form. – MatRt Dec 05 '12 at 02:02
1

HTML

<form id='myfrm'>
    <label for="username">Username</label>
    <input type="text" id="username" placeholder="Username" />

    <label for="password">Password</label>
    <input type="text" id="password" placeholder="Password" />

    <button id="login">Login</button> 
</form>

JavaScript:

$(document).ready(function() {

    $('#myform').submit(function() {

        $.ajax({
            type: "POST",
            url: 'admin/login.php',
            data: {
                username: $("#username").val(),
                password: $("#password").val()
            },
            success: function(data)
            {
                if (data === 'Correct') {
                    window.location.replace('admin/admin.php');
                }
                else {
                    alert(data);
                }
            }
        });
        //this is mandatory other wise your from will be submitted.
        return false; 
    });

});
Juned Ansari
  • 5,035
  • 7
  • 56
  • 89
0
​$('form').on('keyup', function(e){
    if(e.which == 13 || e.keyCode == 13){
        alert('enter pressed');
    }        
});​​
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • This, except give your anonymous click function a name (`$('#login').click(doFormSubmit);`) then replace `alert('enter pressed');` with `doFormSubmit();` – joequincy Dec 05 '12 at 02:00
0
  //Insert
    $.ajax({
    url:'insert.php',
    type:'post',
    dataType:'html',
    data:$('#myform').serialize(),
    success:function(s){
        alert(s);
      //  $('#myform')[0].reset();  
      $('#data_table').load('#data_table');         
    }
  })

//FETCH
$(document).ready(function(){
$.ajax({
url:'fetch.php',
method:'post',
data:'json',
success:function(response){

  var data=JSON.parse(response);
  for(i in data){
    
     $("table").append( 
      "<tr id='"+data[i].manid+"'><td>"+data[i].manid+"</td>"
        +"<td>"+data[i].name+"</td>"
        +"<td>" +data[i].date_of_birth+"</td>"
        +"<td>" +data[i].skill_code+"</td>"
         +"<td>"+data[i].email+"</td>"
         +"<td>" +data[i].mobileno+"</td>"  
         +"<td>" +data[i].address+"</td>" 
         +"<td>" +data[i].remarks+"</td>"  
         +"<td>" +'<i class="fas fa-pen text-warning" id="edit"></i>'+"</td>"  
         +"<td>" +'<i class="far fa-trash-alt text-danger remove" id="delete"></i>'+"</td></tr>"); 
        }       
  }
})
})



//DELETE
  $(document).ready(function(){

  $("#data_table").on('click','#delete',function(){
    var id = $(this).parents("tr").attr("id");


    if(confirm('Are you sure to remove this record ?'))
    { 
        $.ajax({
           url: 'delete.php',
           type: 'GET',
           data: {id: id},
           error: function() {
              alert('Something is wrong');
           },
           success: function(data) {
                $("#"+id).remove();
                alert("Record removed successfully");  
           }
        });
   }
 });});

//EDIT
$(document).ready(function(){
$('#data_table').on('click','#edit',function(){
    var id = $(this).parents("tr").attr("id");

    if(confirm('Are you sure to edit this record ?'))
    { 
        $.ajax({
           url: 'edit.php',
           type: 'GET',
           data: {id: id},
           error: function() {
              alert('Something is wrong');
           },
           success: function(response) {
             $('#submit').hide();
             $('#update').css('display','block');
            var data=JSON.parse(response);
            for(i in data){
               $('#id').val(data[i].manid);
               $('#name').val(data[i].name);
               $('#dob').val(data[i].date_of_birth);
               $('#skill').val(data[i].skill_code);
               $('#address').val(data[i].address);
               $('#mobile').val(data[i].mobileno);
               $('#email').val(data[i].email);
               $('#remarks').val(data[i].remarks);

            }
            
}
        });

   }

})
 })


//UPDATE
$(document).ready(function(){
$('#update').click(function(){
    $.ajax({
    url:'update.php',
    type:'post',
    dataType:'html',
    data:$('#myform').serialize(),
    success:function(s){
        alert(s);
      $('#myform')[0].reset();  
      $('#submit').show();
      $('#update').css('display','none');         
    }
  }) 
})})
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 07 '23 at 10:18
0
//Ajax code for dependency dropdown
<script>
$(document).ready(function(){
    $('#state').on('change',function(){
        var state= $('#state').val();
        // alert(state);
        $.ajax({
            url:'drop.php',
            type:'post',
            data:{s_id:state},
            success:function(a){
                // alert(a);
                $('#district').html(a);
            }

        })
    })
})
</script>

// PHP code dependency dropdown

<?php

if(!empty($_POST['s_id'])){
$id=$_POST['s_id'];

$sql="select * from distr where state_id=$id";
$query=pg_query($sql);
if(pg_num_rows($query)>0){
 echo '<option value="">Select District</option>'; 
    while($row=pg_fetch_assoc($query)){
        echo '<option value="'.$row['id'].'">'.$row['dist'].'</option>';    
    
    }
 }
    else{
        echo"<option value=''>not found</option>";
    }
 }
 ?>
//HTML code
     <label class="form-label">State</label>
<select class="form-select" id="state" name="state">
           <option value="" >select</option>
           <?php
           $sql="select * from state";
           $query=pg_query($sql);
           while($row=pg_fetch_assoc($query)){
               echo"<option value='".$row['id']."'>".$row['st']."</option>";
           }
           ?>
       </select>
<label class="form-label">District</label>
 <select class="form-select" id="district" name="district">
           <option value="" >select</option>
       </select>
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 07 '23 at 10:18
  • Add an explanation of those scripts. – sanitizedUser Jul 12 '23 at 12:47
0
    //regex code for text & number
 $(document).on('keyup blur','#name',function(){
 $(this).val( $(this).val().replace(/[^A-Za-z ]/g,'') ); 
});
$(document).on('keyup blur','#phone,#pincode',function(){
    $(this).val($(this).val().replace(/[^0-9]/g, ''));
})

//On submit validation
$(document).on('click', "#submit", function() {
var Current_Field_id = $(this).attr('id');
try{
    if ($("#name").val().length == '') {
        throw {
            msg: "Enter your name",
            foc: "#name"
        }
    }
    if ($("#dob").val().length == '') {
        throw {
            msg: "Enter your date of birth",
            foc: "#dob"
        }
    }

var birthday=$('#dob').val();
var optimizedBirthday = birthday.replace(/-/g, "/");
var myBirthday = new Date(optimizedBirthday);
var currentDate = new Date().toJSON().slice(0,10)+' 01:00:00';
var myAge = ~~((Date.now(currentDate) - myBirthday) / (31557600000));

if(myAge < 25 || myAge > 35) {
    throw{
        msg:'Age should must be above 25-35 years',
        foc:'#dob'
    }
}
    if ($("#skill").val().length == '') {
        throw {
            msg: "choose your skill",
            foc: "#skill"
        }
    }
if ($('input:radio[name=gender]:checked').length == 0)  {
        throw {
            msg: "select gender",
            foc: "#gender"
        }
    }

    if ($("#mobile").val().length == '') {
        throw {
            msg: "Enter mobile number",
            foc: "#mobile"
        }
    }

   if($('#email').val().length==""){
            throw{
                msg:'please enter email',
                foc:'#email'
            }
        }
        if(!$('#email').val().match(/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/)){
            throw {
                msg: "Enter valid Email",
                 foc: "#email"
            }

        }

    $.ajax({
    url:'insert.php',
    type:'post',
    dataType:'html',
    data:$('#myform').serialize(),
    success:function(s){
        alert(s);
      //  $('#myform')[0].reset();  
      $('#data_table').load('#data_table');         
    }
  })
  
    return true;
}
catch(e){
    alert(e.msg);
    $(e.foc).focus();
} })
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 07 '23 at 10:18
0

Phone number validation

if (!$('#phone').val().match('[6-9]{1}[0-9]{9}')) {

        throw {
            msg: "Invald Mobileno",
            foc: "#phone"
        }

    }

    if ($('#phone').val() === '6666666666' || $('#phone').val() === '7777777777'
        || $('#phone').val() === '8888888888' || $('#phone').val() === '9999999999') {
        throw {
            msg: "Repated Numbers not allowed",
            foc: "#phone"
        }
    }
0

Index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Chennai</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
  <script src="https://kit.fontawesome.com/68ee502f7d.js" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script>
  <script>
    $(document).ready(function() {
        $("#starting").change(function(){
            var id=$('#starting').val();
            {

            $.ajax({
                url:'drop.php',
                type:'post',
                data:{ending_id:id},
                success:function(data){
                    $("#ending").html(data);
                }
            })
        }
              })
            })
  </script>
</head>
<body>
<div class="container">
    <div class="row mt-5">
        <div class="col-md-4"></div>
        <div class="col-md-4">
            <h5 class="text-center text-capitalize">Transport form</h5>
            <form class="form" id="form" name="form" autocomplete="off">
            <input type="hidden" id="id" name="id" >

                <label for="name">
                    Name
                </label> 
                <input type="text" name="name" id="name" class="form-control name">      
                <label for="dob" class="mt-4">DOB</label>
                <input type="date" name="dob" class="form-control dob" id="dob">    
                <label class="mt-4" for="gender">Gender</label>
                <br>
                <input type="radio" class="gender" id="male" name="gender" value="male">
                <label for="male">Male</label> 
                <input type="radio"class="gender" id="female" name="gender" value="female">
                <label for="female">Female</label>
                <input type="radio" class="gender" id="others" name="gender" value="others">
                <label for="others">Others</label>
                <br>
                <label for="phone" class="mt-4">Phone</label>
                <input type="text" class="form-control phone" id="phone" name="phone" maxlength="10">
                <label for="email" class="mt-4">Email</label>
                <input type="email" class="form-control email" id="email" name="email">
                <label for="starting" class="mt-4">From</label>
                <select name="starting" id="starting" name="starting" class="form-control starting">
                    <option value="">--select from--</option>
                    <?php
                    session_start();
                    require 'dbcon.php';
                    $sql = "select * from starting";
                    $result = pg_query($sql);
                    while ($row = pg_fetch_assoc($result)){ ?>
                    <option value="<?php echo $row['id']; ?>"><?php echo $row['starting_place'];?></option>
                    <?php
                    }
                    ?>
                </select>
                <label for="ending" class="mt-4">To</label>
                <select name="ending" id="ending" class="form-control ending">
                    <option value="">--select to--</option>
                </select>
                <button class="btn btn-success submit mt-4" name="submit" type="button" id="submit">Submit</button>
                <button class="btn btn-success mt-4" name="update" style="display:none;" type="button" id="update">Update</button>

            </form>
        </div>
    </div>
</div>
<div class="json-table container-fluid mt-5">
    <table class="table table-bordered text-center text-capitalize" id="table">
        <tr class="text-primary">
            <th>id</th>
            <th>Name</th>
            <th>Dob</th>
            <th>Gender</th>
            <th>Phone</th>
            <th>Email</th>
            <th>From</th>
            <th>To</th>
            <th>Edit</th>
            <th>Delete</th>
        </tr>
    </table>
</div>
<script>
        //regex code for text & number
 $(document).on('keyup blur','#name',function(){
 $(this).val( $(this).val().replace(/[^A-Za-z ]/g,'') ); 
});
$(document).on('keyup blur','#phone',function(){
    $(this).val($(this).val().replace(/[^0-9]/g, ''));
})

//On submit validation
$(document).on('click', "#submit", function() {
var Current_Field_id = $(this).attr('id');
try{
    if ($("#name").val().length == '') {
        throw {
            msg: "Enter your name",
            foc: "#name"
        }
    }
    if ($("#dob").val().length == '') {
        throw {
            msg: "Enter your date of birth",
            foc: "#dob"
        }
    }
if ($('input:radio[name=gender]:checked').length == 0)  {
        throw {
            msg: "select gender",
            foc: "#gender"
        }
    }

    if ($("#phone").val().length == '') {
        throw {
            msg: "Enter mobile number",
            foc: "#phone"
        }
    }

    if (!$('#phone').val().match('[6-9]{1}[0-9]{9}')) {

throw {
    msg: "Invald Mobileno",
    foc: "#phone"
}

}

if ($('#phone').val() === '6666666666' || $('#phone').val() === '7777777777'
|| $('#phone').val() === '8888888888' || $('#phone').val() === '9999999999') {
throw {
    msg: "Repated Numbers not allowed",
    foc: "#phone"
}
}

   if($('#email').val().length==""){
            throw{
                msg:'please enter email',
                foc:'#email'
            }
        }
        if(!$('#email').val().match(/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/)){
            throw {
                msg: "Enter valid Email",
                foc: "#email"
            }

        }
        if($('#starting').val().length==""){
            throw{
                msg: 'please choose From Place',
                foc: '#starting'
            }
        }
        if($('#ending').val().length==""){
            throw{
                msg: 'please choose To Place',
                foc: '#ending'
            }
        }

    $.ajax({
    url:'insert.php',
    type:'post',
    dataType:'html',
    data:$('#form').serialize(),
    success:function(s){
        alert(s);
    //   $('#data_table').load('#data_table');         
    }
  })
  
    return true;
}
catch(e){
    alert(e.msg);
    $(e.foc).focus();
} })
</script>

<!-- ajax fetch query -->

<script>
$(document).ready(function(){
$.ajax({
url:'fetch.php',
method:'post',
data:'json',
success:function(response){

  var data=JSON.parse(response);
  for(i in data){
    
     $("table").append( 
      "<tr id='"+data[i].id+"'><td>"+data[i].id+"</td>"
        +"<td>"+data[i].name+"</td>"
        +"<td>" +data[i].dob+"</td>"
        +"<td>" +data[i].gender+"</td>"
         +"<td>"+data[i].phone+"</td>"
         +"<td>" +data[i].email+"</td>"  
         +"<td>" +data[i].starting+"</td>" 
         +"<td>" +data[i].ending+"</td>"  
         +"<td>" +'<i class="fa-solid fa-pen-to-square text-warning" id="edit"></i>'+"</td>"  
         +"<td>" +'<i class="far fa-trash-alt text-danger remove" id="delete"></i>'+"</td></tr>"); 
        }       
  }
})
})

</script>

<!-- ajax delete query -->
<script>

 $(document).ready(function(){

$("#table").on('click','#delete',function(){
  var id = $(this).parents("tr").attr("id");


  if(confirm('Are you sure to remove this record ?'))
  { 
      $.ajax({
         url: 'delete.php',
         type: 'get',
         data: {id: id},
         error: function() {
            alert('Something is wrong');
         },
         success: function(data) {
            // alert(data)
              $("#"+id).remove();
              alert("Record removed successfully");  
         }
      });
 }
});
});

</script>

<!-- ajax edit -->
<script>

$(document).ready(function(){
$('#table').on('click','#edit',function(){
    var id = $(this).parents("tr").attr("id");

    if(confirm('Are you sure to edit this record ?'))
    { 
        $.ajax({
           url: 'edit.php',
           type: 'get',
           data: {id: id},
           error: function() {
              alert('Something is wrong');
           },
           success: function(response) {
             $('#submit').hide();
             $('#update').css('display','block');
            var data=JSON.parse(response);
            for(i in data){
               $('#id').val(data[i].id);
               $('#name').val(data[i].name);
               $('#dob').val(data[i].dob);
// gender edit
               if(data[i].gender=='male'){
                $("#male").prop("checked", true);
               }
               else if(data[i].gender=='female'){
                $("#female").prop("checked", true);
               }
               else{
                $("#other").prop("checked", true);
               }
// gender edit end
               $('#phone').val(data[i].phone);
               $('#email').val(data[i].email);
               $('#starting').val(data[i].starting);
            //    dependent edit
               $.ajax({
          url:'drop.php',
          type:'post',
          data:{ending_id:data[i].starting},
          success:function(res){
            $("#ending").html(res);//append option tag

               $('#ending').val(data[i].ending);

          }
        })
            }
            
}
        });

   }

})
 })

</script>

<!-- update ajax query -->

<script>
    $(document).ready(function(){
$('#update').click(function(){
    $.ajax({
    url:'update.php',
    type:'post',
    dataType:'html',
    data:$('#form').serialize(),
    success:function(s){
        alert(s);
      $('#form')[0].reset();  
      $('#submit').show();
      $('#update').css('display','none');         
    }
  });
});
});
</script>
</body>
</html>
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 07 '23 at 13:34
0

Dbcon.php

<?php
$db = pg_connect("host=localhost port=5432 dbname=test3 user=postgres 
password=2104");
?>

Drop.php

<?php
require_once 'dbcon.php';

if (!empty($_POST['ending_id'])) {
    $id = $_POST['ending_id'];

    $drop = "SELECT * FROM ending WHERE ending_id =$id";
    $result = pg_query($drop);

     if(pg_num_rows($result)>0){
    echo '<option value="">Select photographer</option>'; 
       while($row=pg_fetch_assoc($result)){
           echo '<option value="'.$row['id'].'">'.$row['ending_name'].'</option>';    
       
       }
    }

   
}
?>

Insert.php

<?php

session_start();

require 'dbcon.php';

$name = $_POST['name'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$starting = $_POST['starting'];
$ending = $_POST['ending'];

$insert = "insert into transport(name,dob,gender,phone,email,starting,ending)
values('$name','$dob','$gender',$phone,'$email','$starting','$ending')";

$result=pg_query($insert);
if ($result){
    echo'your form submit successfully';
}

else{
    echo 'your form not submit';
}

pg_close($db);
exit();

?>

Fetch.php

<?php

require_once 'dbcon.php';

$select = 'select * from transport';
$result = pg_query($select);

$data = array();

while ($row = pg_fetch_assoc($result)) {
    $data[] = $row;
}

echo json_encode($data);
exit();
?> 

Delete.php

<?php

require_once'dbcon.php';

if(isset($_GET['id'])){
$id=$_GET['id'];
$delete="delete from transport where id=$id";
$result=pg_query($delete);
}
?>

Edit.php

<?php
require_once'dbcon.php';
if(isset($_GET['id'])){
$id=$_GET['id'];
$edit="select * from transport where id=$id";
$result=pg_query($edit);
$data=array();
    
    while($row=pg_fetch_assoc($result)){
        $data[]=$row;
 
 }
 
 }  
 echo json_encode($data);
 exit();
 ?>

Update.php

<?php
require_once'dbcon.php';
 //print_r($_POST); die;
$id=$_POST['id'];
$name=$_POST['name'];
$dob=$_POST['dob'];
$gender=$_POST['gender'];
$phone=$_POST['phone'];
$email=$_POST['email'];
$starting=$_POST['starting'];
$ending=$_POST['ending'];

$update="update transport set name='$name',dob='$dob', gender='$gender',phone= $phone,email='$email',starting='$starting',ending='$ending' where id=$id";
$result=pg_query($update);
if($result){
echo"Updated successfully";
}
else{
echo"Something wrong";
}
?>
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 07 '23 at 13:36