0

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,

1
  • 2
    can try to put echo json_encode($found); out off loop from search.php Commented Aug 30, 2016 at 16:31

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @Kamlesh Gupta. your suggestion made some progress. I got a result this time but I'm getting all nulled values. [{"name":null,"init_date":null,"position":null,"email":null}]. if I query the database with the sample user_id I'm testing this with, I get the results I'm looking for so I don't think it has anything to do with the query. any ideas?
Ok, I manned to get the values into the array by changing modifying the data: data, in the ajax call to data: data : {user_id: $('#user_id').val()}, and the POST in the php script from if(isset($_POST['btn-search'])) to if(isset($_POST['user_id'])). now how do I get the values into the input fields?
Ok. I got it to work. I was using JSON.stringify(data) and I was getting the array results but I removed dataType: 'json', and did result = jQuery.parseJSON(data); and now I can use result.user_id to get the value from the array. so $("#user_id").val(result.user_id); now works.
1

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.

1 Comment

Thanks Martin. I removed the loop as suggested by Kamlesh Gupta and it made some progress. I don't necessarily need to iterate data as an array but I considered it was a good approach. I don't know how to pass the value of a php variable to fill out the expected field. if I do a regular variable like $user_id = $row['user_id']; how can I load the value into the form?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.