jQuery UI Autocomplete can't figure it out - jquery-ui

I decided to use jQuery UI for my autocomplete opposed to a plugin because I read that the plugins are deprecated. My overall goal is to have an autocomplete search bar that hits my database and returns users suggestions of city/state or zipcodes in a fashion similar to google. As of now I am not even sure that the .autocomplete function is being called. I scratched everything I had and decided to start with the basics. I downloaded the most recent version of jQuery UI from http://jqueryui.com/download and am trying to get the example that they use here http://jqueryui.com/demos/autocomplete/ to work. All the scripts that I have included seem to be connected at least linked through Dreamworks so I am fairly certain that the paths I have included are correct. The CSS and Javascripts that I have included are unaltered straight from the download. Below is my HTML code and my backend PHP code that is returning JSon formated data. Please help me. Maybe I need to include a function that deals with the JSon returned data but I am trying to follow the example although I see that they used a local array.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQueryUI Demo</title>
<link rel="stylesheet" href="css/ui-lightness/jquery-ui-1.8.17.custom.css" type="text/css" />
<script type="text/javascript" src ="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src ="js/jquery-ui-1.8.17.custom.min.js"></script>
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#tags").autocomplete({
source: "search_me.php"
});
});
</script>
</head>
<body>
<div class="demo">
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</div><!-- End demo -->
<div class="demo-description">
<p>The Autocomplete widgets provides suggestions while you type into the field. Here the suggestions are tags for programming languages, give "ja" (for Java or JavaScript) a try.</p>
<p>The datasource is a simple JavaScript array, provided to the widget using the source-option.</p>
</div><!-- End demo-description -->
</body>
</html>
Below the PHP part.
<?php
include 'fh.inc.db.php';
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
$location = htmlspecialchars(trim($_GET['term'])); //gets the location of the search
$return_arr = array();
if(is_numeric($location)) {
$query = "SELECT
zipcode_id
FROM
user_zipcode
WHERE
zipcode_id REGEXP '^$location'
ORDER BY zipcode_id DESC LIMIT 10";
$result = mysql_query($query, $db) or die(mysql_error($db));
while($row = mysql_fetch_assoc($result)) {
extract($row);
$row_array['zipcode_id'] = $zipcode_id;
array_push($return_arr, $row_array);
}
}
mysql_close($db);
echo json_encode($return_arr);
?>
Thanks for the ideas. Here is an update.
I checked the xhr using firebug and made sure that it is responding thanks for that tip. also the above php code I hadn't initialized $return_arr so i took care of that. Also thanks for the clarification of the js required or rather not required. Now when I type in a zipcode a little box about a centimeter shows up underneath it but I can't see if anything is in there, I would guess not. I went to my php page and set it up to manually set the variable to "9408" and loaded the php page directly through my browser to see what it returned. This is what it returned.
[{"zipcode_id":"94089"},{"zipcode_id":"94088"},{"zipcode_id":"94087"},{"zipcode_id":"94086"},{"zipcode_id":"94085"},{"zipcode_id":"94083"},{"zipcode_id":"94080"}]
I then went to a JSON code validator at this url http://jsonformatter.curiousconcept.com/ at it informed me that my code is in fact returning JSON formatted data. Anymore suggestions to help me troubleshoot the problem would be terrific.
Wow after more research I stumbled across the answer on someone another post.
jquery autocomplete not working with JSON data
Pretty much the JSON returned data must contain Label or Value or both. Switched the zipcode_id to value in my $row_array and... boom goes the dynamite!

Your scripts (js files) references are not correct, should only be:
<!-- the jquery library -->
<script type="text/javascript" src ="js/jquery-1.7.1.min.js"></script>
<!-- the full compressed and minified jquery UI library -->
<script type="text/javascript" src ="js/jquery-ui-1.8.17.custom.min.js"></script>
The files "jquery.ui.core.js", "jquery.ui.widget.js" and "jquery.ui.position.js" are the separated development files, the jquery ui library is splitted into modules.
The file "jquery-ui-1.8.17.custom.min.js" contains them all, compressed and minified !
Concerning the data source, as stated in the "Overview" section of the Autocomplete documentation: when using a an URL, it must return json data, either of the form of:
an simple array of strings: ['string1', 'string2', ...]
or an array of objects with label (and a value - optionnal) property [{ label: "My Value 1", Value: "AA" }, ...]
I'm really not familiar with PHP so just make sure your php script returns one of those :-)

Related

How to add option in <redoc>?

