douqi1625 2016-10-18 20:52
浏览 56

从JSON自动完成HTML表单

Allright so I have this form :

Form

When the name is entered in the first input , I need to populate the "ID" and "Email" with data from a SQL table. The name input is autocomplete with JSON, here is an example of the JSON:

[{
"label": "Andre Nadeau",
"Num": "104J",
"email": "Andre.Nadeau@example.com"
}, {
"label": "Andre Potvin",
"Num": "130J",
"email": "Andre.Potvin@example.com"
}],

I'm able to autocomplete the Name field but I don't understand how to send the data for the ID and email in the other fields.

PHP :

$query = $db->query("SELECT * FROM info_employer WHERE Prenom LIKE '%".$searchTerm."%' ORDER BY Prenom ASC");
while ($row = $query->fetch_assoc()) {
    $data[] = array(
        'label' => $row['Prenom'] . ' ' . $row['Nom'],
        'Num' => $row['Num'],
        'email' => $row['Email']
    );}

HTML:

<script>
        $(function() {
            $( "#Nom" ).autocomplete({
                source: 'Search.php',
            })
        })
</script>


<div class="form-group">
    <label for="Name">Nom: </label>
       <input type="text" id="Nom" class="form-control" name="Nom" required>
    <label for="Num">ID: </label>
       <input type="text" id="Num" class="form-control" name="Num">
    <label for="Email">Email: </label>
       <input type="text" id="Email" class="form-control" name="Email">

EDIT:

I'm trying to work with Feeda answer, everything make a lot of sense but I'm having difficulties to make it work.

I changed my PHP to :

    $searchTerm = $_GET['term'];

//get matched data from table
$query = $db->query("SELECT * FROM info_employer WHERE Prenom LIKE '%".$searchTerm."%' ORDER BY Prenom ASC");
while ($row = $query->fetch_assoc()) {
    switch($option)   {
        case 'nom':
            $data[] = $row['Prenom'] . ' ' . $row['Nom'];
        case 'email':
            $data[] = $row['Email'];
    }

And the Javascript to :

        <script>
        $(function() {
            $( "#Nom" ).autocomplete({ source: 'Search.php?option=name', }) 
            $( "#email" ).autocomplete({ source: 'Search.php?option=email', })  
        })
    </script>

If I understand correctly I should be able to use /Search.php?option=nom and see some data but when I try in browser in give my a blank page with "null".

And of course my autocomplete is not working yet :(

UPDATE

At this point i'm not sure if it would be better if I create a new question but i'm almost there !

I'm able to get the data I need with all the help I got here( Thanks everyone <3)

My problem now is that I can find a user using the "Name" field in my form, but once I selected the user I need the email field to be completed automatically using the email linked to the user in my database...

So here is where I'm at for the code :

HTML $(function() { $( "#Nom" ).autocomplete({ source: 'Search.php?option=nom', }) $( "#email" ).autocomplete({ source: 'Search.php?option=email', })
})

PHP

   //get search term
$option = $_GET['option'];
$searchTerm = $_GET['term'];

//get matched data from table
$query = $db->query("SELECT * FROM info_employer WHERE Prenom LIKE '%".$searchTerm."%' ORDER BY Prenom ASC");
while ($row = $query->fetch_assoc()) {
    switch($option)   {
        case 'nom':
            $data[] = $row['Prenom'] . ' ' . $row['Nom'];
        case 'email':
            $data[] = $row['Email'];
    }
}

//return json data
echo json_encode($data);

I think I should use Ajax for that last part bot as you probably already guessed this is not one of my skills.

MORE UPDATE

Following gschambial advice :

HTML

<script>
$(function(){
$('#Nom').autocomplete({
              minLength: 0,
              source: function (request, response) {
                  $.ajax({
                      type: "GET",
                      url: 'Search.php',
                      dataType: "json",
                      data: {term : request.term},
                      dataType: "json",
                      success: function (data) {
                          $.each(data,function(key, item){
                             return {
                               label : item.NumColumnName,
                               value : item.EmailColumnName
                             };
                          });
                      },
                      error: function (result) {
                          alert("Error");
                      }
                  });
              },
              select: function (event, ui) {
                          var Num = $("#Num");
                          var Email = $("#Email");
                          Num.val(ui.item.label);
                          Email.val(ui.item.value);
              }
          });     
  });        

PHP

    $searchTerm = $_GET['term'];

//get matched data from table
$query = $db->query("SELECT * FROM info_employer WHERE Prenom LIKE '%".$searchTerm."%' ORDER BY Prenom ASC");
while ($row = $query->fetch_assoc()) {
    switch($option)   {
        case 'nom':
            $data[] = $row['Prenom'] . ' ' . $row['Nom'];
        case 'email':
            $data[] = $row['Email'];
    }
}

//return json data
echo json_encode($data);

Still no luck !

  • 写回答

2条回答 默认 最新

  • dongmeijian1716 2016-10-18 21:00
    关注

    Autocomplete takes an array so makes separate arrays of these and get it through ajax. and then assign source accordingly for each.

    while ($row = $query->fetch_assoc()) {
        $data['names'][] = $row['Prenom'] . ' ' . $row['Nom'];
        $data['ids'][] = $row['Num'];
        $data['emails'][] = $row['email'];
    

    }

    in JavaScript:

    source : data.names;
    

    ELSE:

    instead of source: Search.php try. Search.php?option=name

    On PHP.

    switch($option)   {
     case 'name':
      $data[] = $row['Prenom'] . ' ' . $row['Nom'];
     case 'email':
        $data[] = $row['email'];
    ..
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图