0

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 !

ayyyymtl
  • 13
  • 7
  • can you `$(function() { $.ajax({ method: 'POST', url: 'Search.php' success: function(response) { console.log(response); }); });` execute this code and tell me what is being returned from your php file? – gschambial Oct 19 '16 at 13:01
  • I tryed the code and it returned a Uncaught SyntaxError: Unexpected identifier in the console, not sure if i'm missing something – ayyyymtl Oct 19 '16 at 16:43

2 Answers2

0

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'];
..
}
Fida
  • 1,339
  • 1
  • 12
  • 21
  • The solution make a lot of sense but I honestly have no idea how to work with ajax. I understand the PHP part but would need a bit more help for the JavaScript. – ayyyymtl Oct 18 '16 at 21:06
  • Allright so I understand the switch but how is this going to autocomplete the "Email" field when I enter a name in the name field ? – ayyyymtl Oct 18 '16 at 21:17
  • $( "#Nom" ).autocomplete({ source: 'Search.php?option=name', }) $( "#email" ).autocomplete({ source: 'Search.php?option=email', }) – Fida Oct 19 '16 at 06:35
  • I really appreciate the time you take to help me, – ayyyymtl Oct 19 '16 at 12:43
  • I edited the question with the change I made if you have time to take a look :) – ayyyymtl Oct 19 '16 at 12:49
  • $option = $_GET['option']; – Fida Oct 19 '16 at 12:55
0

I think, you need something like this:

