I'm trying to get the jquery ui autocomplete to work with a codeigniter project.
so far I have an input field <input type="text" id="text1"/>
and then in my script I have
source: function(request, response) {
$.post('autocompleteHandler', {mechanic: request.term}, function(data) {
console.log('data.phpResp = '+data.phpResp);
console.log('in post?');
console.log('data = '+data.toSource);
var realArray = $.makeArray(data); // this line was needed to use the $.map function
response($.map(realArray, function(item) {
console.log('in map');
return {
label: item.info,
value: item.info
}
}));
}, 'json');
},
In my codeigniter controller I have this function
function autocompleteHandler() {
$input = $this->input->post('mechanic');
$this->load->model('login_model');
$results = $this->login_model->search_mechanic_criteria($input);
$mechs= array();
foreach($results as $result) {
$mechs['info'] = $result['mechanic_name'];
}
}
I'm not getting this to work. anyone have any ideas of where I can begin to troubleshoot? I really have a hard time with the jquery ui documentation.
EDIT: I've changed my code a bit. Instead of returning json_encode, I needed to echo json_encode on the php side of things. I still don't have anything showing up in my console though.
2ND EDIT Now my question is, how can I return multiple values for the autocomplete function? If i have a query that returns, just one row, it works fine, but if I have multiple rows returned, doesn't work. It's gotta be something with the way i'm returning the data, but I can't figure it out.
I have been playing around with jsfiddle after you mentioned toSource(). See http://jsfiddle.net/XYMGT/. I find that the map function does not return jQuery, but the new array.
OLD STUFF:
I suspect that the $.map function does not return the array, but jQuery. Maybe it would to do this:
// also you could inspect the data if the server returns what you think it returns:
console.log(data);
// first map the array
$.map(data, function(item) {
console.log('in response?');
return {
label: 'testing',
value: 'test'
}
})
// ...then separately do the response part
response(data);
Lets us know if it makes a difference.
EDIT:
If this PHP code is still used:
function autocompleteHandler() {
echo json_encode(array('phpResp' => 'something'));
}
Then console.log(data) should show the following in the console tab in FireBug:
{'phpResp':'somehting'}
Meaning that console.log(data.phpResp) should print 'something'. I am unsure where you are getting data.toSource from.
I would launch fiddler and see what it says it's returning. You can also go straight to your server side page in the browser that is serving the JSON results. I think the autocomplete automatically adds ?term to the string. url.aspx?term=|valueofText1|
$("#text1").autocomplete({
source: url,
minLength: 2,
select: function (event, ui) {
sou = ui.item.label;
}
});
Related
I have googled and looked at SO for a while now and can't seem to figure this out. The only requirement Im trying to meet is to return a properly formatted javascript array that contains the results of the sql statement.
I.E.
Given a query:
SELECT NUMBERS FROM TABLE
And results:
NUMBERS
1
2
3
I would like to eventually get back an array like so
["1","2","3"]
Please help me understand where I am going wrong
Here is my php code
<?php
$mysqli = new mysqli("local.host.com", "user", "pass", "db");
$sql = "SELECT DISTINCT NAME FROM table";
$result = $mysqli->query($sql);
while($row = $result->fetch_array())
{
$rows[] = $row['NAME'];
}
echo(json_encode($rows));
$result->close();
/* close connection */
$mysqli->close();
?>
Here is my javascript:
function GetCards()
{
var cardarray = new Array();
//alert('test');
$.getJSON('getcardlist.php', function(data)
{
for(var i=0;i<data.length;i++)
{
cardarray.push(data[i]);
}
//return cardarray;
});
return cardarray;
}
EDIT:
Little more information, Im trying to setup an autocomplete list for jquery ui, this is my setup for the autocomplete widget.
var list = GetCards();
$( "#name" ).autocomplete({
source: list,
minLength: 2
And this is the error Im getting from chrome console
Uncaught TypeError: Cannot read property 'label' of null
GetCards is returning an empty array -- which is what you're passing on to the Autocomplete widget -- and causing the widget to throw up the TypeError exception. To pass on the populated array, move the code that instantiates Autocomplete into your getJSON success callback (I'm not sure you even need to loop through data -- unless you need to actually transform its contents in some way):
$.getJSON( 'getcardlist.php', function( data ) {
$( "#name" ).autocomplete( {
source: data,
minLength: 2
} );
} );
Alternatively, consider using Autocomplete's shorthand for loading directly from the data feed (see passing source as a string). However, this approach may require some additional work on the server-side to filter down the list as the user types -- if you want that behavior.
you have to use $.each to get the data
$.getJSON('getcardlist.php', function(data)
{
$.each(data, function(key, val) {
cardarray.push(val);
});
//return cardarray;
});
Been playing with this for too long now!
I'm using codeigniter.
I am trying to get some data back from an Ajax get request. Simply I want to check a MySQL DB to check if there is some data in there mathcing a given date. A simple true or false will be fine for the return.
Here is my request, followed by the PHP. The PHP does return the correct result into $data, but when it gets back to the Ajax request, the alert(data) is called and shows up as blank... nothing there.
Any ideas what I'm doing wrong?
Thanks
function get_appointment_data(request_date){
$.ajax({
url: 'http://localhost/doctor_today/booking/retrieve_cal_data',
type: 'GET',
data: request_date,
success: function(data){
alert(data);
}
});
}
function retrieve_cal_data() {
$this->load->model('Booking_model');
$date = $this->input->get('date');
$data = $this->Booking_model->get_calendar_data($date);
return $data==null;
}
I am not familiar with codeigniter but you must output the result of the function. Instade of 'return' you must use 'echo' to return result to ajax request.
You have to echo the result, otherwise your ajax won't receive a result and the success handler won't execute. Here is what I'm going to use for this case, I'm using the simpler .post function for that task with one key difference - I specify 'json' at end of it which means I'll get a json object as a result from my .post (you can search Google for this). The next key is to use encode the result I wanna get in json format using PHP's json_encode function and echo its result. We don't really need to return a result via the normal 'return' statement. So...
The script:
var url = 'http://example.com/ajax_function';
var data = null;
$.post(url, data, function(data) {
if(data.ok)
alert('Everything is fine!');
else
alert('Ops!');
}, 'json');
The server side:
function retrieve_cal_data() {
$this->load->model('Booking_model');
$date = $this->input->get('date');
$data = $this->Booking_model->get_calendar_data($date);
echo json_encode(array('OK' => $data==null));
}
If you call directly the PHP function it should output something like
{ "OK": "true" }
which later on will be translated to an javascript array
data[OK] = true;
which you can use as you wish.
Cheers,
Stan.
P.S. I haven't tested the code but it should pretty work.
I'm stuck with the implementation of the jQuery Autocomplete. I'm using this tutorial: http://1300grams.com/2009/08/17/jquery-autocomplete-with-json-jsonp-support-and-overriding-the-default-search-parameter-q/
My jQuery code is this:
$("#quickSearchQuery").autocomplete("http://mydomain.net/json.php", {
dataType: 'json',
selectFirst: true,
minChars: 2,
max: 8,
parse: function(data) {
var rows = new Array();
data = data.members;
for(var i = 0; i < data.length; i++) {
rows[i] = { id : data[i].id, name : data[i].name, location : data[i].location };
}
return rows;
},
formatItem: function(row, i, n) {
return row.name + ' (' + row.location + ')';
}
});
A call to http://mydomain.net/json.php?q=Alb produces a JSON response like this:
{"query":"Alb","members":[{"id":"1","name":"Peter Albert","location":"New York"},{"id":"4","name":"Adalbert Smith","location":"Alabama"},{"id":"42","name":"Albert Einstein","location":"Vienna"}]}
My problem is: It just doesn't work. The Autocomplete doesn't appear, no elements are created.
If I run the code from the tutorial, everything is fine and I get the autocompleted list of cities. But even if I only change the source URI and from data.geonames to data.members (and so on), the autocompleter stops working.
What I've tried:
I changed dataType to jsonp and json, but jsonp creates the 'invalid label' error on the JSON file
I modified the PHP script's content-type with header("Content-Type: application/json");
I tried all the other Autocompleters, but nothing changed
I tried all the fixes I have found from responses at Stack Overflow and tutorials in the web
I copied a JSON response from geonames.org into a file, uploaded it to my server and used this hardcoded response as lookup source. Still no autocompleter showing :(
Maybe you got an idea?
Thanks!
Joe
with autocomplete, you must use the property id and value to make it working. Only those properties are used to render the list.
In your php object, declare something like this (this one comes from C#, but think that you understand it):
public class Product
{
public String id { get; set; } //must be used
public String value { get; set; } //must be used
public String marque { get; set; }
}
and return the json-serialized string to the client.
The json is something like that
[{"id":"1","value":"UMTS","comment":"umts comment"},
{"id":"2","value":"RAN","comment":"ran comment"},
{"id":"3","value":"Swap","comment":"swap comment"}]
It will be auto-mapped in your JS and the autocomplete should work for now.
I fairly new to JQuery and perhaps trying to achieve something that might be abit harder for a beginner. However I am trying to create an autocomplete that sends the current value to a PHP script and then returns the necessary values.
Here is my Javascript code
$("#login_name").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://www.myhost.com/myscript.php",
dataType: "jsonp",
success: function(data) {
alert(data);
response($.map(data, function(item) {
return {
label: item.user_login_name,
value: item.user_id
}
}))
}
})
},
minLength: 2
});
And here is the the last half of "myscript.php"
while($row = $Database->fetch(MYSQLI_ASSOC))
{
foreach($row as $column=>$val)
{
$results[$i][$column] = $val;
}
$i++;
}
print json_encode($results);
Which produces the following output
[{"user_id":"2","user_login_name":"Name1"},{"user_id":"3","user_login_name":"Name2"},{"user_id":"4","user_login_name":"Name3"},{"user_id":"5","user_login_name":"Name4"},{"user_id":"6","user_login_name":"Name5"},{"user_id":"7","user_login_name":"Name6"}]
Can anyone tell me where I am going wrong please? Starting to get quite frustrated. The input box just turns "white" and no options are shown. The code does work if I specify an array of values.
UPDATE
I have changed the code to and still having no luck.
$("#login_name").autocomplete({
source: "/ajax/login_name.php",
dataType: "json",
minLength: 2,
cache: false,
select: function(event, ui) {
alert(ui);
}
});
Using FireFox's Web Developer tool, I am getting an error "b is null".
Finally found the solution that fits my needs
$("#login_name").autocomplete({
source: function(request, response){
$.post("/ajax/login_name.php", {data:request.term}, function(data){
response($.map(data, function(item) {
return {
label: item.user_login_name,
value: item.user_id
}
}))
}, "json");
},
minLength: 2,
dataType: "json",
cache: false,
focus: function(event, ui) {
return false;
},
select: function(event, ui) {
this.value = ui.item.label;
/* Do something with user_id */
return false;
}
});
some suggestions:
Why dataType= "jsop"? It doesn't appear to be jsonp. I think you want "json".
insert a cache : false in the options, as well. This insures the request is always made, and never satisfied from browser-side cache.
check if the call is going out, with something like Fiddler or Charles.
does your success fn get called? You have a alert() there. Does it get invoked?
if you have Firebug or the IE8 developer tools, you can put a breakpoint on the alert() to verify the value of the parameters.
Why specify the full hostname in the URL?
Last night I had an odd situation with autocomplete where the response was null, the empty string, when I used a different hostname for the page and the Ajax request. When I modified it to use the same hostname, the request succeeded. Actually because of the same origin policy, you should have no hostname at all in the URL for the ajax call.
Yes you do need header info for your json
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-type: text/x-json");
and tvanfosson makes a good point abut the the plug
in anycase I don't think you make the ajax call the plugin does.
if you are infact using jquery-ui autocomple you should read over the documentation get a basic version running. your php is fine aside from the missing header data
In case anyone else needs it :
The documentation for autocomplete in jQuery UI specifies the querystring parameter to use is 'term' and not 'q'... or least it does now.
E.g. http://www.myhost.com/myscript.php?term=someToSearchFor
Simple Jquery ui autocomplete, for those who might need it.
//select data from the table
$search = $db->query('SELECT Title from torrents');
//then echo script tags and variables with php
<?php echo '<script type="text/javascript">
$(function() {
var availableTags = [';
foreach ($search as $k) {
echo '"'.$k['Title'].'",';
}
echo '];
$( "#tags" ).autocomplete({
minLength:2, //fires after typing two characters
source: availableTags
});
});
</script>';
?>
your html form
<div id="search">
<form id="search-form">
<input id="tags" type="text" />
<input type="submit" value="Search" />
</form>
</div>
A JSON strcuture is a flat string, while map expects an array or array like structure. try json decode on the string before using map.
I had a problem like you too. And now I fix it. The problem is my json that return from my server contain a syntax error.
In http://api.jquery.com/jQuery.getJSON/ tells that if there are some error in JSON, it will fail silently. The JSON must match the JSON standard here http://json.org/ .
For my error is my string in JSON is wrapping in only one quote. But the JSON standard accept only string that wrap in double quotes.
eg. "Hello World" not 'Hello World'
When you fix it you can set the source as string URL. The term will be in "term" query string. And it works!!
I'm trying to use jQuery.post() function to retrieve some data. But
i get no output.
I have a HTML that displays a table. Clicking this table should trigger a jQuery.post event.
My scriptfile looks like this:
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML; //This gets me the rowID for the DB call.
jQuery.post("../functions.php", { storeID: "storeID" },
function(data){
alert(data.name); // To test if I get any output
}, "json");
});
});
My PHP file looks like this:
<?php
inlcude_once('dal.php');
//Get store data, and ouput it as JSON.
function getStoreInformation($storeID)
{
$storeID = "9";//$_GET["storeID"];
$sl = new storeLocator();
$result = $sl->getStoreData($storeID);
while ($row = mysql_fetch_assoc($result)) {
{
$arr[] = $row;
}
$storeData = json_encode($arr);
echo $storeData; //Output JSON data
}
?>
I have tested the PHP file, and it outputs the data in JSON format. My only problem now is to return this data to my javascript.
since the javascript is located in the /js/ folder, is it correct to call the php file by using '../'?
I don't think I'm passing the storeID parameter correctly. What is the right way?
How can I call the getStoreInformation($storeID) function and pass on the parameter? The jQuery example on jQuery.com has the following line: $.post("test.php", { func: "getNameAndTime" }
Is the getNameAndTime the name of the function in test.php ?
I have gotten one step further.
I have moved the code from inside the function(), to outside. So now the php code is run when the file is executed.
My js script now looks like this:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data);
}, "text");
});
This results in an alert window which ouputs the store data as string in JSON format.
(because I have changed "json" to "text").
The JSON string looks like this:
[{"id":"9","name":"Brandstad Byporten","street1":"Jernbanetorget","street2":null,"zipcode":"0154","city":"Oslo","phone":"23362011","fax":"22178889","www":"http:\/\/www.brandstad.no","email":"bs.byporten#brandstad.no","opening_hours":"Man-Fre 10-21, L","active":"pending"}]
Now, what I really want, is to ouput the data from JSON.
So I would change "text" to "json" and "alert(data)" to "alert(data.name)".
So now my js script will look like this:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data.name);
}, "json");
});
Unfortunately, the only output I get, is "Undefined".
And if I change "alert(data.name);" to "alert(data);", the output is "[object Object]".
So how do I output the name of teh store?
In the PHP file, I've tried setting $storeID = $_GET["sID"]; But I don't et the value. How can I get the value that is passed as paramter in jQuery.post ?
(currently I have hardcoded the storeID, for testing)
Lose the quotes around "storeID":
Wrong:
jQuery.post("../functions.php", { storeID: "storeID" }
Right:
jQuery.post("../functions.php", { storeID: storeID }
bartclaeys is correct. As it is right now, you are literally passing the string "storeID" as the store ID.
However, a couple more notes:
It might seem weird that you will be setting storeID: storeID - why is only the second one being evaluated? When I first started I had to triple check everytime that I wasn't sending "1:1" or something. However, keys aren't evaluated when you are using object notation like that, so only the second one will be the actual variable value.
No, it is not correct that you are calling the PHP file as ../ thinking of the JS file's location. You have to call it in respect of whatever page has this javascript loaded. So if the page is actually in the same directory as the PHP file you are calling, you might want to fix that to point to the right place.
Kind of tied to the previous points, you really want to get your hands on Firebug. This will allow you to see AJAX requests when they are sent, if they successfully make it, what data is being sent to them, and what data is being sent back. It is, put simply, the consensus tool of choice to debug your Javascript/AJAX application, and you should have it, use it, and cherish it if you don't want to waste another 6 days debugging a silly mistake. :)
EDIT As far as your reply, if you break down what you are returning:
[
{
"id":"9",
"name":"Brandstad Byporten",
"street1":"Jernbanetorget",
"street2":null,
"zipcode":"0154",
"city":"Oslo",
"phone":"23362011",
"fax":"22178889",
"www":"http:\\/www.brandstad.no",
"email":"bs.byporten#brandstad.no",
"opening_hours":"Man-Fre 10-21, L",
"active":"pending"
}
]
This is actually an array (the square brackets) containing a single object (the curly braces).
So when you try doing:
alert(data.name);
This is not correct because the object resides as the first element of the array.
alert(data[0].name);
Should work as you expect.
Your JSON is returned as a javascript array... with [] wrapping the curly bits [{}]
so this would work.
wrong: alert(data.name);
right: alert(data[0].name);
Hope that helps.
D
Ok, thanks to Darryl, I found the answer.
So here is the functional code for anyone who is wondering about this:
javascript file
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
jQuery.post("get_storeData.php", { storeID: this.cells[0].innerHTML }, // this.cells[0].innerHTML is the content ofthe first cell in selected table row
function(data){
alert(data[0].name);
}, "json");
});
});
get_storeData.php
<?php
include_once('dal.php');
$storeID = $_POST['storeID']; //Get storeID from jQuery.post parameter
$sl = new storeLocator();
$result = $sl->getStoreData($storeID); //returns dataset from MySQL (SELECT * from MyTale)
while ($row = mysql_fetch_array($result))
{
$data[] = array(
"id"=>($row['id']) ,
"name"=>($row['name']));
}
$storeData = json_encode($data);
echo $storeData;
?>
Thanks for all your help guys!