lexer
lexer

Reputation: 77

Populate input field with value from php mysql selected data using ajax

I have dropdown list populated from php mysql select (load from a table named "userstable" that has two fields "name" and "email"). I want to select a "name" from the php mysql dropdown list and using Ajax (json) gets the "email" for the user selected from mysql table and show it in a input field. The dropdown list works and I can select the name but the email info in not being populated in the input field called "email".

The mysql database table:

userstable contains fields [name],[email].

My index.php code:

<?php
    require_once("conection.php");
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Contact Form Validation using jqBootstrapValidation with Ajax PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jqBootstrapValidation/1.3.6/jqBootstrapValidation.js"></script>

<!-- Ajax function for getting email --> 
 <script>
$(document).ready(function(){
    $('#name').on('change',function(){
        var name = $(this).val();
        $.ajax({
            url : "getemail.php",
            dataType: 'json',
            type: 'POST',
            async : false,
            data : { name:name,email : email},
            success : function(data) {
                userData = json.parse(data);
                $('#email').val(userData.email);
            }
        }); 
    });
});
</script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Showing User Info</h3>
   <br />
   <form id="simple_form" novalidate="novalidate">
            <div class="row">
            <!--Dropdown list for selecting name --> 
              <div class="col-md-6">
                <div class="control-group">
                  <h3>User</h3>
                      <select required id="name" name="name"  class="form-control" onchange="showname(this.value)">
                      <option value="">Select User</option>
                        <?php include("userselect.php") ?> 
                      </select>
                </div>
              </div>
                <!-- input field for showing user email -->               
              <div class="col-md-6">
                <div class="control-group">
                   <h3>Email</h3>
                    <div class="form-group mb-0 pb-2">
                        <input type="text" name="email" id="email" class="form-control form-control-lg"  />
                        <p class="text-danger help-block"></p>
                    </div>
                </div>
              </div>           
          </div>
   </form>
  </div>
 </body>
</html>

This is the php code userselect.php for selecting user name for showing email:

<?php

    $selectdata = "SELECT * FROM userstable ORDER BY name";
    $DoQuery = $connect->query($selectdata);

    while($register = $DoQuery->fetch_assoc()){

        echo "<option value='".utf8_encode($register["name"])."'";
        if ($_POST["name"]==$register["name"])
        {
            echo "selected";
        }
        echo ">".utf8_encode($register["name"])."</option>";
    }
// $connect->close();
?>

This getmail.php code for getting email to show:

 <?php

     $connect = mysqli_connect("localhost", "root", "mysq1passw0rd", "users");

     $query = "SELECT * FROM userstable WHERE name = '".$_POST["name"]."'";
     $result = mysqli_query($connect, $query);
     while($row = mysqli_fetch_array($result))
     {
       $data["email"] = $row["email"];
     }

     echo json_encode($data);


    ?> 

Please, any ideas?

Upvotes: 0

Views: 1490

Answers (3)

lexer
lexer

Reputation: 77

Thanks to all, I changed Ajax fuction and getemail.php and now It works and I changed getdata.php for returning "email" and "age" of the user.

This my index.php file:

<?php
    include 'connection.php';
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Contact Form Validation using jqBootstrapValidation with Ajax PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jqBootstrapValidation/1.3.6/jqBootstrapValidation.js"></script>
<style type="text/css">


select#select_ext {
  border-radius: 10px;
  border: 2px solid #73AD21;
  padding: 20px; 
  width: 250px;
  height: 150px;
color: #333;
color: red;  
}

select#name{
    background: white;
    border: 0.15em solid #57ABB8;
    border-radius: 1.15em;
    color: gray;
    cursor: pointer;
    font-size: 0.80em;
    height: 39px;
    text-indent: 5px;
    width: 160px;
}

select#namex{
    background: white;
  border-radius: 5px;
  border: 2px solid #73AD21;
    color: blue;
    cursor: pointer;
    font-size: 1em;
    text-indent: 5px;
    width: 200px;
    height: 40px;
}
</style>



