Codeigniter Autocomplete from Database - javascript

I have some problems in my project. I am trying to do autocomplete with JavaScript in CodeIgniter. I already tried many options, but they don't work!
The controller:
public function getResult($referencia){
if(!empty($referencia) || isset($referencia))
{
$this->db->like('referencia', $referencia);
echo json_encode( $this->db->get('produto_servico_tbl')->result());
}
}
The autocomplete.js (created by me):
$(document).ready(function(){
$('#search').keypress(function(e){
if(e.which == 13)
{
e.preventDefault();
}
var searched = $('#search').val()
var fullurl = $('#hiddenurl').val() + 'autoComplete_v.php/autoComplete_c/getResult/' + searched
$.getJSON(fullurl,function(result){
//display suggestion code goes here
var elements = [];
$.each(result, function(i, val){
elements.push(val.referencia)
})
$('#search').autocomplete({
source : elements
})
})
})
})
The view:
<head>
<link href="<?=base_url()?>css/ui-lightness/jquery-ui-1.10.3.custom.css" media="screen" type="text/stylesheet" rel="stylesheet" />
<form>
<label for="search">Search</label>
<input id="search" type="text"/>
<input value="<?=base_url()?>" id="hiddenurl" type="hidden">
<input type="submit" value="submit"/>
</form>
<script src="<?=base_url()?>js/jquery-1.9.1.js" type="text/javascript"></script>
<script src="<?=base_url()?>js/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script src="<?=base_url()?>js/jquery-ui-1.10.3.custom" type="text/javascript"></script>
<script src="<?=base_url()?>js/autocomplete.js" type="text/javascript"></script>

You are giving the wrong URL for the AJAX call.
Change this line:
var fullurl = $('#hiddenurl').val() + 'autoComplete_v.php/autoComplete_c/getResult/' + searched
Here $('#hiddenurl').val() is your base_url(). So the complete URL will be:
var fullurl = $('#hiddenurl').val() + 'controller_class_name/getResult/' + searched
In CodeIgniter your URL is like this:
base_url/controller_class_name/method_name/parameter1/parameter2....
Your autocomplete_v.php will produce an error. You can check how your JavaScript is working with Firebug.

Related

direct user to php page with javascript + an id

I am very new to javascript - mainly only used it to go back a page or go to a link ..
I got it working on the example page, now I'm trying to get it to work on my website ... However nothing occurs when the link is pressed...
The files exist in their linked locations. The script is copied from the example.
HEADER:
<script type="text/javascript" src="js/jquery-impromptu.min.js"></script>
<link rel="stylesheet" media="all" type="text/css" href="css/jquery-impromptu.css" />
<script type="text/javascript">
function removeUser(id){
var txt = 'Are you sure you want to remove this user?<input type="hidden" id="userid" name="userid" value="'+ id +'" />';
$.prompt(txt,{
buttons:{Delete:true, Cancel:false},
close: function(e,v,m,f){
if(v){
var uid = f.userid;
window.location = "deletemember.php?id=" + id;
}
else{}
}
});
}
</script>
LINK :
<a href='javascript:;' onclick='removeUser(544666);'>Delete</a>
Check this demo: https://github.com/trentrichardson/jQuery-Impromptu/blob/master/demos/user_manager.html
What you should do is make a function. This function is called when a user does something, but it should contain an ID. For example:
Edit
So, as you can see you will call the function 'editUser(4)' where 4 is the ID.
Back to JS
function editUser(id){
}
In this function you add your part, and you end up with this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="../jquery-impromptu.js"></script>
<script type="text/javascript">
function removeUser(id){
var user = $('#userid'+id)
var fname = user.find('.fname').text();
var lname = user.find('.lname').text();
var txt = 'Are you sure you want to remove this user with id: '+id+'?';
$.prompt(txt,{
buttons:{Change:true, Cancel:false},
submit: function(e,v,m,f){
var flag = true;
if (v) {
window.location = "deletemember.php?id=" + id;
}
return flag;
}
});
}
</script>
<a href='javascript:;' onclick='removeUser(544666);'>Delete</a>
Now the ID is useable for your window.location.
Use window.location.href or window.location.replace:
<script type="text/javascript">
function removeUser(id) {
var txt = 'Are you sure you want to remove this user?<input type="hidden" id="userid" name="userid" value="' + id + '" />';
$.prompt(txt, {
buttons: {
Delete: true,
Cancel: false
},
close: function (e, v, m, f) {
if (v) {
var uid = f.userid;
//window.location.href = "deletemember.php?id=" + uid;
window.location.replace("deletemember.php?id=" + uid);
} else {}
}
});
}
</script>
You can read about the difference here.