$(function(){
$('#Nom').autocomplete({
              minLength: 0,
              source: function (request, response) {
                  $.ajax({
                      type: "POST",
                      url: 'Search.php',
                      dataType: "json",
                      data: {term : request.term},

                      success: function (data) {
                          $.each(data,function(key, item){
                             return {
                               label : item.nom,
                               value : item.email
                             };
                          });
                      },
                      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 CODE:

$post_data= json_decode(file_get_contents('php://input'), true); 
print_r($post_data); 
$searchTerm = $post_data["term"];
    $data= array();

    //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()) {

                $data["nom"] = $row['Prenom'] . ' ' . $row['Nom'];
                $data["email"] = $row['Email'];

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

Try this out! I hope, It will solve your purpose.

gschambial
  • 1,383
  • 2
  • 11
  • 22
  • Thanks for the input, If I use an exact copy of the function you gave me i get some error in my error.log : PHP Notice: Undefined index: option in /var/www/html/Search.php on line 12, referer: http://absence.com/ PHP Notice: Undefined index: term in /var/www/html/Search.php on line 13, referer: http://absence.com/ PHP Notice: Undefined variable: data in /var/www/html/Search.php on line 31, referer: http://absence.com/ – ayyyymtl Oct 19 '16 at 16:45
  • @ayyyymtl This error comes when you have some uninitialized variables. – gschambial Oct 19 '16 at 17:09
  • Changed `searchTerm` to `term`. Check my updated answer. – gschambial Oct 19 '16 at 17:10
  • @ayyyymtl Also remove `$option = $_GET['option'];` from your `Search.php` file. – gschambial Oct 19 '16 at 17:13
  • @ayyyymtl can you also update the final version of PHP file you are using now? – gschambial Oct 19 '16 at 17:19
  • The part of the code you want is that where you pass data: { term: request.term } you would add something like { data: { email: $('#email').val(), num: $('#num').val() } } – Marco Oct 19 '16 at 17:22
  • @Marco Sorry, i didn't get you? – gschambial Oct 19 '16 at 17:23
  • @gschambial I just updated Marco , Yes this work for the autocomplete in 1 field but it don't fill the rest of the form :( – ayyyymtl Oct 19 '16 at 17:24
  • 1
    @ayyyymtl Don't worry, Autocomplete is Working, Great. We will get to the next part now. – gschambial Oct 19 '16 at 17:26
  • @gschambial By the way ,when i remove my $option = $_GET['option']; i get back the a Undefined variable in my error log – ayyyymtl Oct 19 '16 at 17:26
  • Oh and just to be sure I was clear, right now autocomplete is not working anymore with the function you gave me. I'm sure we are on the right path ! – ayyyymtl Oct 19 '16 at 17:31
  • @ayyyymtl actaully i don't know about PHP at all. I am just anticipating. Are you sure the way you are creating `$data` array is correct? – gschambial Oct 19 '16 at 17:31
  • I think I am since the autocomplete was working with $( "#nom" ).autocomplete({ source: 'Search.php?option=nom', }) – ayyyymtl Oct 19 '16 at 17:32
  • @gschambial I really appreciate the time you give me, I will stay on hold to make sure i'm not changing something that could break the script – ayyyymtl Oct 19 '16 at 17:38
  • @ayyyymtl I have update my answer. Also use the PHP Code i have added in my answer. – gschambial Oct 19 '16 at 17:44
  • @gschambial allright I updated the script and PHP, first time I opened the page I got an alert with "Error" and not much else. I think it's good news since now the script is "reacting" – ayyyymtl Oct 19 '16 at 17:48
  • @ayyyymtl can you check developer console and see if any error is logged? – gschambial Oct 19 '16 at 17:49
  • @gschambial no luck with the console, nothing in the logs. All I can see right now is that in my apache log the page do a GET (GET /Search.php?term=namehere HTTP/1.1" 200 205 "http://absence.com/) when I type – ayyyymtl Oct 19 '16 at 17:54
  • @ayyyymtl It means, Request is going. Can you confirm if data is being returned from the query. – gschambial Oct 19 '16 at 18:02
  • @ayyyymtl Check this question http://stackoverflow.com/questions/40021402/how-to-get-values-of-the-ajax-response/40021678#40021678. Are you sure you are doing similar thing. Because i am not aware much of PHP? – gschambial Oct 19 '16 at 18:04
  • @gschambial If got to the url absence.com/Search.php?term=Phi it return me a page with {"nom":"Philippe Mir","num":"373","email":"Philippe.Mir@example.com"} Seems like the data is returned correcly – ayyyymtl Oct 19 '16 at 18:16
  • But in my error log i have a PHP Notice: Undefined index: term in /var/www/html/Search.php on line 11 – ayyyymtl Oct 19 '16 at 18:16
  • @ayyyymtl Yeah, it means PHP code is now returning correct data. Are you getting this data with PHP code i shared or the previous one? – gschambial Oct 19 '16 at 18:19
  • @ayyyymtl I think you are not able to `term` query parameter. Try to get it in the way, I have updated the answer. Check and confirm. – gschambial Oct 19 '16 at 18:29
  • @gschambial Yes i was using the PHP you sent me , if I update with the last PHP you edited I'm back with a bunch Undefined index and Variable PHP Notice: Undefined variable: url in /var/www/html/Search.php on line 11 PHP Notice: Undefined index: query in /var/www/html/Search.php on line 12 PHP Notice: Undefined index: email in /var/www/html/Search.php on line 13 – ayyyymtl Oct 19 '16 at 18:36
  • @ayyyymtl I mistakenly wrote `query['email']` instead of `query['term']`. Did you notice? – gschambial Oct 19 '16 at 18:39
  • @gschambial yes but I wasn't certain if it was on purpose. I made the switch on my side but still no luck :'-( . Now when i try the url with /Search.php It return only the last result of the table.. – ayyyymtl Oct 19 '16 at 18:45
  • @ayyyymtl Check the updated answer. I think we can directly use parameter `term` in query. Also, change ajax request to `POST` – gschambial Oct 19 '16 at 18:48
  • @ayyyymtl try both `$term` and `{$term}` one by one. – gschambial Oct 19 '16 at 18:58
  • @gschambial it return me an error with {$term} (javascript alert and log) since PHP don't like the {} in this case. Should i get ride of the ( $parts = parse_url($url); parse_str($parts['query'], $query); $searchTerm = $query['term'];) of previous updates ? If i do it only say that the variable $term is not assigned – ayyyymtl Oct 19 '16 at 19:05
  • @ayyyymtl check the updated answer. you need to decide your JSON paramters from POST request and then get `term` from this. – gschambial Oct 20 '16 at 01:58