Jquery mobile autocomplete with PHP

I took the example from the Jquery Mobile page:
http://view.jquerymobile.com/1.3.2/dist/demos/widgets/autocomplete/autocomplete-remote.html
But in that case it search the data to a Mysql db with PHP & Json
I tested the Json data (firebug & json lint) and when I type the text it shows the results on firebug but nothing is showing on the results!!!!
Here's my code:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="jquery-mobile/index.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery-1.9.1.min.js" type="text/javascript"></script>
<link href="themes/synergy.min.css" rel="stylesheet" type="text/css"/>
<link href="jquery-mobile/jquery.mobile.structure-1.3.2.min.css" rel="stylesheet" type="text/css"/>
<link href="css/custom.css" rel="stylesheet" type="text/css">
<script src="jquery-mobile/jquery.mobile-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).bind("mobileinit",function(){
	$.mobile.page.prototype.options.addBackBtn = true;
});
</script>	
<style>
.ui-listview-filter-inset {
    margin-top: 0;
}
</style>
</head> 
<body> 

  
 <!--Page search-->
<div data-role="page" id="searchPage" data-theme="c">
	<div data-role="header" data-position="fixed">
		<img src="images/logo.png"/>
	</div>
   
	<div data-role="content">

	<h3>Cities worldwide</h3>
<p>After you enter <strong>at least three characters</strong> the autocomplete function will show all possible matches.</p>
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Find a city..." data-filter-theme="c"></ul>
		
	</div>
		  	
    
	<div data-role="footer" data-position="fixed"  data-id="my-footer">
    <div data-role="navbar" class="nav-glyphish-example" data-grid="d">
		<ul>
        <li><a href="#contactPage" id="about" data-icon="custom" data-theme="c">About</a></li>
        <li><a href="index.html" id="browse" data-icon="custom" data-theme="c">Browse</a></li>
        <li><a href="#eventsPage" id="events" data-icon="custom" data-theme="c">Events</a></li>				
		<li><a href="javascript:void(0)" onclick="window.open('http://issuu.com/guidedsynergy', '_system')"; id="magazine" data-icon="custom"data-theme="c">Magazine</a></li>
        <li><a href="#searchPage" id="search" data-icon="custom" data-theme="c">Search</a></li>	
			
		</ul>
	</div>
		<h4>Copyright</h4>
	</div>
</div>


	<script type="text/javascript">
$( document ).on( "pageinit", "#searchPage", function() {
    $( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
        var $ul = $( this ),
            $input = $( data.input ),
            value = $input.val(),
            html = "";
        $ul.html( "" );
        if ( value && value.length > 2 ) {
            $ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
            $ul.listview( "refresh" );
            $.ajax({
                url: "services/search.php",
                dataType: "jsonp",
                crossDomain: true,
                data: {
                    term: $input.val()
                }
            })
            .then( function ( response ) {
                $.each( response, function ( i, val ) {
                    html += "<li>" + val + "</li>";
                });
                $ul.html( html );
                $ul.listview( "refresh" );
                $ul.trigger( "updatelayout");
            });
        }
    });
});
</script>
</body>
</html>

Here's the PHP:
<?php
header('Content-Type: application/json', true);
include 'config.php';
//connection to the database
$conn = mysql_connect($dbhost, $dbuser, $dbpass)
  or die("Unable to connect to MySQL");


//select a database to work with
$selected = mysql_select_db($dbname,$conn)
  or die("Could not select directory2");
  
  	$search = $_GET['term']; 
	$return = array();
    $query = mysql_query("SELECT business FROM `directory2` WHERE `business` LIKE '%$search%' ORDER BY business ASC") or die('Something went wrong');

    while ($row = mysql_fetch_array($query)) {
    $return[]= $row['business'];
}
echo json_encode($return) ;

?>

Open in new window


Thanks a lot for your help.
acbvAsked:
Who is Participating?
 
leakim971PluritechnicianCommented:
when using phonegap you get back a strange content... maybe a 404 error because the path is not good

so use a FULL path
do a try with the URL provided on the example here :
http://view.jquerymobile.com/1.3.2/dist/demos/widgets/autocomplete/autocomplete-remote.html
It should work then try the path to your webserver, FULL PATH to the URL
Use JSONP and not JSON so back the dataType:'jsonp' and crossDomain:true
0
 
Ray PaseurCommented:
Can you confirm that the PHP script works, for example, if you access it from the browser?
0
 
acbvAuthor Commented:
Yes, it works, it shows data like this:
["ANGELIC HOLISTIC HEALING","ANODYNE CHIROPRACTIC & SPORTS THERAPY","BEAUTY-WELL INC."]
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
Ray PaseurCommented:
Just a comment, not a solution, but the query in the PHP script should probably have a LIMIT clause.

Is there any connection between the placeholder saying "Find a city" and the PHP query looking for a column named "business?"
0
 
leakim971PluritechnicianCommented:
replace :
dataType: "jsonp"
by :
dataType: "json"
0
 
acbvAuthor Commented:
Yes I will put the limit after.  No there is not connection, is just a text.
0
 
leakim971PluritechnicianCommented:
did you saw my comment?
0
 
acbvAuthor Commented:
changing to dataType:"json" made it work on the website, but when I tested on my Iphone (trough phone gap 2.9) doesn't show any results.....
(I tested the same way the demo of the example,  with the link the the demo has, the geobytes autocomplete link and it works on my iPhone)
0
 
leakim971PluritechnicianCommented:
so LET jsonp
BUT replace :
echo json_encode($return);
BY :
echo $_GET["callback"] . "(" . json_encode($return) . ")";
0
 