Javascript/JSON error: not well formed

I am testing putting a text editor on my page and storing it as part of a JSON object.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://tinymce.cachefly.net/4.0/tinymce.min.js" type="text/javascript"> </script>
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
<link rel="stylesheet" href="/jquery.mobile-1.3.2.min.css"/>
<script src="/jquery-1.9.1.min.js"></script>
<script src="/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<form method="post" action="formSubmit.js">
<textarea name ="editor"></textarea>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
JS
$(document).ready(function () {
var text = $("editor").val();
var name = "project name";
var id = 5;
var item = new item(name, text, id);
var itemArray = localStorage.items;
if (itemArray == undefined) {
itemArray = [];
} else {
itemArray = JSON.parse(itemArray);
}
itemArray.push(item);
localStorage.items = JSON.stringify(itemArray);
});
I want to be able to store item in a JSON object. When I run this I receive a "not-well formed" error at line 1 of the Javascript. It's a very simple program I'm running and can't seem to pinpoint what is causing the error. Is the JSON done incorrectly or are scripts in my HTML header causing issues?
$("editor") is looking for an html tag called 'editor'. you probably want to attach an id attribute to your and do $('#editor')

jQuery adding to JSP page

I have a piece of jQuery code which I found on the internet and I want to integrate it to my jsp page, I use Spring form tags.
Here is the jQuery code:
(function ($) {
//тут превращаем select в input
var id = "test",
$id = $('#' + id),
choices = $id.find('option').map(function (n, e) {
var $e = $(e);
return {
id: $e.val(),
text: $e.text()
};
}),
width = $id.width(),
realClass = $id.get(0).className,
realId = $id.get(0).id,
$input = $('<input>',{width: width});
$id.after($input);
$id.hide();
$id.find('option').remove();
//превратили
$input.select2({
query: function (query) {
var data = {}, i;
data.results = [];
// подтставим то что искали
if (query.term !== "") {
data.results.push({
id: query.term,
text: query.term
});
}
// добавим остальное
for (i = 0; i < choices.length; i++) {
if (choices[i].text.match(query.term) || choices[i].id.match(query.term)) data.results.push(choices[i]);
}
query.callback(data);
}
}).on('change',function()
{
var value=$input.val();
$id.empty();
$id.append($('<option>').val(value))
$id.val(value);
}
);
})(jQuery);
CSS file for jQuery - I name it test.css and apply it to my jsp page:
#test {
width: 300px;
}
My jsp page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
<title>Страница выборки</title>
<link rel="stylesheet" href="resources/cssFiles/jquery-ui.css"/>
<link rel="stylesheet" href="resources/cssFiles/test.css"/>
<script type="text/javascript" src="resources/jsFiles/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="resources/jsFiles/jquery-ui.js"></script>
<script type="text/javascript" src="resources/jsFiles/jquery-ui-i18n.js"></script>
<script type="text/javascript" src="./resources/jsFiles/selecter.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#parctdate, #chldAdmitDate, #chldSchlDate, #name, #type, #daySchdl, #workSchdl, #rotation, #numbch, #chUnder3, #chUpper3, #chGoSchool, #chAdmitted").mouseenter(function() {
$(this).css("background-color", "gainsboro");
});
$("#parctdate, #chldAdmitDate, #chldSchlDate, #name, #type, #daySchdl, #workSchdl, #rotation, #numbch, #chUnder3, #chUpper3, #chGoSchool, #chAdmitted").mouseleave(function() {
$(this).css("background-color", "white");
});
var enabledDays = ["6-1-2013", "7-1-2013", "8-1-2013", "9-1-2013", "10-1-2013", "11-1-2013"];
function nationalDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < enabledDays.length; i++) {
if($.inArray((m+1) + '-' + d + '-' + y,enabledDays) != -1 || new Date() > date) {
return [true];
}
}
return [false];
}
$(function(){
$.datepicker.setDefaults($.extend($.datepicker.regional["ru"]));
$("#datepicker1, #datepicker2, #datepicker3").datepicker({dateFormat: "yy-mm-dd",
duration: "normal",
numberOfMonths: [ 1, 2 ],
constrainInput: true,
beforeShowDay: nationalDays});
});
});
</script>
</head>
<body>
<spring:message code="label.input.button" var="labelbutton"/>
<h3 align="center"><spring:message code="label.input.topLabel"/></h3>
<form:form id="myform" cssClass="testClass" modelAttribute="fboAttribute" method="post" action="add" >
<table align="center">
<tr id="name">
<td><form:label path="institution.nameOfInstitution"><spring:message code="label.input.nameOfInstitution"/></form:label>
<form:select id="test" path="institution.nameOfInstitution">
<form:option value=""><spring:message code="label.select.msg" />-</form:option>
<form:options items="${listOfInstitutionsNames}"/>
</form:select>
<tr>
<td><input type="submit" value="${labelbutton}"/></td>
</table>
</form:form>
I would like to integrate my jQuery scripts with my jsp and Spring form tags.
I'm sorry I'm new in jQuery.
Thank you
jQuery, like any JavaScript, is added in a <script> tag in the <head> tag of your JSP page. You either add all the code or just a link to the .js file containing your jQuery, like for example :
<script src="./libs/jquery/1.10.1/jquery.min.js"></script>
Having done that, you want now to leverage your jQuery in the HTML tags, you do that as for any HTML page. Namely, in your case, you don't have to take away the spring tags. Let it generate the select/options via your ${listOfInstitutionsNames}, just add class="testclass" to your spring form tag, like this :
<form:form cssClass="testclass" id="myform" modelAttribute="fboAttribute" method="post" action="add" >
When rendering the form on a browser, Spring will include in the generated HTML the class attribute with value of testclass.
Hope that helps, best of luck.
For Dynamic Web Project(designed using MVC Model)
Add like this in head section:
<script type="text/javascript" src="${pageContext.request.contextPath}/jQuery.js"/></script>
I kept my jQuery.js in WebContent folder(with jsp pages).
if what you mean is that you want to bind Java side information to JS var, you can do as I did:
At Java side, use Google's Gson to encode Java object to Json string.
At Java side, use org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(String) to make you Json string escaped as JavaScript.
At JSP side, do something like this:
<script>
var jsonObject = JSON.parse("<%=yourJsonString%>");
</script>

Retrieve results from SOLR using jquery calls

I am working to get response from SOLR using jquery. When I use the below code I got the error saying Typeerror:data is null
When looked at the code in firebug, data in on_data function is null. I think I am missing something in the Solr URL.The URL I am using is http://xxxx.xxx.xxxx.xxx/xxx_xxx/core0/selectcore0/select/?q=%3A&version=2.2&start=0&rows=10&indent=on&wt=json.
Can you please take a look at my code, and also suggest me the URL style in the code
<html>
<head>
<title>Solr Search</title>
</head>
<body>
<h3>Solr Search</h3>
Query: <input id="query" />
<button id="search">Search</button>
<hr/>
<div id="results">
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function on_data(data) {
$('#results').empty();
var docs = data.response.docs;
$.each(docs, function(i, item) {
$('#results').prepend($('<div>' + item.name + '</div>'));
});
var total = 'Found ' + docs.length + ' results';
$('#results').prepend('<div>' + total + '</div>');
}
function on_search() {
var query = $('#query').val();
if (query.length == 0) {
return;
}
var url='http://xxxx.xxx.xxxx.xxx/xxx_xxx/core0/selectcore0/select/?q='+query+'&version=2.2&start=0&rows=50&indent=on&wt=json';
$.getJSON(url, on_data);
}
function on_ready() {
$('#search').click(on_search);
/* Hook enter to search */
$('body').keypress(function(e) {
if (e.keyCode == '13') {
on_search();
}
});
}
$(document).ready(on_ready);
</script>
Here is the working version of your code, and list of changes:
1) added wrf: adds a wrapper-function around the JSON response, useful in AJAX with dynamic script tags for specifying a JavaScript callback function
2) added callback: need to use JSONP instead of an ordinary JSON request, due to JavaScript’s cross-domain security restrictions.
<html>
<head>
<title>Solr Search</title>
</head>
<body>
<h3>Solr Search</h3>
Query: <input id="query" />
<button id="search">Search</button>
<hr/>
<div id="results">
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function on_data(data) {
$('#results').empty();
var docs = data.response.docs;
$.each(docs, function(i, item) {
$('#results').prepend($('<div>' + item.name + '</div>'));
});
var total = 'Found ' + docs.length + ' results';
$('#results').prepend('<div>' + total + '</div>');
}
function on_search() {
var query = $('#query').val();
if (query.length == 0) {
return;
}
var url='http://xxxx.xxx.xxxx.xxx/xxx_xxx/core0/selectcore0/select/?q='+query+'&version=2.2&start=0&rows=50&indent=on&wt=json&callback=?&json.wrf=on_data';
$.getJSON(url);
}
function on_ready() {
$('#search').click(on_search);
/* Hook enter to search */
$('body').keypress(function(e) {
if (e.keyCode == '13') {
on_search();
}
});
}
$(document).ready(on_ready);
</script>
Since you are using $.getJSON, you might need to add &wt=json to your query.
So your query should be: http://xxxx.xxx.xxxx.xxx/xxx_xxx/core0/selectcore0/select/?q=search_query&version=2.2&start=0&rows=10&indent=on&wt=json
By default Solr gives XML response. You need to specify if you need JSON response by adding &wt=json
Mode detail: http://wiki.apache.org/solr/SolJSON
I have installed solr 5.2.1: item.name in the function on_data is not provided anymore. I used item.id and it worked.

