How to combine two similar scripts and run it with slight variations - javascript

I have the following two scripts:
The first one, on grabs a keyword from input#search and populates a dropdown#search-results with the results from the ajax call for that keyword.
$(document.body).on( 'keyup', '#search', function ( e ) {
//e.preventDefault();
value = $(this).val(); //grab value of input text
jQuery.ajax({
url : ajaxsearch.ajax_url,
type : 'post',
data : {
action : 'search_client',
key : value,
},
success : function( response ) {
response = jQuery.parseJSON(response);
//console.log(response);
$.each(result, function(k, v) {
$('#search-results').append('<li>' + v['Name'] + '</li>');
});
}
});
});
The second script, grabs the value of the clicked dropdown result, does the same action as the first script only this time the ajax result is used to populate fields located on the page.
$(document.body).on('click','#search-results > li', function ( e ) {
//e.preventDefault();
value = $( this ).text(); //grab text inside element
jQuery.ajax({
url : ajaxsearch.ajax_url,
type : 'post',
data : {
action : 'search_client',
key : value,
},
success : function( response ) {
response = jQuery.parseJSON(response);
//console.log(response);
$.each(response, function(k, v) {
$('#clientID').val( v['ClientId'] );
$('#denumire').val( v['Name'] );
$('#cui').val( v['CUI'] );
$('#regcom').val( v['JRegNo'] );
$('#adresa').val( v['Address'] );
$('#iban').val( v['IBAN'] );
$('#banca').val( v['Bank'] );
$('#telefon').val( v['Phone'] );
$('#pers-contact').val( v['Contact'] );
});
}
});
});
Is there a way to combine the second script into the first one so not to make the second ajax call, but be able to populate the fields on the page with the results from the first ajax call depending on the clicked result in the dropdown list?

If the text you insert from v['Name'] into the list item in the first script is the exact same thing you want to use elsewhere in the page in the second script, you can reduce the code way, way down. After all, if you already have the value you want, there's no need to go search for it again.
//first function, just the relevant bits...
$.each(result, function(k, v) {
var newItem = $('<li>' + v['Name'] + '</li>');
$.data(newItem, "value", v);
$('#search-results').append(newItem);
});
//second function, the whole thing
$(document.body).on('click','#search-results > li', function ( e ) {
e.preventDefault();
var v = $.data($( this ), "value"); //grab object stashed inside element
$('#clientID').val( v['ClientId'] );
$('#denumire').val( v['Name'] );
$('#cui').val( v['CUI'] );
$('#regcom').val( v['JRegNo'] );
$('#adresa').val( v['Address'] );
$('#iban').val( v['IBAN'] );
$('#banca').val( v['Bank'] );
$('#telefon').val( v['Phone'] );
$('#pers-contact').val( v['Contact'] );
});
This should let you store the entire result object into the list item, then retrieve it later. If you have some elements in that list that you're not putting there with searches, you'll have to do some more work to get their relevant data too.

Related

Variable Scope Between JS Functions: Variable Not Defined

I am working on a script that uses jQuery get function to send information to another page and return the data as an alert on current page. I am trying to send the search field value from input form (this works), as well as the collector ID, which is a value generated by an option selected in a drop down menu above the search form.
Unfortunately, I keep getting "collector_id is undefined error" when I run the script. I think I am having an issue with the scope of the variable.. but have tried many options and can't seem to find the solution which keeps the value of collector_id for use in the get function.
$( document ).ready(function() {
$( ".search-field" ).keyup(function() {
//THIS FUNCTION UPDATES THE COLLECTOR ID VARIABLE FROM DROPDOWN MENU VALUE SELECTED BY USER
$( "select" )
.change(function () {
var collector_id = "";
$( "select option:selected" ).each(function() {
collector_id += $( this ).data('value') + " ";
});
})
.change();
//THIS FUNCTION DOES A SEARCH ON ANOTHER PHP SCRIPT PASSING search and collector_id values
if($(".search-field").val().length > 3) {
var search = $(".search-field").val();
$.get("query-include.php" , {search: search, collector_id: collector_id})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
}
});
});
you just need to initialize collector_id outside of the change, so it will be in scope for the $.get
var collector_id = "";
$( "select" )
.change(function () {
$( "select option:selected" ).each(function() {
collector_id += $( this ).data('value') + " ";
});
})
.change();
//THIS FUNCTION DOES A SEARCH ON ANOTHER PHP SCRIPT PASSING search and collector_id values
if($(".search-field").val().length > 3) {
var search = $(".search-field").val();
$.get("query-include.php" , {search: search, collector_id: collector_id})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
}
});

Jquery remote completion, li's are not selectable

I'm trying to create a text input with text completion using a remote host.
I've been trying to use the example in the following URL: http://demos.jquerymobile.com/1.4.0/listview-autocomplete-remote/
this is the javascript code from the example:
$( document ).on( "pageinit", "#myPage", function() {
$( "#autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then( function ( response ) {
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
so first of all I changed dataType from jsonp to json which makes the ajax call
return a proper json object and the unordered list is filled properly.
the problem that I encounter is that once I see the text completion (the li elements), I can't select any of the elements.
I tried browsing this example on my Galaxy Note 2 and I encountered the same problem, the elements are not selectable.
any ideas how to resolve the issue?
thanks
update
as to #Omar comment i changed the following line:
html += "<li>" + val + "</li>";
to
html += "<li><a href='#'>" + val + "</a></li>";
now i can click on an item but it doesn't do anything. it supposed to close the list and add to the text field the selected item.
You need to delegate an event to generated list items and then update input with the value.
$("#autocomplete").on("click", "li", function () {
/* text of clicked element */
var value = $(this).text();
/* update value of input */
$("#autocomplete-input").val(value);
/* optional - remove autocomplete result(s) */
$(this).parent().empty();
});
Demo

cannot get the results to be displayed on the page

I cannot display the results which I got from database:
{"results": ["USA", "Canada"]}
{"message":"Could not find any countries."} //else
I got this error from console:
Uncaught TypeError: Cannot read property 'length' of undefined.
Could you please check my code to find out what is my mistake.
Here is my view:
My Travel Plans
<div id="my_div">
<div id="country_list_is_got"></div>
<div id="country_list_is_not_got"></div>
</div>
Controller:
if ($this->my_model->did_get_country_list($user_id)) {
$country["results"]= $this->model_users->did_get_country_list($user_id);
echo json_encode($country);
}
else {
$country = array('message' => "Could not find any countries." );
echo json_encode($country);
}
JS file:
$("#load_country_list").click(function() {
$.post('cont/get_country_list', function (country) {
if (country.message !== undefined) {
$( "#country_list_is_not_got").text(country.message);
} else {
$.each(country.results, function(i, res) {
var item = $('<div>'),
title = $('<h3>');
title.text(res);
item.append(title);
item.appendTo($("#country_list_is_got"));
});
}
});
});
You need to tell jQuery what content type is coming back from the server (json)
It defaults to 'string' and it has no reason to think that's incorrect.
See the documentation for the correct parameter order.
Your .each iterator is trying to loop over a string, and - obviously - failing.
Edit: As a point of pedantry, why are you using POST to GET data? "Get" is literally in your URL.
I think it should be $.get or the $.getJSON shortcut, instead of $.post
$.getJSON("cont/get_country_list", function( data ) {
console.log(data);
// something like this for list construction and append to body
var countries = [];
// maybe you need data.results here, give it a try or see console
$.each( data, function( key, val ) {
countries.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "country-list",
html: countries.join( "" )
}).appendTo( "body" );
});
Live Demotry this, issue is results contain array.but you try to use key,value
if (country.message !== undefined) {
$( "#country_list_is_not_got").text(country.message);
} else {
for(i=0;i<country.results.length;i++){
var item = $('<div>'),
title = $('<h3>');
title.text(country.results[i]);
item.append(title);
item.appendTo($("#country_list_is_got"));
}
}

Removing duplicates from autocomplete results Json

I have an issue where I have added two feature classes and it means that I sometimes get results which are duplicated in the autosuggest. I wondered if there is a way I can some how check for duplicates and fetch an alternative instead of showing the same result twice.
This is my code here (working): http://jsfiddle.net/spadez/nHgMX/4/
$(function() {
jQuery.ajaxSettings.traditional = true;
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: ["A","P"],
style: "full",
maxRows: 7,
name_startsWith: request.term,
country: "UK"
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
Any help or information would be much appreciated
Hard to tell exactly what you're asking. But to remove duplicates from an array of objects, you can use underscore's _.uniq()
$.map( _.uniq(data.geonames, false, function(o){return o.adminName1})
Here's a jsfiddle that doesn't show duplicates. But again, it's hard to tell what a duplicate really is from your structure, but this code should move you in the right direction
You don't have use underscore, it's really easy to implement uniq on your own, just look at azcn2503's answer
I modified the code slightly so that it does the following:
Puts all the autocomplete entries in to an object, with the autocomplete value as the key
Converts this object back in to an array and returns it
By doing this, any duplicate keys simply overwrite the previous one.
The success function now looks like this:
success: function( data ) {
var x = $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
});
// Create an object to easily filter out duplicates (key of same name will simply be reused)
var x2 = {};
for(var i in x) {
x2[x[i].value] = x[i];
}
// Create a new array that simply converts the object in to a de-duplicated array
var x3 = [];
for(var i in x2) {
x3.push(x2[i]);
}
// Return the array
response(x3);
}
I have tested it and it seems to be working, although your issue with the duplicates appearing in the first place is not something I can replicate.
Updated fiddle: http://jsfiddle.net/nHgMX/8/
If your ajax call is returning an array with the response value, you can run it through a plugin to remove duplicate entries. Here's a plugin that I found on another SO thread somewhere a while back.
function ArrayNoDupes(array) {
var temp = {};
for (var i = 0; i < array.length; i++)
temp[array[i].value] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
I may be mistaken, but you would implement it into your existing code by changing the following line:
source: function( ArrayNoDupes(request), response )
EDIT: Updated function per Juan Mendes' comment

Mystery ajax request occurring somehow

Whenever I type in the autocomplete field an ajax request is sent and there is no code I've written to do this. Checking the console I see it's a 400 GET request to the controller that loaded this view with param (json) appended to the url. I'm absolutely stumped.
<head>
<script data-main="<?=base_url()?>public/requirejs/main.js" src="<?=base_url()?>public/requirejs/require-jquery.js"></script>
<script>
requirejs(['a_mod'],
function(a_mod) {
$(document).ready(function() {
var param = [];
param = $('#elem').attr('value');
a_mod.foo(param, "#someElem");
});
});
<script>
main.js
require(["jquery",
"jquery-ui"],
function() {
}
);
The autocomplete function
'foo' : function(param, elementAutocomplete, elementTags) {
console.log("init ac");
$(elementAutocomplete).autocomplete({
source: param,
minLength: 1,
select: function (event, ui) {
event.preventDefault();
//
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $("<li></li>")
.data( "item.autocomplete", item )
.append( '<a>' + item.label + '</a>' )
.appendTo(ul);
}
},
Your source attribute for the autocompleter is a string:
param = $('#elem').attr('value');
And a string source means that it is a URL:
Autocomplete can be customized to work with various data sources, by just specifying the source option. A data source can be:
an Array with local data
a String, specifying a URL
a Callback
Saying var param = []; just means that param is initialized as an empty array, it doesn't mean that param will always be an array. You need to fix your param value to be an array.

Categories

Resources