简体   繁体   中英

PHP: how to populate html form fields with query results using ajax

I'm trying to populate a form with values after performing a simple search but when I run the script, I either get "undefined" or a blank response when I do alert(data);.

search.php

<?php
include_once 'config/config.php';
include_once 'config/connect.php';
$conn = dbconn();

if(isset($_POST['btn-search']))
{
    $sub_id = mysqli_real_escape_string($conn, $_POST['user_id']);
    $sql = "SELECT * FROM users WHERE user_id = '".$sub_id."'";
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($res);

    $found = array();
    while ($row = mysqli_fetch_array($res))
    {
        $found[] = array(
            'name' => $row['full_name'],
            'init_date' => $row['init_date'],
            'position' => $row['position'],
            'email' => $row['email'],
        );
        echo json_encode($found);
    }
}
mysqli_close($conn);
?>

script

<script>
/*
simple validation script
*/

$('document').ready(function()
{
    $('#register-submit-btn').attr('disabled', 'disabled');
     /* validation */
     $("#register-form").validate({
      rules:
      {
            user_id: {
            required: true,
            minlength: 5,
            },
       },
       messages:
       {
            cedulaid:{
                      required: "The user ID is required",
                      minlength: "The user ID should be no less than 5 characeters long.",
                     },
       },
       submitHandler: submitForm
       });  
       /* validation */

       /* get data */
       function submitForm()
       {        
            var data = $("#details-form").serialize();

            $.ajax({
            type : 'POST',
            url  : 'search.php',
            data : data,
            beforeSend: function()
            {
                $("#detailsmsg").fadeOut();
                $("#btn-search").html('<img src="include/btn-ajax-loader.gif" /> &nbsp; Looking...');
                $('#btn-search').attr('disabled', 'disabled');
            },
            success :  function(data)
               {
               alert(data);
                        $("#detailsmsg").fadeIn(1000, function(){                       
                        $("#detailsmsg").removeClass("alert-danger").addClass("alert-success");
                        $('#btn-search').removeAttr('disabled');
                        $("#btn-search").html('Search again?');
                        $('#register-submit-btn').removeAttr('disabled');
                        $("#detailsmsg").html("<span>Data Found</span>");

                        });
                        $("#name").val(data.name); // not sure how to do this part. this is probably very wrong but still not getting anything on the alert.
                        $("#init_date").val(data.init_date);
                        $("#position").val(data.position);
                        $("#email").val(data.email);
              }
            });
                return false;
        }
       /* get data */
});
</script>

I have the alert(data) at the top of the success function because I want to see what I would get in return but it comes back blank. If I do alert(data[0]) I get "undefined" message.

the console POST returns this:

name=&init_date=&position=&email=

There are probably many mistakes in the script and I'm open to any feedback and help I can get. Let me know if any other details are needed.

Thanks in advance,

for getting single output, you only need a $row = mysqli_fetch_array($res); not loop..it will return single parameter output..

Search.php

<?php
include_once 'config/config.php';
include_once 'config/connect.php';
$conn = dbconn();

if(isset($_POST['btn-search']))
{
    $sub_id = mysqli_real_escape_string($conn, $_POST['user_id']);
    $sql = "SELECT * FROM users WHERE user_id = '".$sub_id."'";
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($res);

    $found = array();

        $found[] = array(
            'name' => $row['full_name'],
            'init_date' => $row['init_date'],
            'position' => $row['position'],
            'email' => $row['email'],
        );
        echo json_encode($found);

}
mysqli_close($conn);
?>

try it once..may be it will help you.

By just quickly looking at the PHP code it returns nested arrays:

[
    [
        'name' => 'whatever',
        'init_date' => 'date',
        ...
    ]
]

This happens because you first define $found = array(); and then append more arrays to it with $found[] = array(...) .

The javascript part however tries to access just data.name which doesn't exist. Maybe data[0].name should exist assuming there's at least one record in the database.

Did you want to iterate data as an array instead?

But maybe the problem lies in the PHP part where you call mysqli_fetch_array() twice and therefore override $row variable and skip the first result found:

$row = mysqli_fetch_array($res);

$found = array();
while ($row = mysqli_fetch_array($res))
{
...

Last thing I see is that you probably want to call echo json_encode($found); after the while loop when you've collected all search results. By the way, this also produces invalid JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM