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!!
Related
I'm using the following ajax script to POST data back after re-sorting the rows (which works fine). I'm not getting anything in the alert(data) that is being shown once I drag-and-drop the row. It should show me what it's trying to pass to the 'refresh_order.php' file.
I am NOT a jQuery or ajax expert -- I found this bit of code online and the first part works for me (the dragging and dropping) but I don't know what's wrong with the ajax that posts the data back to MySQL.
What do I need to do to fix this?
$('tbody').sortable({
cancel: ":input,button,[contenteditable]",
axis: "y",
update: function (event, ui) {
var data = $(this).sortable('serialize');
alert(data); // Sent to server
$.ajax({
data: data,
type: 'POST',
url: 'refresh_order.php',
success: function(response) {
// alert(response); // Server response
}
});
}
});
[I have looked through most of the posts here on Stack Overflow and seen nothing that helps my situation. I even tried to reach out to the person who I got the code from but haven't received a response.]
From the documentation:
Note: If serialize returns an empty string, make sure the id attributes include an underscore. They must be in the form: "set_number" For example, a 3 element list with id attributes "foo_1", "foo_5", "foo_2" will serialize to "foo[]=1&foo[]=5&foo[]=2". You can use an underscore, equal sign or hyphen to separate the set and number. For example "foo=1", "foo-1", and "foo_1" all serialize to "foo[]=1".
I assume your tr elements are missing the id attributes in the appropriate format. Here's a working example:
<table>
<tbody>
<tr id="tr_1">
<td>r1c1</td>
<td>r1c2</td>
</tr>
<tr id="tr_2">
<td>r2c1</td>
<td>r2c2</td>
</tr>
</tbody>
</table>
$('tbody').sortable({
cancel: ":input,button,[contenteditable]",
axis: "y",
update: function(event, ui) {
var data = $(this).sortable('serialize');
console.log(data);
}
});
https://jsfiddle.net/bwxmfzs5/
Is there something wrong with this code?
Form input:
<input type="text" id="currentTag" name="currentTag" class="inputbox"/>
jquery:
$("#currentTag").autocomplete({
source:'getautocomplete.php',
minLength:1
});
getautocomplete.php
$term=$_GET["term"];
$query=mysql_query("SELECT * FROM table_name WHERE tag_value LIKE '%".$term."%' ORDER BY tag_value ");
$results=array();
while($row = mysql_fetch_array($query)){
$results[] = array('label' => $row['tag_value']);
}
echo json_encode($results);
getautocomplete.php output when script is called directly:
[{"label":"birdseye"},{"label":"doggy"},{"label":"tomhat"}]
'SOLVED'
It's a bit of a hack job, but I ended up setting source as a jquery var instead of url. Then used php include to echo the json into the var. All this in a Joomla site. Some conflict that I don't understand was happening, because the above code worked in a test file outside of Joomla. If anyone knows the conflict I'd curious to learn. Cheers.
$(document).ready(function() {
$( "#currentTag" ).autocomplete({
source: tags
});
});
var tags = <?php include("getautocomplete.php");?>;
see this link http://jqueryui.com/autocomplete/
Include all js .
Get the data from MySQL using Ajax. Proceed With
what you did now.
In the above link you will find demo source code see once
try this once
$( "#currentTag" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getautocomplete.php",
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 3
});
There is a few thing wrong here, it could be any of the problems
i assume you connect to the db first, this is not shown in the example but that might be the problem
you should make sure you escape your $term, because you give the availability of SQL injection
you should avoid useing SELECT * if you only need tag_value
you should use mysql_fetch_assoc if you want to use assoc arrays in your result
you should make sure the source URL is correct, it is a relative path the way you've put it, try to always use absolute paths, you never know where your script will be used (and with pretty urls, this becomes worse)
i want to add an smart autocomplete to my project in which when ever user is typing a word in any input its autocompleted from his own dictionary.
his owner dictionary is built by saving every word he ever submit to server something like (array_values($_POST))
my current JS
$('input.complete').live('keyup.autocomplete', function(){
var hi=$(this).val().toUpperCase();
var was=this;
$(this).autocomplete({
//PROBLEM Should i consider to change source from ajax/mysql to different source ?
//since there gona be too many requests ??
source: function(request, response) {
$.ajax({ url: '<?=base_url()?>ajax/ac',
//PROBLEM how can i set term=word currently being edited..(start=' ',end=pointerpos)
data: { 'term': this.term },
dataType: "json",
type: "POST",
success: function(data){
if(data.length){
//response(data);
//Commented out cause i dont wana display dropdown.. just typeahead.
if(data[0]['value'].substr(0,hi.length).toUpperCase()==hi){
$(was).val(data[0]['value']);
//currently working with single word inputs..once i get how to select only current word will edit these..
was.selectionStart=hi.length;
was.selectionEnd=data[0]['value'].length;
}
}
}
});
},
select: function(event, ui){},
minLength: 2,
delay: 500
});
As u can see i have 2 problems
Question
how can i select current word that user is typing ?
is this a good approach to reach my goal, or i should consider different plugin
You are using PHP language as well. So in my opinion you can use PHP to solve your problem more easily. Let's say you have php function get_word($excerpt) in get.php file. So,
<?php
get_word($_POST['excerpt']);
function get_word($excerpt) {
// Find exact word from database or array using given $excerpt
// and return complete word.
return $complete_word;
}
?>
And in your jquery (assuming input field as .input),
$(document).ready(function() {
$('.input').live('keyup',function() {
var excerpt = $(this).val();
$.post("get.php", {excerpt:excerpt}, function(data) {
// do anything with data.
$('.input').val(data);
});
});
})
For more precise, you can get bunch of matching words from get.php file, and display list of words to be selected.
So i'm trying to pull the info entered into this form and use it for other things.
<form onsubmit="return false;">
Enter a School:
<input id="schoolsearch" type="text" />
<INPUT TYPE=SUBMIT VALUE="GO">
</form>
I know this may seem like a simple question- but i just can't figure it out. This form is acting with a .php file that helps power the autocomplete function.
Would i just use METHOD=post or what?
Thanks in advance for any help
Here is the outline of how ajax works in javascript. For more info see here http://api.jquery.com/jQuery.post/.
run this on.keypress()
$.ajax({
type: 'POST',
url: url, //url of the php file that searches for schools with the given value
data: data, // the data you are sending so something like $('#school').val()
success: success, // prepare to catch what the php returns
dataType: dataType
});
Hiya please see demo here: http://jsfiddle.net/vZtGs/ or please see one of my old replies using few more options in here: jquery autocomplete using '#'
good read here: http://jqueryui.com/demos/autocomplete/ (with other options and events supported)
Code
$( "#autocomplete, #schoolsearch" ).autocomplete({
source: function( req, resp ) {
$.post( "/echo/json/", {
json: '["School1", "School2", "School3", "School4", "School5"]',
delay: 1
}, function(data) {
resp( data );
}, "JSON" );
},
select: function(event, ui) {
//var terms = split(this.value);
alert('Do whatever with this value man: ' + ui.item.value);
return false;
}
});
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;
}
});