Alter Ajax Json Query Parameter [duplicate] - javascript

This question already has answers here:
How do you pass multiple parameters of the same type to jQuery Get
(5 answers)
Closed 9 years ago.
This is my current code: http://jsfiddle.net/spadez/nHgMX/2/
$(function() {
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: "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" );
}
});
});
This link states this: http://www.geonames.org/export/geonames-search.html
featureclass(es) (default= all feature classes); this parameter may
occur more than once, example: featureClass=P&featureClass=A
How can I adjust my code to set the feature class to A and P not just P as it is currently?

I find 2 solutions:
First one is use method suggested by #George Cummins:
jQuery.ajaxSettings.traditional = true;
...
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: ["A","P"],
In second you can add parameters to query string:
$.ajax({
url: "http://ws.geonames.org/searchJSON?featureClass=A&featureClass=P", // you can concantenate it

Related

Jquery autocomplete from json array

Please solve this issue:
I have the json format array in external js: (NOT Ajax(json) request)
var data = [{"Id": 0,"City": "Chicago"},{"Id": 1,"City": "New York"},...]
I need to create Jquery autocomplete form with arrow. Maybe it will be:
select
Chicago (from external JS)
New York
/select,
or textarea, input. One thing is required: arrow will be visible, because user may choose elements with mouse.
How to attach array to html page?
Image
Here it shows all the items containing the word in input. Check this fiddle. May it helps.
var data = [{"Id": 0,"City": "Chicago"},
{"Id": 1,"City": "New York"},
{"Id": 2,"City": "Aew York1"},
{"Id": 3,"City": "Bew York2"}]
$.each(data,function(i,item){
var $option=$('<option>',{val:item.Id,text:item.City});
$('#tags').append($option);
})
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" ).appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
classes: {
"ui-tooltip": "ui-state-highlight"
}
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false;
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.tooltip()
.appendTo( this.wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.on( "mousedown", function() {
wasOpen = input.autocomplete("widget").is( ":visible" );
})
.on( "click", function() {
input.trigger("focus");
// Close if already visible
if ( wasOpen ) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input.val( "" ).attr( "title", value + " didn't match any item" ).tooltip("open");
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
$( "#tags" ).combobox();
.custom-combobox {
position: relative;
display: inline-block;
}
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
}
.custom-combobox-input {
margin: 0;
padding: 5px 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div>
<label for="tags">Tags: </label>
<select id="tags"></select>
</div>

How to implement my own rule in filter result in jQuery UI Autocomplete

This is my code:
var projects = [{label:"PH2938", value: "1", fk: "3", desc: "hello"},
{label:"JUH28", value: "2", fk: "0", desc: "world"},];
{label:"HK383", value: "3", fk: "3", desc: "!"},];
$( "#serial_no" ).autocomplete({
minLength: 0,
source: function(request, response) {
var results = $.ui.autocomplete.filter(projects, request.term);
response(results);
},
focus: function( event, ui ) {
$( "#serial_no" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#serial_no" ).val( ui.item.label );
$( "#device_id" ).val( ui.item.value );
$( "#device_model" ).text( ui.item.desc );
return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
So now, for example, if I type 'H' in the field, all 3 results (i.e PH2938, JUH28, HK383) will be shown. My question is: is possible to make it only show the results (i.e. PH2938, HK383) whose fk = 3. That is, can I implement my own rule in showing which results.
If I have understood correctly you need to filter the projects by some criteria. In this case by fk being equal to '3'.
As you are already using jQuery then $.grep is the good candidate for the filtering task.
$.grep(projects, function (project) {
return project.fk === '3';
});
Now we have to decide where to perform this filtering.
If you want to get rid of those projects that meet the fk criteria regardless of the term used in the autocompletion input, I would do it in the original projects array:
var projects = [{label:"PH2938", value: "1", fk: "3", desc: "hello"},
{label:"JUH28", value: "2", fk: "0", desc: "world"},];
{label:"HK383", value: "3", fk: "3", desc: "!"},];
projects = $.grep(projects, function (project) {
return project.fk === '3';
});
If what you want is something more flexible that allows you to provide a different data source depending on other criteria, not only the text matching of the label, then you can perform this filtering in the source property:
source: function(request, response) {
var results = $.ui.autocomplete.filter(projects, request.term);
// Filter the matched results by project fk 3.
results = $.grep(results, function (project) {
return project.fk === '3';
});
response(results);
},
The filtering could be performed before the matching too:
source: function(request, response) {
// Filter the matched projects by project fk 3.
var filteredProjects = $.grep(projects, function (project) {
return project.fk === '3';
});
var results = $.ui.autocomplete.filter(filteredProjects, request.term);
response(results);
},
See a demo for the latter.

jquery autocomplete does not shows result

I have input of type text to which I have attached autocomplete:
javascript:
$("#descSearchBox").keyup(function(e) {
//$("#ui-id-1").addClass("dropdown-menu").removeClass('ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all');
$(".ui-autocomplete").removeClass("ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all")
.addClass('dropdown-menu');
$.post("/controls/DistControl.php", {
action: 'descAutocomplete',
description: $(this).val(),
myDistribution: $("#cbMyDistributions").is(":checked")
}, function(data) {
data = $.parseJSON(data);
$( "#titleSearchBox" ).val('');
console.log(data);
$( "#descSearchBox" ).autocomplete({
source: data.result.titles,
select: function( event, ui ) {
$("#titleSearchBox").val(ui.item.label);
distributionTableUpdate();
}
});
}
);
});
and here is php script that sends request back:
function descAutocomplete() {
$where['LIKE'] = [ "description" => $_POST['description'] ];
if( $_POST["myDistribution"] === "true" )
$where["user_id[=]"] = $_SESSION['user_id'];
$dists = DistributionModel::getAll( $where, 10, 0, 'title', 'ASC', [ 'title' ] );
$titles = [];
foreach($dists as $d) {
$titles[] = $d->get('title');
}
$response = new ResponseModel(ResponseModel::$TYPE_INFO, 'Description Autocomplete', [ 'titles' => $titles ]);
echo $response->encode();
}
The thing is I get result back, for example I just type 'e' in search and I get array with 4 elements but it shows nothing or just shows the last one. Why would do so? Why it does not shows all results?
Try to use Like
$("#name").autocomplete({
source: function( request, response ) {
$.ajax({
url: "URL",
dataType: "json",
data: {term: request.term},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.state,
id: item.id
};
}));
}
});
},
select: function(event, ui) {
$('#id').val(ui.item.id);
}
});

traversing jQuery JSON Object array

I am try access an Object array using getJson, I've tried many things but I keep getting an 'undefined' or [Object, object] returned.
$.getJSON( "js/test.json", function( data ) {
var items = new Array();
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val.entries.title + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Here is the JSON, I am trying to get the 'title' of each 'entries'.
{
"$xmlns": {
"pl1": "url"
},
"startIndex": 1,
"author": "MJS",
"entries": [
{
"title": "This is target",
"m$ct": [
{
"m$name": "name"
}
],
"m$rt": "pd",
"m$content": [
{
"plfile$width": 640
},
{
"plfile$width": 960
}
],
"plm$c": [],
"link": ""
},
{
"title": "title2",
"m$ct": [
{
"m$name": "name"
}
],
"m$rt": "pd",
"m$content": [
{
"plfile$width": 640
},
{
"plfile$width": 960
}
],
"plm$c": [],
"link": ""
}
]
}
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val.entries.title + "</li>" );
});
should instead read:
$.each( data.entries, function( key, entry ) {
items.push( "<li id='" + key + "'>" + entry.title + "</li>" );
});
You're iterating over the whole json instead of the entries
It should be data.entries in the each and then just val.title
$.getJSON( "js/test.json", function( data ) {
var items = new Array();
$.each( data.entries, function( key, val ) {
items.push( "<li id='" + key + "'>" + val.title + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

jQuery UI autocomplete jsonp mapping response

I am trying to use the autocomplete from jqueryUI. When i alert the response i get the following : ([ { "id": "test", "label": "test", "value": "test" } ]);
but when i try to map the result the dropdown result is empty. here is my code:
<script>
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://localhost/jQuery/development-bundle/demos/autocomplete/search3.php",
jsonp: "jsonp_callback",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
alert(data);
response( $.map( data, function( item ) {
return {
label: item.label,
value: item.value
}
}));
}
});
},
minLength: 2,
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" );
}
});
});
</script>
my server side script uses the following code:
echo $_GET['jsonp_callback'] . '(' . $data . ');';
Thanks anyway
use this line
url: "http://ws.geonames.org/searchJSON?jsonp_callback=?",
and datatype also
dataType: 'jsonp',
instead of
url: "http://ws.geonames.org/searchJSON",

Categories