Solved

Jquery mobile autocomplete with PHP

Posted on 2013-10-28
35
2,997 Views
Last Modified: 2013-10-29
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.
0
Comment
Question by:acbv
  • 17
  • 14
  • 4
35 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39606739
Can you confirm that the PHP script works, for example, if you access it from the browser?
0
 

Author Comment

by:acbv
ID: 39606763
Yes, it works, it shows data like this:
["ANGELIC HOLISTIC HEALING","ANODYNE CHIROPRACTIC & SPORTS THERAPY","BEAUTY-WELL INC."]
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39606775
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
 
LVL 82

Expert Comment

by:leakim971
ID: 39606807
replace :
dataType: "jsonp"
by :
dataType: "json"
0
 

Author Comment

by:acbv
ID: 39606812
Yes I will put the limit after.  No there is not connection, is just a text.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39606834
did you saw my comment?
0
 

Author Comment

by:acbv
ID: 39606881
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
 
LVL 82

Expert Comment

by:leakim971
ID: 39607170
so LET jsonp
BUT replace :
echo json_encode($return);
BY :
echo $_GET["callback"] . "(" . json_encode($return) . ")";
0
 

Author Comment

by:acbv
ID: 39607192
Is not working on phone either...
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39607194
please provide a link to your page
0
 

Author Comment

by:acbv
ID: 39607228
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39607240
what to type?
I tried : new
It work but send me back an empty result : []
jQuery19108092506115790457_1383000102212([])
0
 

Author Comment

by:acbv
ID: 39607245
angelic
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39607246
@leakim971: try "pra"
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39607256
Thank you Sir Paseur
It work :
work
0
 

Author Comment

by:acbv
ID: 39607260
Yes, it works on the website but not on my mobile device as I said, I'm using phonegap 2.9
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39607306
Is not working on phone either...

wok fine for me too, clear your browser cache :
iphone
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:acbv
ID: 39607337
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
 
LVL 82

Expert Comment

by:leakim971
ID: 39607361
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
 

Author Comment

by:acbv
ID: 39607607
Yes it says:
parseerror
Error:
jQuery19108143491349183023_1383013785122 was not called
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39608269
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
 

Author Comment

by:acbv
ID: 39609060
Did the change, on the web appears a window with the word object
On the phone nothing happens.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39609068
great, now replace :
window.a = function(response) { alert(typeof response); }
by :
window.a = function(response) { alert( JSON.stringify(response) ); }

what do you get?
0
 

Author Comment

by:acbv
ID: 39609187
On the web: I get the results on a window
Nothing on the phone
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39609218
if you place an alert before the ajax call, do you get it on the phone?

alert('ok');
$.ajax(...
0
 

Author Comment

by:acbv
ID: 39609309
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
 
LVL 82

Expert Comment

by:leakim971
ID: 39609367
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
 

Author Comment

by:acbv
ID: 39609517
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
 
LVL 82

Expert Comment

by:leakim971
ID: 39609572
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
 

Author Comment

by:acbv
ID: 39609635
On the phone:
parseerror
SyntaxError: JSON parse error:
Unrecognized token '<'
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 39609656
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
 

Author Comment

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

Author Comment

by:acbv
ID: 39609752
and yes is working with the link from the demo
0
 

Author Comment

by:acbv
ID: 39609776
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
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39609827
@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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Batch, VBS, and scripts in general are incredibly useful for repetitive tasks.  Some tasks can take a while to complete and it can be annoying to check back only to discover that your script finished 5 minutes ago.  Some scripts may complete nearly …
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now