I want to add some additional option to my ReDoc. For current implementation I am using json file that is generated from Swagger, and this is added in html page. Example how this is done:
<body>
<redoc spec-url='http://petstore.swagger.io/v2/swagger.json'></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc#next/bundles/redoc.standalone.js"> </script>
</body>
I use this as referent documentation: https://github.com/Rebilly/ReDoc
How can I add option object in tag and not use ReDoc object? And how can I use vendor extension e.g. x-logo?
In documentation this is set via json file, but my json file is auto generate from Swagger.
You just place the options after the spec-url in the redoc tag like this:
<body>
<redoc spec-url='http://petstore.swagger.io/v2/swagger.json' YOUR_OPTIONS_HERE></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc#next/bundles/redoc.standalone.js"> </script>
</body>
in this example on ReDoc repository you can verify it (line 22 at this moment):
https://github.com/Rebilly/ReDoc/blob/master/config/docker/index.tpl.html#L22
Important:
Remember to "kebab-casing the ReDoc options", as an example if your options are:
hideDownloadButton noAutoAuth disableSearch
YOUR_OPTIONS_HERE
should be (after kebab-casing them):
hide-download-button no-auto-auth disable-search
Your body with those options becomes like this:
<body>
<redoc spec-url='http://petstore.swagger.io/v2/swagger.json' hide-download-button no-auto-auth disable-search></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc#next/bundles/redoc.standalone.js"> </script>
</body>
Hope it will be usefull to you.
ReDoc has advanced initialization via Redoc.init so you can download the spec manually and add some postprocessing (e.g. add an x-logo).
You can pass ReDoc options as the second argument to Redoc.init:
<body>
<div id="redoc"></div>
<script src="https://cdn.jsdelivr.net/npm/redoc#next/bundles/redoc.standalone.js"> </script>
<script>
fetch('http://petstore.swagger.io/v2/swagger.json')
.then(res => res.json())
.then(spec => {
spec.info['x-logo'] = { url: "link/to/image.png" };
Redoc.init(spec, {
// options go here (e.g. pathInMiddlePanel)
}, document.getElementById('redoc'));
});
</body>
NOTE: This requires Fetch API to be available in browsers so it won't work in IE11.
You can place your options next to spec-url.
Be sure that the version of Redoc you are using, have options you want to use, you can check it by going to the specific version. github.com/Redocly/redoc/tree/vx.x.x.
As a side note features lazy-rendering in available till v1.22.3.
https://github.com/Redocly/redoc#redoc-options-object
You can use all of the following options with standalone version on tag by kebab-casing them, e.g. scrollYOffset becomes scroll-y-offset and expandResponses becomes expand-responses.

jQuery auto-complete altered to work with jQuery-Mobile

I have code written to autocomplete a text input box from a mysql database. I am currently in the process of mitigating the setup to jQuery Mobile but I am having substantial issues finding out how to write a modified autocomplete. My original html is below (heavily simplified)
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<script>
$(function() {
$( "#get_ingredient_1" ).autocomplete({source: 'search.php'});
});
</script>
<div class="ui-widget">
<input id="get_ingredient_1" name="ingredient_type" style = "width:200px">
</div>
</html>
the search.php is shown below.
<?php
//database configuration
include("db_connect.php");
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$category_query = mysqli_query($dbconnection, "SELECT DISTINCT ingredient FROM ingredients WHERE ingredient LIKE '%".$searchTerm."%' ORDER BY ingredient ASC");
//while ($row = $query->fetch_assoc()) {
while($row = mysqli_fetch_assoc($category_query)){
$data[] = $row['ingredient'];
}
//return json data
echo json_encode($data);
?>
this outputs in the format:
["Adzuki beans","Alfalfa","Allspice","Almond meal"]
ive tried to comment it accordingly. Essentially this generates a text input bot and when you start typing will try and guess what ingredient you are wanting.
unfortunatly when I alter the jquery files to:
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
It no longer autocompletes. Ive read through dozens of examples but I cant find a basic 1 input autocomplete option that I can adapt.
Can anyone shed some light on how to alter this short piece of code to autocomplete, so I can study and adapt it to its full functionality.
Ive looked at all the jquery-mobile examples but have found them lacking in the details I need here, specifically the "remote listview" as it has to populate from a file generated from a mysql source like the search.php shown above.
hope someone can help translate this to jquery mobile use.

Why do I have to mess with #Script.Render to include scripts in HTML document

