Jqueryui autocomplete, get selected user id - javascript

im new to jquery ui autocomplete. Im basically using autocomplete with ajax, with PHP to get list of users.
autocompleteajax.js
$(function() {
$( "#ranksearch" ).autocomplete({
source: function( request, response ) {
console.log('in');
$.ajax({
url: "autocompleteajax.php",
dataType: "json",
data: {
q: request.term
},
success: function( data ) {
console.log(request);
console.log(data);
response(data);
}
});
},
});
});
and the JSON, that php is returning looks like this
{3: "Tomek To", 4: "Tomek Kula"}
The number is userid, and the string is Firstname Lastname. I would like to store the selected userid somewhere, after someone chooses it from autocomplete list. Is there any simple way to achieve it?

Thanks to help #Dev.Joel i found out the solution.
In php i stored users like this
$users[] = array('value'=>$uid,'label'=>$uname);
Then the i got the values in js by doing this
$(document).ready(function () {
$('#ranksearch').on('autocompleteselect', function (e, ui) {
e.preventDefault(); // prevent the "value" being written back after we've done our own changes
this.label = ui.item.label;
$('#ranksearch').val(this.label);
console.log(ui.item.value);
});
});
Something was broken meanwhile i did this and i had to assign myself the label to input, since it was using value.

Related

JQuery Autocomplete and AJAX combination

I'm trying to implement auto-complete on a textbox in php. The data from autocomplete is retrieved using a GET ajax call (which calls a certain api and returns json output).
The code for my ajax was as follows:
<script type="text/javascript">
$(function() {
$( "#tags" ).keyup(function() {
var query = document.getElementsByName('newartist')[0].value;
$.ajax({
type: "GET",
url: "https://lab.anghami.com/rest/v1/SEARCHedge.php",
data: "output=jsonhp&q=" + query,
dataType: "html",
success: function (data) {
var obj = JSON.parse(data);
console.log("1. " + obj[0]);
console.log("2. " + obj[1]);
}
});
});
});
</script>
This code was working perfectly find, and the output was shown in the console correctly. Next I tried adding this ajax call as "source" to my autcomplete call as follows:
<script type="text/javascript">
$(function() {
var query = document.getElementsByName('newartist')[0].value;
$( "#tags" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: "GET",
url: "https://lab.anghami.com/rest/v1/SEARCHedge.php",
data: "output=jsonhp&q=" + query,
dataType: "html",
success: function (data) {
var obj = JSON.parse(data);
var outp = [];
outp.push(obj.sections[0].data[0].name);
outp.push(obj.sections[0].data[1].name);
console.log(obj.sections[0].data[0].name);
console.log(obj.sections[0].data[1].name);
response(outp);
}
});
}
});
});
</script>
Here, the code stopped working for some reasons, and any console.log commands I had stopped outputting the results.
One other method I found as answer to a similar question was to implement the following code:
<script type="text/javascript">
$(function() {
$( "#tags" ).keyup(function() {
var query = document.getElementsByName('newartist')[0].value;
$.ajax({
type: "GET",
url: "https://lab.anghami.com/rest/v1/SEARCHedge.php",
data: "output=jsonhp&q=" + query,
dataType: "html",
success: function (data) {
var obj = JSON.parse(data);
var artists = [];
artists.push(obj[0]);
artists.push(obj[1]);
test(obj);
}
});
});
});
function test(data){
console.log(data);
$("#tags").autocomplete({
source: data
});
}
</script>
This was a bit better as autocomplete was indeed suggesting results, but it was inconsistent as it sometimes outputted 1 result instead of 2 (my ajax call ALWAYS returns 2 results, and I made sure that it's always the case by using console.log), and sometimes the suggestions proposed by autocomplete were those of the previous AJAX call and not the current one (again, console showed new results but autocomplete suggested previous ones.
If you could point to the errors in both of these methods, it would be great.
Thanks!!
Code looking fine. Please mention the JSON output format.

Javascript works fine with a hard-coded string but not with variable

I have a problem I have bee struggling over all morning so I felt it was time to get some help! I have a javascript function which gets the value entered by a user into an autocomplete box, uses AJAX to send that value to a php script which queries the database and then populates the following box with the possible options. The problem is this all works fine when I hard-code in the selected option as so:
var selected="Ed Clancy";
but not when it pulls it from the box, as so:
var selected = this.getValue();
I have tried debugging this using an alert box and both boxes come up with the same string in them so I am completely puzzled! Any ideas? Full code below:
$(riderSelected).on('selectionchange', function(event){
var selected = this.getValue();
//var selected="Ed Clancy";
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: { name: selected },
success: function(data) {
console.log(data);
$('#nap4').append(data);
}
});
});
Based on magicsuggest documentation - http://nicolasbize.com/magicsuggest/doc.html , you probably could do this
var selected = this.getValue()[0];
IF you do not allow multiple selection
Change your code as I have written below for you .
Code
$(riderSelected).on('change', function (event) {
var selected = this.value;
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: {name: selected},
success: function (data) {
console.log(data);
$('#nap4').append(data);
}
});
});

