2

Here I am trying to implement the jQuery I have two main files one is db.php which hold this thing:

<?php

$connection = mysql_connect("localhost","root","");
$db = mysql_select_db("auto",$connection);

$sql = "SELECT * FROM data";

$result = mysql_query($sql,$connection);
//$arr = array();
while($row = mysql_fetch_array($result)){

echo $row['name']."\n";
}
//echo json_encode($arr);

mysql_close($connection);
?>

Then I have another file named as index.html in which I am calling jQuery functions:

<html>
<head>
<link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.8.custom.css">
<link rel="stylesheet" type="text/css" href="css/autocomplete.css">
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.custom.min.js"></script>
<script>

$(document).ready(function(){
    $("#example").autocomplete("db.php");
  });

</script>
</head>

<body>

Auto:<input id="example" type="text">

</body>
</html>

but I am unable to run any code can you tell me why? I am newbie to jQuery so apology for mistakes.

P.S: I tried with json encode function because I search and find out it may be reason of Json data (which I was assigning to $arr then echoing the jsonencode) but still its not working.

3 Answers 3

2

jQuery-ui autocomplete can probe a server side script for autocomplete data but the script must return that data in JSON format in either of these two variations:

An Array of Strings:

[ "Choice1", "Choice2" ]

An Array of Objects with label and [or] value properties:

[ { label: "Choice1", value: "value1" }, ... ]

So you need to revise your PHP code a little -- the json_encode was the right thing to do:

$arr = array();
while($row = mysql_fetch_array($result)){
    $arr[] = $row["name"];
}
echo json_encode($arr);

A little fix needed in your JavaScript too:

    $( "#example" ).autocomplete({
        source: "db.php"
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a Bunch mate actually i found out that i didn't include a Jquery UI Css file as well that was the reason i was having problems....
1

I can suggest you to

  1. install the Firebug extensio and please use Mozilla browser to help you to debug this kind of problem.
  2. Make sure there is no javascript or jquery syntax error by debugging it in Firebug.
  3. Make sure that your application made the request to db.php, you can see it in the firebug console.

I noticed that your jQuery syntax was wrong. See here for reference: http://jqueryui.com/demos/autocomplete/#remote

Please notice there, that were none of them have specified the string directly, always included the source attribute.

It could be that you forgot to specify the "source" attribute.

Good luck.

1 Comment

Thanks a Bunch mate actually i do have firebug it was showing me error of Jquery Library but i found out that i didn't include a Jquery UI Css file as well that was the reason i was having problems....
0

Ok Here is what i come up with the solution I am posting this in answer so that if any other person have problems using this can understand the basic without running around and messing head like me you can take this as a Short Simple Tutorial for Using a Jquery UI Autocomplete:

First Make a Database Name auto in your mysql Server and Put this Dump Query in SQL or create a file named auto.sql and put all following content in that file and import it from phpmyadmin by going inside that database you just created i.e "auto":

-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 27, 2012 at 06:35 PM
-- Server version: 5.5.24-log
-- PHP Version: 5.3.13

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `auto`
--

-- --------------------------------------------------------

--
-- Table structure for table `data`
--

CREATE TABLE IF NOT EXISTS `data` (
  `name` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `data`
--

INSERT INTO `data` (`name`) VALUES
('fahim'),
('asim'),
('yasir'),
('jalil'),
('birdy'),
('gudu'),
('zalim'),
('papu'),
('ozair'),
('saima');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Now make a Folder in your XAMPP or WAMP or any web server your using as auto and make following files and put their Contents in respective order:

First File is db.php:

 <?php

    $connection = mysql_connect("localhost","root",""); 
//make sure you change the hostname, username and password according to your setting
    $db = mysql_select_db("auto",$connection);

    $sql = "SELECT * FROM data";

    $result = mysql_query($sql,$connection);
    $arr = array();
    while($row = mysql_fetch_array($result)){

    $arr[] = $row['name']."\n";
    }
    echo json_encode($arr);

    mysql_close($connection);


    ?>

Make another File with name index.php and put following content:

<html>
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/black-tie/jquery-ui.css" type="text/css" />
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js'></script>
<script>

$(document).ready(function() {
        $( "#AC" ).autocomplete({
            source: "db.php"
        });
    });

</script>
</head>

<body>

 <form>
     Text Box: <input id="AC" type="text" />
    </form>
</body>
</html>

Another thing Notice i am using Online Google API to retrieve the Script Libraries and CSS file so make sure before testing this code you are connected to internet.

Try to Run the Code it will Run Like a Charm :)....Its pretty simple for a newbie as well thats why i didn't explained it...just a simple term i am getting data from database and make all that data echo in jason format because Jquery UI Auto complete require by default the Jason data!!

Hope it helps :)


Another thing i noticed that in firebug that whenever i type something This Autocomplete sends a Ajax request to the Db page from where i am getting the result and in that request it sends a variable name term so if i get that variable in the db.php file i can also use that into my SQL to retrieve Specific String because in above method it will show all the records retrieved from database so if i want to get only Specific terms like for example i put a word "fa" in the text box in the index.html file i want it retrieve only those name from the database which hold the string "fa" for that i can use that $_GET['term'] variable and put it in the SQL statement there i can use SQL LIKE operator to find a certain pattern i will update the db.php file as below:

<?php

    $connection = mysql_connect("localhost","root",""); 
//make sure you change the hostname, username and password according to your setting
    $db = mysql_select_db("auto",$connection);

    $sql = "SELECT * FROM data WHERE name LIKE '%".$_GET['term']."%'";

    $result = mysql_query($sql,$connection);

    //print_r ($result);

    $arr = array();
    while($row = mysql_fetch_array($result)){

    $arr[] = $row['name']."\n";
    }
    echo json_encode($arr);

    mysql_close($connection);


    ?>

Now what i am doing i am saying to SQL get me the names which have the patter of string that $_GET['term'] is retrieving :)....!! T*his is simple Right* ??

If you want to know more about LIKE operator Check This Link http://www.w3schools.com/sql/sql_like.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.