Link to home
Start Free TrialLog in
Avatar of acbv
acbvFlag for Canada

asked on

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.
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Can you confirm that the PHP script works, for example, if you access it from the browser?
Avatar of acbv

ASKER

Yes, it works, it shows data like this:
["ANGELIC HOLISTIC HEALING","ANODYNE CHIROPRACTIC & SPORTS THERAPY","BEAUTY-WELL INC."]
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?"
Avatar of leakim971
replace :
dataType: "jsonp"
by :
dataType: "json"
Avatar of acbv

ASKER

Yes I will put the limit after.  No there is not connection, is just a text.
did you saw my comment?
Avatar of acbv

ASKER

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)
so LET jsonp
BUT replace :
echo json_encode($return);
BY :
echo $_GET["callback"] . "(" . json_encode($return) . ")";
Avatar of acbv

ASKER

Is not working on phone either...
please provide a link to your page
what to type?
I tried : new
It work but send me back an empty result : []
jQuery19108092506115790457_1383000102212([])
Avatar of acbv

ASKER

angelic
@leakim971: try "pra"
Thank you Sir Paseur
It work :
User generated image
Avatar of acbv

ASKER

Yes, it works on the website but not on my mobile device as I said, I'm using phonegap 2.9
Is not working on phone either...

wok fine for me too, clear your browser cache :
User generated image
Avatar of acbv

ASKER

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.)
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
Avatar of acbv

ASKER

Yes it says:
parseerror
Error:
jQuery19108143491349183023_1383013785122 was not called
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

Avatar of acbv

ASKER

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

what do you get?
Avatar of acbv

ASKER

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

alert('ok');
$.ajax(...
Avatar of acbv

ASKER

I put all the ajax code back and the alert, on the phone appears a window saying:  
index.html
ok
(but not results showing)
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

Avatar of acbv

ASKER

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.
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

Avatar of acbv

ASKER

On the phone:
parseerror
SyntaxError: JSON parse error:
Unrecognized token '<'
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of acbv

ASKER

I put the full path of the search.php file & jsonp & crossdomain
Now it gives a parseerror
JQuery 191003.......(etc) was not called
Avatar of acbv

ASKER

and yes is working with the link from the demo
Avatar of acbv

ASKER

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!
@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!