Javascript function to change input fields

I'm trying to check if a user exists in my database and then change the values of my input fields to match that user's information. I have the following code but it doesn't seem to work.
<button onclick="checkAvailability()">Check Availability</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function checkAvailability()
{
$(function()
{
$.ajax(
{
type: 'POST',
url: 'test.php',
data: "name=" + $("#name").val(),
dataType: 'json',
success: function(row)
{
$('#name').val(row[0]);
$('#address1').val(row[1]);
$('#phone1').val(row[2]);
alert('success');
}
});
});
}
</script>
The alert goes off but none of the values are changed. I checked the response using Firebug and the response is a JSON object with the user's information. I'm not sure where the error is. Thank you for any input.
If you have a json object you must use: $("#name").val(row.name);
In case you are getting a json then it might look like this
var json = [{"name": "sample"},{"phone":"sample"},{"address":"sample"}];
When you are doing row[0].
what you get is an object["name":"sample"]
So you must make the following change
success: function(row)
{
$('#name').val(row.name);
$('#address1').val(row.address);
$('#phone1').val(row.phone);
alert('success');
}
Also make sure you have input types with id's name, address1 and phone1

how to pass value in textbox through ajax autocomplete and recieve in php processing page

these are my two textboxes
<input name="temp" type="text" id="authnames" />
<input name="qot" type="text" id="qid" value=""/>
and i am gettting value in the first textbox, i can see it in screen (the one with id authnames)
now i need to pass that value to via jquery/ajax to a new php page and need to retrieve it there
below is my jquery/ajax code, and see the way i am passing it, is this the correct way, coz idont think i am getting any value in autocompletequote.php, what am i doing wrong?
$(document).ready(function(){
$("#qid").autocomplete({
source: "autocompletequote.php",
minLength: 1,
data: { postcode: $("#authnames").val(),
type: "post",
dataType: "json",
success: function(data) {
console.log( data );
console.log("hi");
}
},
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
//alert(label);
alert(value);
}
});
});
there are the two codes i used to retrieve value value in "authnames"
$author = $_POST['postcode'];
and
$author = $_GET['postcode'];
is this correct too?
i have written 2 queries in autocomplete.php
one query do not need value of $author and other needs value of $author,
first query is working fine second is not working its returning null
please help me
I think your syntax for the auto-complete is wrong.
it has to follow jquery-autocomplete 's syntax.
The data is actually a function after the autocomplete.
so to fix ure code, to go towards what u r doing is..
$(document).ready(function(){
$("#qid").autocomplete
({
source:"autocompletequote.php",
minLength:1,
select: function (event, ui)
{
var label = ui.item.label;
var value = ui.item.value;
//alert(label);
alert(value);
$.ajax({
url: "autocompletequote.php",
data: { "Myvariablename" : $("#authnames").val() } ,
type:"post",
dataType:"json",
success:function(data)
{
console.log( data );
console.log("hi");
}
});
}
});
});
Or i am mis-understanding ure purpose
In PHP
$authname = $_POST["Myvariablename"];
EDITED :
To pass an extra query, or custom query, the source attribute has to be a function like so
$("#qid").autocomplete({
source: function(request, response) {
$.getJSON("autocompletequote.php", { "Myvariablename" : $("#authnames").val(), "someothervarialble" : xxx },
response);
},
minLength: 1,
select: function(event, ui){
// your action or futher ajax code goes here.
}
});
finally i got the answer i just changed the code to this
<script>
var label;
var value;
$(document).ready(function(){
$("#tag").autocomplete({
source:'autocomplete.php',
minLength:1,
select: function (event, ui)
{
label = ui.item.label;
value = ui.item.value;
$("#authnames").val(value);
console.log("hi");
//alert(label);
alert(value);
$("#qid").autocomplete({
source:'autocompletequote.php?postcode='+value,
minLength:1,
select: function (event, ui)
{
var label1 = ui.item.label;
var value1= ui.item.value;
console.log("hi");
//alert(label);
//alert(value);
}
});
}
});
});
</script>
now everything is A OK