acbvAuthor Commented:
Is not working on phone either...
0
 
leakim971PluritechnicianCommented:
please provide a link to your page
0
 
leakim971PluritechnicianCommented:
what to type?
I tried : new
It work but send me back an empty result : []
jQuery19108092506115790457_1383000102212([])
0
 
acbvAuthor Commented:
angelic
0
 
Ray PaseurCommented:
@leakim971: try "pra"
0
 
leakim971PluritechnicianCommented:
Thank you Sir Paseur
It work :
work
0
 
acbvAuthor Commented:
Yes, it works on the website but not on my mobile device as I said, I'm using phonegap 2.9
0
 
leakim971PluritechnicianCommented:
Is not working on phone either...

wok fine for me too, clear your browser cache :
iphone
0
 
acbvAuthor Commented:
I'm testing uploading the application on phonegap and then downloading that on my Iphone. I'm not using Xcode.  I don't think cleaning the browser cache has something to do, but anyway I did it (cleaned Safari cache) and it didn't help.

(The strange thing is that I tested the original demo from the jquery mobile page (which doesn't use php) and uploaded to phonegap and then tested in my iphone and it worked.)
0
 
leakim971PluritechnicianCommented:
replace :
$.ajax({
                url: "services/search.php",
                dataType: "jsonp",
                crossDomain: true,
                data: {
                    term: $input.val()
                }
            })

Open in new window

by :
$.ajax({
                url: "services/search.php",
                dataType: "jsonp",
                crossDomain: true,
                data: {
                    term: $input.val()
                },
                error:function(jqXHR, textStatus, errorThrown ) {  alert(textStatus + '\n' + errorThrown); }
            })

Open in new window


you should get the error
0
 
acbvAuthor Commented:
Yes it says:
parseerror
Error:
jQuery19108143491349183023_1383013785122 was not called
0
 
leakim971PluritechnicianCommented:
replace :
$.ajax({
                url: "services/search.php",
                dataType: "jsonp",
                crossDomain: true,
                data: {
                    term: $input.val()
                },
                error:function(jqXHR, textStatus, errorThrown ) {  alert(textStatus + '\n' + errorThrown); }
            })
.then( function ( response ) {
                $.each( response, function ( i, val ) {
                    html += "<li>" + val + "</li>";
                });
                $ul.html( html );
                $ul.listview( "refresh" );
                $ul.trigger( "updatelayout");
            });

Open in new window

by :
window.a = function(response) { alert(typeof response); }
$.getScript("services/search.php?callback=a&term="+$input.val()+"&t="+new Date().getTime())

Open in new window

0
 
acbvAuthor Commented:
Did the change, on the web appears a window with the word object
On the phone nothing happens.
0
 
leakim971PluritechnicianCommented:
great, now replace :
window.a = function(response) { alert(typeof response); }
by :
window.a = function(response) { alert( JSON.stringify(response) ); }

what do you get?
0
 
acbvAuthor Commented:
On the web: I get the results on a window
Nothing on the phone
0
 
leakim971PluritechnicianCommented:
if you place an alert before the ajax call, do you get it on the phone?

alert('ok');
$.ajax(...
0
 
acbvAuthor Commented:
I put all the ajax code back and the alert, on the phone appears a window saying:  
index.html
ok
(but not results showing)
0
 
leakim971PluritechnicianCommented:
On the web: I get the results on a window
Nothing on the phone

That mean your php script don't return a script when you call from your phonegap application
You need to check logs on the server to check what is the request received by your php script.

Try to set the header in your php script (first line of your script) :
header('Content-Type: application/javascript');

Open in new window


additionay try a simple php script :

<?php
header('Content-Type: application/javascript');
echo $_GET["callback"] . '(["ANGELIC HOLISTIC HEALING","ANODYNE CHIROPRACTIC & SPORTS THERAPY","BEAUTY-WELL INC"])';
?>

Open in new window

0
 
acbvAuthor Commented:
tried that, same stuff, I left the alert line there, still says index.html ok
I turned on the error logs on the server (godaddy) but they will be available after 24 hrs.
0
 
leakim971PluritechnicianCommented:
let this (json and not jsonp, crossdomain attribute removed):
$.ajax({
                url: "services/search.php",
                dataType: "json",
                data: {
                    term: $input.val()
                },
                error:function(jqXHR, textStatus, errorThrown ) {  alert(textStatus + '\n' + errorThrown); }
            })
.then( function ( response ) {
                $.each( response, function ( i, val ) {
                    html += "<li>" + val + "</li>";
                });
                $ul.html( html );
                $ul.listview( "refresh" );
                $ul.trigger( "updatelayout");
            });

Open in new window

with :
<?php
header('Content-Type: application/javascript');
echo '["ANGELIC HOLISTIC HEALING","ANODYNE CHIROPRACTIC & SPORTS THERAPY","BEAUTY-WELL INC"]';
?>

Open in new window

0
 
acbvAuthor Commented:
On the phone:
parseerror
SyntaxError: JSON parse error:
Unrecognized token '<'
0
 
acbvAuthor Commented:
I put the full path of the search.php file & jsonp & crossdomain
Now it gives a parseerror
JQuery 191003.......(etc) was not called
0
 
acbvAuthor Commented:
and yes is working with the link from the demo
0
 
acbvAuthor Commented:
OH! I changed the search.php back to the original and IS WORKING!!!!!
So it was the URL!!!!
Thank you, thank you, thank you! leakim971, you are my hero!
0
 
Ray PaseurCommented:
@leakim971: That's a classic example of why I'm a member of EE.  Insight, perseverance, the right questions and an excellent solution.  Nicely done!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.