Ajax success need something for php JSON object

问题内容:

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;
             } 
      }

问题评论:

    
What is the puposes of braces {$keys} in your SQL request ?
    
    
Are you getting correct data and it is not displaying? Or are you not getting data at all?
    
@kerbholz If i write full name then i am getting result. For example if i write kerb then i am not getting any result but if i write kerbholz then i am getting result.
– DevStud
3 hours ago
    
could you print the query and show the query for different inputs? ?

答案:

答案1:

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);
    })
}

答案评论:

    
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
– DevStud
2 hours ago
    
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.
    
Use Chrome dev tools, the Console is a JS interpreter and you can see ajax responsonses in the Network tab
    
your echo json_encode( $data ); showing me all user table row but i just need username and fullname. Look at the screenshot please
– DevStud
1 hour ago
    
try renaming to $data_json then, maybe an interference from your SearchUser‘s $data

原文地址:

https://stackoverflow.com/questions/47753155/ajax-success-need-something-for-php-json-object

添加评论

友情链接:蝴蝶教程