It's been a nightmare to me before I came to know that in order to get jquery ui working in ASP.NET MVC I need to add #Scripts.Render("~/bundles/jqueryui"). Before doing so I kept getting Uncaught error: Undefined is not a function. What I did not understand was why on earth this would happen when I could see the jquery ui file in the sources when inspecting the html source. This is the _Layout.cshtml file:
<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.plugins.js"></script>
<script src="~/Scripts/Helpers.js"></script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
#RenderBody()
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")//Added later to get it working
#RenderSection("scripts", required: false)
</body>
</html>
In my Helper.js file I have some helper functions that I usually use. One of them is applyDatetimePickerAndFormat that is called on $(document).ready(). Inside that function I have the following code:
$('.txt-date').datepicker({
showAnim: "drop",
changeMonth: true,
changeYear: true,
dateFormat: "dd.mm.yy"
});
If I omit #Scripts.Render("~/bundles/jqueryui") in the _Layout.cshtml I will get the aforementioned error. This code works perfectly with any plain html or web form. So it seems that somehow the document can't see the contents of the jquery-ui file. To make my question concrete:
When I look at the Sources of the the web page I can see jquery-ui-1.8.24.js and it's referenced in the html source. Then why can't the code find jquery-ui functions?
If every java script file has to be specified in the #Scripts.Render then why isn't there any problem with my Helper.js file?
And finally where does this ~/bundles/jqueryui path refer to?
jquery-ui depends on jquery (i.e. it must be defined after jquery) but you have duplicated your files. In the head you have included <script src="~/Scripts/jquery-1.8.2.js"></script> followed by jquery-ui. You then reload jquery at the end of the file using #Scripts.Render("~/bundles/jquery") (Its now after jquery-ui).
Delete the script in the head and it should work. I addition, I recommend you delete jquery.validate and jquery.validate.unobtrusive from the head and use #Scripts.Render("~/bundles/jqueryval") at the end of the file (before #RenderSection..). You can examine these bundles in App_Start\BundleConfig.cs file. There are numerous advantages to using bundles (see Bundling and Minification).
If you are using all these files in every page based on _Layout, you can define your own bundle to includes all files.
You need to define the strategy for your js. I recomend you ot organize your js first and after that separate it to smaller parts. One should be common for all the pages(jQuery in your case) and other scripts for validation should be included only on pages that have some editing fileds etc.
Use DRY principle and read some information about how js works. It helps me a lot some time ago and won't take a lot of time.

JqueryMobile loading external script in body does not solve my ajax navigation issue

I see some others (e.g. this post) have had trouble using external javascript scripts in JQuery Mobile - as of today I have joined their ranks.
I have a single external js script (controllers.js) which contains code that affects several pages on the site. It is loaded on every page of the site. I put the js file just before the tag it works fine on the initial page load. However when I navigate thereafter (using the JQM Ajax methods) all functions in the script stop working. I would have thought the script would remain in cache - but heyho. Anyhow there's an FAQ which answers this question and I've implemented their suggestion which is: "...to reference the same set of stylesheets and scripts in the head of every page." I have done this but when I do even on the first page load the js doesn't fire. There aren't page specific scripts - so the remainder of that FAQ does not apply.
My cut down html looks like this:
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="stylesheet" href="/static/jquery-ui-1.10.3.custom.min.css">
<link rel="stylesheet" href="/static/jquery-mobile/css/themes/default/jquery.mobile-1.3.2.min.css">
<script src="/static/jquery-1.9.1.min.js"></script>
<script src="/static/jquery-ui/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script>
<script src="/static/jquery-mobile/js/jquery.mobile-1.3.2.min.js"></script>
<!-- CSS: implied media="all" -->
</head>
<body>
<div data-role="page" id = "main-page">
<div data-role="header" style="overflow:hidden;">
</div>
<div id = "home" data-role="content">
<input type ='button' id = "some_btn" value="press me">
</div>
</div>
<script type="text/javascript" src="/static/js/controllers.js"></script>
</body>
</html>
and within the javascript file
controllers.js
$('#some_btn').click(function()
{
alert('button pressed');
});
Any ideas on what I may be doing wrong here?
Since the content in the #page is loaded dynamically via ajax, click will not work, since it only works on elements that are on the page when the script is called.
You need to use the .on() method:
$('body').on('click','#some_btn',function()
{
alert('button pressed');
});

Simple fusioncharts in MonoTouch not working