JQuery AutoComplete From XML (Dynamic Results)

Perhaps I'm not understanding this concept (I'm an AJAX/javascript/Web newbie). I'm using the JQuery autocomplete feature and if I specify a small, limited items flat file (suggestions.xml) the function works fine, but when I use an actual production data file (3 MB) of suggestions the script doesn't work at all.
So I created a web service that generates XML based on the characters in the textbox but it appears this JQuery doesn't run on each keypress, rather only when the page first loads. Obviously, for this function to be of any use it needs to fetch results dynamically as the user types into the input field.
$(document).ready(function () {
var myArr = [];
$.ajax({
type: "GET",
// this line always sends the default text; not what the user is typing
url: "Suggestions.aspx?searchString=" + $("input#txtSearch").val(),
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function (data) {
alert("XML File could not be found");
}
});
function parseXml(xml) {
//find every query value
$(xml).find("result").each(function () {
myArr.push({ url: $(this).attr("url"), label: $(this).attr("name") + ' (' + $(this).attr("type").toLowerCase() + ')' });
});
}
function setupAC() {
$("input#txtSearch").autocomplete({
source: myArr,
minLength: 3,
select: function (event, ui) {
$("input#txtSearch").val(ui.item.label);
window.location.href = ui.item.url;
//alert(ui.item.url + " - " + ui.item.label);
}
});
}
});
On the server I expected to see a few requests corresponding to the characters the user is typing into the search box but instead I get a single message:
2013-10-18 22:02:04,588 [11] DEBUG baileysoft.mp3cms.Site - QueryString params: [searchString]:'Search'
My flat file of suggestions appears to be way to large for JQuery to handle and my web service script is never called, except when the page is first loaded.
How do I generate suggestions dynamically as the user is typing in the search box if I can't run back to the database (via my web service) to fetch suggestions as the user is typing?
Ok, I got it all worked out.
On the ASPNET side; I created a form to receive and respond to the AJAX:
Response.ContentType = "application/json";
var term = Request.Form["term"];
var suggestions = GetSuggestions(term); // Database results
if (suggestions.Count < 1)
return;
var serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(suggestions);
On the AJAX side I modified the js function:
$("input#txtSearch").autocomplete({
minLength: 3,
source: function (request, response) {
$.ajax({
url: "Suggestions.aspx",
data: { term: $("input#txtSearch").val() },
dataType: "json",
type: "POST",
success: function (data) {
response($.map(data, function (obj) {
return {
label: obj.Name,
value: obj.Url
};
}));
}
});
},
select: function (event, ui) {
$("input#txtSearch").val(ui.item.label);
window.location.href = ui.item.value;
}
});
Everything is working as expected now.
Hope this helps someone else who might get stuck trying to figure out JQuery stuff for ASPNET.

Categories