<!-- Ajax function --> 
<script>
$(document).ready(function(){
  $('#name').on('change',function(){
  var name= $('#name').val();
  if(name != '')
  {
   $.ajax({
    url:"getemail.php",
    method:"POST",
    data:{name:name},
    dataType:"JSON",
    success:function(data)
    {

     $('#age').val(data.age);
     $('#email').val(data.email);
     alert("email: " + data.email);
    }
   })
  }
  else
  {
   alert("Por favor seleccione nombre grupo");
   $('#employee_details').css("display", "none");
  }
 });
});
</script>


 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Showing User Info</h3>
   <br />
   <form id="simple_form" novalidate="novalidate">
            <div class="row">
            <!--Dropdown list for selecting name --> 
              <div class="col-md-4">
                <div class="control-group">
                  <h3>User</h3>
                      <select required id="name" name="name"  class="form-control" onchange="showname(this.value)">
                      <option value="">Select User</option>
                        <?php include("userselect.php") ?> 
                      </select>
                </div>
              </div>
              <div class="col-md-4">
                <div class="control-group">
                   <h3>Age</h3>
                    <div class="form-group mb-0 pb-2">
                        <input type="text" name="age" id="age" class="form-control form-control-lg"  />
                    </div>
                </div>
              </div> 
                <!-- input field "email" for showing user email -->               
              <div class="col-md-4">
                <div class="control-group">
                   <h3>Email</h3>
                    <div class="form-group mb-0 pb-2">
                        <input type="text" name="email" id="email" class="form-control form-control-lg"  />
                    </div>
                </div>
              </div>           
          </div>
   </form>
  </div>
 </body>
</html>

This my userselect.php file:

<?php

    $selectdata = "SELECT * FROM userstable ORDER BY name";
    $DoQuery = $connect->query($selectdata);

    while($register = $DoQuery->fetch_assoc()){

        echo "<option value='".utf8_encode($register["name"])."'";
        if ($_POST["name"]==$register["name"])
        {
            echo "selected";
        }
        echo ">".utf8_encode($register["name"])."</option>";
    }
// $connect->close();
?>

This is getemail.php:

<?php
require_once("connection.php");

if(isset($_POST["name"]))
{

$name=$_POST["name"];


 $query = "SELECT * FROM userstable WHERE name = '".$_POST["name"]."'";
 $result = mysqli_query($connect, $query);
 while($row = mysqli_fetch_array($result))
 {
   $data["age"] = $row["age"];
   $data["email"] = $row["email"];
 }

 echo json_encode($data);
}

?>

Please, How can I do as "sal" suggests for getting the fields "name" and "email" in the selectuser.php file and show "email" in input field id="email" using ajax?

Upvotes: 1

Steve Estes
Steve Estes

Reputation: 123

I'm seeing a couple basic issues that may or may not have anything to do with it.

  • the require_once at top having a possibly-typo'd conection.php, 1 'n' rather than 'nn'.
  • probably a best practice to put a space before "selected", i.e. " selected", in userselect.php
  • your code in the script calling getemail.php but your post referring to the file as getmail.php, i.e. no 'e'
  • not sure why you would set "async = false", since this is definitely an asynchronous request (user-triggered, not on page load - that's the 'a' in 'ajax').
  • your getemail.php script is designed to produce a set of rows, but your ajax parsing assumes it's only getting one reply. The JSON encoding may be trying to put a hierarchy around it to prepare for getting more than one row as output.

If none of that ends up mattering, then I'd try taking the unparsed output from the AJAX request and putting that in the email field (or just msgbox() it) to see if you're getting data back that looks right. That should help isolate the problem to whether it's in the request, the processing of the request, or the parsing of the reply.

Lastly, never put your password in code snippets like that - god knows where all else you use that password and this handle.

Upvotes: 1

Joynal Abedin
Joynal Abedin

Reputation: 75

Please remove a line your from your code

line: userData = json.parse(data);

success : function(data) {
    userData = json.parse(data);
    $('#email').val(userData.email);
}

To

success : function(data) {
    $('#email').val(data.email);
}

because you are already json_encode in your getmail.php file.

 echo json_encode($data); //your getmail.php

Upvotes: 1

Related Questions