I'm trying to embed a column3d chart from fusioncharts in my MonoTouch project using UIWebView. I've added the necessary outlets and tested by using loadrequest to load a url and loadHtmlString to format a simple line of text. This works fine. I even tested that fusionchart works correctly on my browser using the below code and it does.
I have a folder named "charts" in my MonoTouch project that contains, Column3d.swf, jquery.min.js, FusionCharts.js, FusionCharts.HC.js and FusionCharts.HC.Charts.js.
In my
ViewDidLoad
string htmlString = "<html>
<head>
<script type=\"text/javascript\"src=\"Charts/jquery.min.js\">
</script>
<script type=\"text/javascript\" src=\"Charts/FusionCharts.js\">
</script>
<script type=\"text/javascript\" src=\"Charts/FusionCharts.HC.js\">
</script>
<script type=\"text/javascript\" src=\"Charts/FusionCharts.HC.Charts.js\">
</script>
</head>
<body>
<div id=\"chartContainer\">FusionCharts will load here!
</div>
<script type=\"text/javascript\"> var myChart = new FusionCharts( \"Charts/Column3D.swf\", \"myChartId\", \"400\", \"300\", \"0\", \"1\" );myChart.setXMLUrl(\"Charts/Data.xml\");
myChart.render(\"chartContainer\");
</script>
</body>
</html>";
this.webView.LoadHtmlString (htmlString, new NSUrl ("./Charts", true));
/*string htmlString = "<html><head></head><body><span style=\"font-weight: bold;\">This</span> " +
"<span style=\"text-decoration: underline;\">is</span> <span style=\"font-style: italic;\">some formatted</span> " +"<span style=\"font-weight: bold;text-decoration: underline;\">text!</span><br></body></html>";*/ //works
//this.webView.LoadHtmlString (htmlString, null); //works
Data.xml
<chart caption='Weekly Sales Summary'
xAxisName='Week' yAxisName='Amount' numberPrefix='$'>
<set label='Week 1' value='14400' />
<set label='Week 2' value='19600' />
<set label='Week 3' value='24000' />
<set label='Week 4' value='15700' />
</chart>
Can someone explain how I can get this working? Thanks in advance.
EDIT: I also tried
string htmlString = "<html><head> <title>Creating Pure JavaScript chart</title><script type=\"text/javascript\" src=\"charts/FusionCharts.js\"></script></head> <body><div id=\"chartContainer\">FusionCharts will load here!</div> <script type=\"text/javascript\">FusionCharts.setCurrentRenderer('javascript');var myChart = new FusionCharts( \"charts/Column3D.swf\", \"myChartId\", \"400\", \"300\", \"0\", \"1\" );myChart.setXMLData(\"<chart><set label='Data1' value='1' /></chart>\"); myChart.render(\"chartContainer\"); </script></body> </html>";
where i force the renderer to use javascript and set the chart parameters in the string to no avail. Anyone?
I solved my issue and thought I would post it should someone run into a similar issue.
The first thing I did was to right click on each of my javscript files ie FusionCharts.js, FusionCharts.HC.js and FusionCharts.HC.Charts.js and set their build type to content.
I then told Monotouch the build path for the charts would be contained in the charts folder by declaring
string path = NSBundle.MainBundle.BundlePath + "/Charts/";
Since I declare i am going to look in the Charts folder for related files, I then had to amend my htmlString by removing the "charts" keyword reference from all the "src" as below (since we are already lo.
string htmlString = "<html>
<head>
<script type=\"text/javascript\" src=\"jquery.min.js\">
</script>
<script type=\"text/javascript\" src=\"/FusionCharts.js\">
</script>
<script type=\"text/javascript\" src=\"/FusionCharts.HC.js\">
</script>
<script type=\"text/javascript\" src=\"FusionCharts.HC.Charts.js\">
</script>
</head>
<body>
<div id=\"chartContainer\">FusionCharts will load here!
</div>
<script type=\"text/javascript\"> var myChart = new FusionCharts(\"Column3D.swf\", \"myChartId\", \"400\", \"300\", \"0\", \"1\" );myChart.setXMLUrl(\"Charts/Data.xml\");
myChart.render(\"chartContainer\");
</script>
</body>
</html>";
I then call the loadHtml string method as below with the second argument pointing to the path that contains the javascript files.
this.webView.LoadHtmlString(htmlString, new NSUrl(path, true));
I even tested that fusionchart works correctly on my browser using the below code and it does.
Did you test this with an iOS device running Safari ?
project that contains, Column3d.swf,
That looks like a Flash file and iOS (and WebKit) does not support flash.
The website hints of an HTML5 version - so if they support flash-less browser then you should be able to do what you want using MonoTouch (or anything in iOS) using FusionChart. Otherwise you might need to look at other charting products (or a server-side solution).
FusionCharts had put out a blog post showing how to get HTML5 charts in iOS devices.
Have a look at it here - http://blog.fusioncharts.com/2012/02/create-charts-for-iphone-and-ipad-apps-using-fusioncharts-xt/

Resources