1

I am trying to make a user search system like facebook using ajax and php json. But i have one problem.

From the data users table have Marc Zuckerberg, Marc Zeyn, Marc Alp. I mean 3 user first name is same, so normaly when i write the Marc name then i should be get all Marc names from data. Like

<div class="ul">Marc Zuckerbert</div>
<div class="ul">Marc Zeyn</div>
<div class="ul">Marc Alp</div>

but i am not getting all Marc names just i am getting one marc result. Chrome developer console show me all Marc name but not show my within HTML. I think i need some code from ajax success.

JS

$('body').delegate('#searchkey','keyup', function(){
      clearTimeout(timer);
      timer = setTimeout(function(){
          var box = $('#searchkey').val();
          contentbox = $.trim(box);
          var dataString = 'keys=' + contentbox;
          if(contentbox !==''){
            $.ajax({
              type: "POST",
              url: siteurl +"requests/search.php",
              data: dataString,
              dataType:"json",
              cache: false,
              beforeSend: function(){},
              success: function(data){ 
                   $('.un').html(data.username);
                   $('.uf').html(data.fullname);
              }
            });
          }
      });
   });

search.php

<?php
include_once 'inc.php';
if(isset($_POST['keys'])) {
     $keys = mysqli_real_escape_string($db, $_POST['keys']); 
    $keyRestuls = $WidGet->SearchUser($keys);
    if($keyRestuls) {
        // If array is in data
     foreach($keyRestuls as $datas) { 
        $dataUsername = $datas['username'];
        $dataUserID = $datas['fullname'];
        $data = array(
          'username' => $dataUsername,
          'fullname' => $dataUserID
        );  
       echo json_encode( $data );   
 }
}
}
?>

SearchUser function is here

    public function SearchUser($keys){
       $keys = mysqli_real_escape_string($this->db, $keys);
       $result = mysqli_query($this->db,"SELECT 
          username,
          uid,
          fullname FROM 
          users WHERE 
          username like '%{$keys}%' or fullname like '%{$keys}%' 
          ORDER BY uid LIMIT 10") or die(mysqli_error($this->db));
             while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
                 $data[]=$row;
             }
             if(!empty($data)) {
             // Store the result into array
              return $data;
             } 
      }
AlwaysStudent
  • 1,354
  • 18
  • 49

1 Answers1

2

Your PHP script is generating a malformed JSON

{"username":"marc1","fullname":"Marc Zuckerberg"}
{"username":"marc3","fullname":"Marc Zeyn"} 
{"username":"marc2","fullname":"Marc Alp"} 

It shoulds generate

[
    {"username":"marc1","fullname":"Marc Zuckerberg"},
    {"username":"marc3","fullname":"Marc Zeyn"},
    {"username":"marc2","fullname":"Marc Alp"},
]

You can fix it by appending to an array instead of writting each row independamently

foreach($keyRestuls as $datas)
{ 
    $dataUsername = $datas['username'];
    $dataUserID = $datas['fullname'];
    $data[] = array(
      'username' => $dataUsername,
      'fullname' => $dataUserID
    );    
}
echo json_encode( $data ); 

And then you'll have to loop over $data in your JS, I suggest you use $.each

function success(data) {
    $.each(data, function(key, value) {
        console.log(value.username + ": " + value.fullname);
    })
}
gogaz
  • 2,323
  • 2
  • 23
  • 31
  • so i need just this in `$.each` like this: `$(".un").html(value.username);` right ? If yes why i am getting this error from developer console. `Uncaught TypeError: Cannot read property 'fullname' of null` – AlwaysStudent Dec 11 '17 at 13:59
  • don't use `.html()` as it will replace previously inserted data. See edit and try it yourself, I had no errors running it with the data I provided. – gogaz Dec 11 '17 at 14:10
  • Use Chrome dev tools, the Console is a JS interpreter and you can see ajax responsonses in the Network tab – gogaz Dec 11 '17 at 14:13
  • your `echo json_encode( $data );` showing me all user table row but i just need username and fullname. [Look at the screenshot please](https://prnt.sc/hm04vf) – AlwaysStudent Dec 11 '17 at 14:19
  • try renaming to `$data_json` then, maybe an interference from your `SearchUser`'s `$data` – gogaz Dec 11 '17 at 14:23
  • That problem was fixed but can you tell me what is this. Why i am getting many result from developer console for just one letter 'm' ? [SCREENSHOT](https://prnt.sc/hm0emu) – AlwaysStudent Dec 11 '17 at 14:37
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160939/discussion-between-gogaz-and-devstud). – gogaz Dec 11 '17 at 14:41