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.
Related
I have checked the logs of my PHP function and I have correctly formatted JSON data that I am returning from the method. The AJAX is calling it and returning, getting a null value for the response variable. Any Ideas? Here is the AJAX code:
$.ajax({
type: "POST",
url: "index.php/controllerFile/get_standby",
data: 'id=' + $(this).attr('id'),
success: function(response){
console.log('response is: ' + response); //It is null here
$.colorbox({'href':'index.php/config/view/standby' + response.urlData,'width':1000,'title':'Standby People'});
},
dataType:'json'
});
Here is the PHP function:
function get_standby()
{
$id = $this->input->post('id');
$this->load->model('teetime');
$url['urlData'] = ($this->teetime->get_standby_by_id($id));
$printing = json_encode($url);
log_message('error', 'JSON ' . $printing);
return $printing;
}
Try using echo in your PHP instead of return.
echo $printing;
I would suggest opening up Developer Tools in Chrome (View > Developer > Developer Tools) and selecting the Network tab. When your AJAX post request is made, it should add an entry there (the "Path" column should be "index.php/controllerFile/get_standby" and the "Method" column should have "POST"). Click the row for the request and check the Response tab to make sure your JSON is there.
If the response is empty, your problem is with your PHP code (you might not be printing the JSON returned from that function to the page). Otherwise, it would seemingly be a problem with your JavaScript.
I'm having an issue returning a JSON from PHP to Javascript. Below is my PHP to create the JSON:
$environment[] = array('id' => $env, 'adjacencies' => $hostnames);
foreach($hostnames as $hostname) {
$environment[] = array('id' => $hostname, 'name' => $hostname, 'data' => array());
}
return json_encode($environment);;
When I print the json_encode environment to a text file, it comes back as:
[{"id":"Dev","adjacencies":["tb23","tbwag","tbvg","tbut"]},{"id":"tb23","name":"tb23","data":[]},{"id":"tbwag","name":"tbwag","data":[]},{"id":"tbvg","name":"tbvg","data":[]},{"id":"tbut","name":"tbut","data":[]}]
It seems that this is printing out properly but when I return it to the Javascript its coming back as undefined/null. Below is the javascript with the ajax call:
var ajax = new AJAX();
var args = "id=" + $("#apps").val() + "&env=" + node.id + "&nocache=" + (new Date()).valueOf();
ajax.connect("POST", "http://" + window.location.hostname + "/project/graph/host", args, function(json) {
var output = '';
for (property in json) {
output += property + ': ' + json[property]+'; ';
}
alert(output);
});
I've obviously tried a lot of different things to get it to print out but haven't had any luck. In PHP, I've tried json_last_error and it came back as '0', which means that there isn't an issue with the JSON structure.
In the end, I'd like to use the following command in Javascript to continue building my graph:
var hostNodes = eval('(' + json + ')');
Any help is appreciated as to why I can't get this to come back!
Keep your PHP code in an unique file that receives one post parameters, then construct the json array if it set, and at the bottom you can do
echo json_encode($json);
flush();
I'm not a professional with pure javascript and I'm not familar with your approach, but you should consider using jQuery, at least I'm going to suggest one way to receive an json array so that you can easily work with it (you also make sure that the data is json):
$.ajax(
{
// Post select to url.
type : 'post',
url : 'myPHPAjaxHandler.php',
dataType : 'json',
data :
{
'select' : true
},
success : function(data)
{
// PHP has returned a json array.
var id, hostname;
for(var i = 0; i < data.length; i++)
{
id = data[i].id;
hostname = hostname[i].id;
// Construct a string or an object using the data.
}
},
complete : function(data)
{
// Optional.
}
});
Like I say, It's there for you to decide whether you pick it up or not. It can become handy for complex projects.
It looks like you're assuming that the data passed to the callback function will be your JSON already parsed into JS objects, but I don't see any indication that that would be the case; it's most likely the raw JSON data that must be parsed into JS objects using JSON.parse (NOT eval() - eval() is very dangerous, you should always prefer JSON.parse when working with true JSON data, as it will not permit XSS-style attacks as they are generally not "pure" JSON.)
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 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;
}
});
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!