How do you use $('document').ready(function()) in jQuery?

I have a piece of code that is working fine in IE, but it doesn’t run in Firefox. I think the problem is that I have not been able to implement $('document').ready(function). The structure of my json is like [{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}].
I will be very thankful if someone can see my code & help me in correctly implementing it. Here is my code:
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2
/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$.getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
$.each(jsonData, function (i, j) {
document.form1.fruits.options[i] = new Option(j.options);
});});
});
</script></head>
<body><form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" /></form></body>
</html>
Short version (suggested by meeger): don't use single quotes around document.
document is a variable that comes with JavaScript (at least in the browser context). Instead, try the following for the relevant line.
$(document).ready(function() {
You'll also want to take the onLoad attribute off of the body tag, else it will run twice.
Just run $(document).ready(function() {doStuff}). This will automatically run when the document is ready.
It's best practice, at least in my opinion, that you don't put any events in the html itself. This way you separate the structure of an html document from it's behavior. Instead attach events in the $(document).ready function.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var selectElem = $('#fruits');
for(var i = 0; i < jsonData.length; i++) {
selectElem.append($('<option>').html(jsonData[i].options));
}
});
});
</script>
</head>
<body>
<form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" />
</form>
</body>
</html>
EDIT:
I tested with the following and mocked the json object since I can't make that call myself.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var jsonData = JSON.parse('[{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]');
var selectElem = $('#fruits');
for(var i = 0; i < jsonData.length; i++) {
selectElem.append($('<option>').html(jsonData[i].options));
}
});
</script>
</head>
<body>
<form name="form1">
My favourite fruit is :
<select name="fruits" id="fruits" />
</form>
</body>
</html>
Here it is in all its glory. The shorthand, awesome version:
UPDATED
<script type="text/javascript" language="javascript">
$(function() {
$.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var cacheFruits = $('#fruits'),
cacheOption = $(document.createElement('option'));
$.each(jsonData, function (i, j) {
cacheFruits.append(
cacheOption.clone().attr('value', j.options).html(j.options)
);
});
});
});
</script>
Of course, I don't know what your JSON structure is, so you may need to play around with the append section of the code.
There should be no reason why the above would not work.
You do not need quotes around document. Once the page has completely loaded, it will start executing whatever you have defined in ready()
$(document).ready(function() {
$(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
$(this).each(jsonData, function (i, j) {
document.form1.fruits.options[i] = new Option(j.options);
});
});
});
Try this, your json data should be in this format:
[{'text':'sometext','value':'somevalue'},{'text':'sometext','value':'somevalue'}];
$(document).ready(function() {
$(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
var options = [];
$.each(jsonData, function (i, j) {
options.push('<option value="' + j.value + '">' + j.text + '</option>');
});
$('#fruits').html( options.join(''));
});
});
Please note that there may be an encoding/escaping issues here.
Make sure that you escape the text properly from the server side.
htmlentities, htmlspecialchars can help you with that.
This should work in most browsers

Categories