0

I am making a web app. Main index page has a big input tag for searching. A person enters a mobile number and through AJAX and php, i do a live search into a MySQL database.

I am being able to retrieve the the required row from the database. I have tried to do a print_r() on the resultant array, and it appears. But when i try to use only an element of the array, it doesn't.

Please see if you can find the problem:

The Javascript

<script>
$(document).ready(function(e) {
    $('#search').keyup(function(e) {
                if($(this).val().length > 2){
        $.get('php/search.php', {input: $(this).val()}, function(data){
                        alert(data);
                        });
                }
    });
});
</script>

php/search.php file is:

<?php
require_once 'customer.php';

$input = $_REQUEST['input'];
print_r($cus->read($input));
?>

And customer.php file is:

public function read($input) {
    //What search needs to do
    //Part 1 - Check if input is a mobile number or Text
    if(is_numeric($input) && strlen($input) > 2){
       //Search in mobile number
       $sql = "SELECT * FROM customers WHERE mobile LIKE '{$input}%' LIMIT 1";
       $result = $this->query($sql);
       $output = json_encode(mysqli_fetch_assoc($result));
       return $output;
    }else{}
}

$cus = new Customer();

When it works, this is what i can see:

If i remove the print_r function in search.php and in the javascript change the

alert(data);

to

alert(data[0]);

i get an alert which says "undefined".enter image description here

Weirdly if i change to

alert(data[id]);

nothing happens. but if i change to

alert(data[name]);

i get undefined again.

notANerdDev
  • 1,284
  • 11
  • 28

1 Answers1

1

Try this

$(function() {
  $('#search').keyup(function(e) {
    var val = $(this).val();
    if (val.length > 2) {
      $.get('php/search.php', {
        input: val
      }, function(data) {
        var res = $.parseJSON(data);
        if (res) alert(res["name"]);
      });
    }
  });
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236