jQuery autocomplete display worng search item - javascript

how can jQuery autocomplete match input word with list from json object. When I start typing some word in input field jQuery displays wrong results. I think autocomplete show only list from json object. Dont know what is the problem on this autocoplete. So if you coud give me advice to solve this on some other way.
When I select some value in serachbox results this code will append all results to other inputs as value. This is my code:
jQuery
$( document ).ready(
$("#get_search").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/organizations/",
type: "GET",
dataType: "json",
data: {term: request.term},
contentType: "application/json; charset=utf-8",
success: function(data) {
response($.map(data, function(item) {
console.log(item.name);
return {
org_name: item.name,
oib: item.oib,
address: item.address,
city: item.city,
postal_code: item.postal_code
};
}));
}
});
},
minLength: 2,
scroll: true,
select: function(event, ui) {
//this.value = ui.item.org_name;
//console.log(ui.item.org_name+' '+ui.item.oib+' '+ui.item.address);
$('#get_search').val(ui.item.org_name);
$('#oib').val(ui.item.oib);
$('#address').val(ui.item.address);
$('#city').val(ui.item.city);
$('#postal_code').val(ui.item.postal_code);
return false;
}
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li>").data("item.autocomplete", item).append("<a><strong>" + item.org_name + "</strong><br>" + item.oib + " - " + item.address + " - " + item.city + "</a>").appendTo(ul);
});
json object
[
{
"id": "8",
"oib": "213214214",
"name": "asdasdd",
"address": "asdad",
"city": "asdasd",
"postal_code": "asdads"
},
{
"id": "8",
"oib": "213214214",
"name": "asdasdd",
"address": "asdad",
"city": "asdasd",
"postal_code": "asdads"
},
{
"id": "8",
"oib": "213214214",
"name": "asdasdd",
"address": "asdad",
"city": "asdasd",
"postal_code": "asdads"
},
{
"id": "8",
"oib": "213214214",
"name": "asdasdd",
"address": "asdad",
"city": "asdasd",
"postal_code": "asdads"
},
]
html
<input class="form-control ui-autocomplete-input" id="get_search" name="form1-name" type="text" autocomplete="off">

Related

Issues parsing JSON with JQuery/Ajax

I'm accessing an API through JQuery/JSON. I can get the entire JSON block to display on a page using the following:
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
contentType: 'application/json',
headers: {'Access-Control-Allow-Origin': '*'},
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', 'Basic ' + btoa('un:pw'));
},
error: function(jqXHR, textStatus, data){
console.log("(1)Static error message");
console.log("(2)Output of textStatus " + textStatus);
console.log("(3)Output of data " + data);
},
success: function(data) {
var myData = data;
$('#myData').html('<p>'+ myData +'<p>')
}
})
However, when I try to access a key/value from that JSON, I get undefined. I think I'm not parsing the JSON correctly. Here's an example of some code I tried inside the success function:
$.each(myData.blockOne, function(data){
$('#myData').html('<p>'+ this.blockOne.id +'<p>')
});
Here's is an example of the JSON:
[
{
"ItemName": {
"id": "XYZ",
"caseNumber": "123"
},
"blockOne": [
{
"id": "ABC",
"subject": "321",
}
],
"blockTwo": [
{
"id": "EFG",
"subject": "456",
}
]
},
{
"ItemName": {
"id": "HIJ",
"caseNumber": "333"
},
"blockOne": [
{
"id": "JIL",
"subject": "999",
}
],
"blockTwo": [
{
"id": "OPE",
"subject": "778",
}
]
},
]
I'm trying to output something like the following:
Item
ID: XYZ
Case: 123
Block 1:
ID: ABC
Subject: 321
Block 2:
ID: EFG
Subject: 456
Item
ID: HIJ
Case: 333
Block 1:
ID: JIL
Subject: 999
Block 2:
ID: OPE
Subject: 778
Any help is greatly appreciated.
Inside $.each(), you need to loop through myData array instead of myData.blockOne because myData.blockOne returns only the data of the blockOne object.
var myData = [{
"ItemName": {
"id": "XYZ",
"caseNumber": "123"
},
"blockOne": [{
"id": "ABC",
"subject": "321",
}],
"blockTwo": [{
"id": "EFG",
"subject": "456",
}]
},
{
"ItemName": {
"id": "HIJ",
"caseNumber": "333"
},
"blockOne": [{
"id": "JIL",
"subject": "999",
}],
"blockTwo": [{
"id": "OPE",
"subject": "778",
}]
},
];
var html = "";
$.each(myData, function() {
html += `
<p>Item</p>
<p>ID :${this.ItemName.id}</p>
<p>Case :+${this.ItemName.caseNumber}</p>
<p>Block 1:</p>
<ul>
<li>ID :${this.blockOne[0].id}</li>
<li>Subject :${this.blockOne[0].subject}</li>
</ul>
<p>Block 2:</p>
<ul>
<li>ID :${this.blockTwo[0].id}</li>
<li>Subject :${this.blockTwo[0].subject}</li>
</ul>
`
});
$('#myData').html(html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myData"></div>

JSGrid Not show data from json

Hi I'm tryng to modify the "DataManipulation" example from jsGrid demos and I'm not able to show data from a json file retrived using a GET ajax call. Here's my controller code:
{
loadData: function (filter) {
var data = $.Deferred();
$.ajax({
type: "GET",
contentType: "application/json",
url: "myFileURL.json",
dataType: "json"
}).done(function(response){
console.log(response);
data.resolve(response);
});
return data.promise();}
The json retrived is like this
{"98762":{"Address":"Address 1","Age":1,"Country":1,"Married":false,"Name":"Name1"},"637399":{"Address":"Address 2","Age":2,"Country":2,"Married":true,"Name":"Name 2"},"234567554":{"Address":"Address 3","Age":3,"Country":3,"Married":true,"Name":"Name"}}
Your json is not well formed. jsGrid expects a list of objects as a return type. Use this instead.
[
{
"Address": "Address 1",
"Age": 1,
"Country": 1,
"Married": false,
"Name": "Name1"
},
{
"Address": "Address 2",
"Age": 2,
"Country": 2,
"Married": true,
"Name": "Name 2"
},
{
"Address": "Address 3",
"Age": 3,
"Country": 3,
"Married": true,
"Name": "Name"
}
];
This is with the assumption that the schema of the json is correct. Good luck!

How do I map an array of objects

I can't figure this out and I've been at it for hours, so let's say I have an array of JSON. I want to map out the data into a new array.But I am stuck, could someone explain how to use map properly with an array of Json objects, thanks.
var results = [{
"userid": 1213,
"name": "jake",
"id": 3242,
"state": "ny"
}, {
"userid": 1203,
"name": "phil",
"id": 3142,
"state": "ny"
}, {
"userid": 1013,
"name": "kate",
"id": 3241,
"state": "js"
}];
$.ajax({
dataType: "json",
data: results,
success:function(data){
$.map(data.results, (dat, item) {
var array = new Array();
var groups;
groups = array;
groups.a = dat.userid;
groups.b = dat.name;
groups.c = dat.state;
array.push(groups);
} })
});
Map your array before calling $.ajax();
results = results.map(function(item) {
return {
a: item.userid,
b: item.name,
c: item.state;
};
});
//DO your thing
$.ajax({
dataType: "json",
data: results
});
You just forget return mapped obj.
var results = [{
"userid": 1213,
"name": "jake",
"id": 3242,
"state": "ny"
}, {
"userid": 1203,
"name": "phil",
"id": 3142,
"state": "ny"
}, {
"userid": 1013,
"name": "kate",
"id": 3241,
"state": "js"
}];
console.log($.map(results, function(dat, item) {
var groups = {};
groups.a = dat.userid;
groups.b = dat.name;
groups.c = dat.state;
return groups;
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First thing, you need to put your mapping code inside an ajax callback. Then, you can use either jQuery map or javascript map or simple for loop to iterate through each item in the response array.
$.ajax({
dataType: "json",
data: results,
success: function( data )
{
var groups = data.map(function(currentItem){
var group = {};
group.a = currentItem.userid;
group.b = currentItem.name;
group.c = currentItem.state;
return group;
});
console.log( groups );
}
});

multidimensional json data into different input text boxes through jquery/ajax

I have created an autocomplete searchbox followed by two input text boxes.
Please help me how to assign values of autocomplete's selected values.
For ex. if we select ajax, corresponding price should be assigned to 1003 and role should be assigned to foreign.
My json response which I got from php echo output is :
{
"users": [
{
"name": "ajax",
"price": "1003",
"author": "foriegn"
},
{
"name": "jquery",
"price": "1000",
"author": "dd"
},
{
"name": "mysql",
"price": "1000",
"author": "f"
},
{
"name": "php",
"price": "1000",
"author": "abc"
},
{
"name": "php frameword",
"price": "1000",
"author": "def"
},
{
"name": "php tutorial",
"price": "1000",
"author": "ghi"
},
{
"name": "wordpress",
"price": "1000",
"author": "g"
},
{
"name": "wordpress theme",
"price": "1000",
"author": "h"
},
{
"name": "xml",
"price": "1000",
"author": "j"
}
]
}
My JavaScript code below :
var counter = 2;
var availableTags = ["php", "php frameword", "php tutorial", "jquery", "ajax", "mysql", "wordpress", "wordpress theme", "xml"];
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
var roleInput = $('<input/>', {
type: 'text',
placeholder: 'Role',
name: 'Role' + counter,
id: 'textbox' + counter
});
var priceInput = $('<input/>', {
type: 'text',
placeholder: 'price',
name: 'price' + counter,
id: 'textbox' + counter
});
var searchInput = $('<input/>', {
type: 'text',
placeholder: 'search',
name: 'search' + counter,
id: 'se' + counter
});
var hidd = $('<input/>', {
type: 'hidden',
name: 'searchhid' + counter,
id: 'searchhid' + counter
});
newTextBoxDiv.append(searchInput).append(roleInput).append(priceInput).append(hidd);
newTextBoxDiv.appendTo("#TextBoxesGroup");
$('#se' + counter).autocomplete({
source: availableTags
});
counter++;
});
Current fiddle setup is at : http://jsfiddle.net/premgowda/UC74L/6/
PS: I am extremely new to Json and jquery. I havent added the json output into my fiddle setup as I am not sure how to do it .
Use jQuery UI autocomlete select event:
http://api.jqueryui.com/autocomplete/#event-select
Once you've got the selected value, find the matching object and select it's others properties. Like this:
for(i = 0; i < users.length; ++i) {
(users[i].name == selected) {
break;
}
}
price = users[i].price;
author = users[i].author;

Retrieving and displaying JSON data from URL

I am trying to retrieve and display information about current weather from a JSON object using javascript and a URL request:
http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805'
the data from the URL looks like this:
{
"data": {
"current_condition": [
{
"cloudcover": "75",
"humidity": "88",
"observation_time": "03:30 PM",
"precipMM": "2.7",
"pressure": "1008",
"temp_C": "12",
"temp_F": "54",
"visibility": "8",
"weatherCode": "302",
"weatherDesc": [
{
"value": "Moderate rain"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0018_cloudy_with_heavy_rain.png"
}
],
"winddir16Point": "SE",
"winddirDegree": "140",
"windspeedKmph": "17",
"windspeedMiles": "11"
}
],
"request": [
{
"query": "DE3",
"type": "Postcode"
}
],
"weather": [
{
"date": "2012-05-09",
"precipMM": "11.8",
"tempMaxC": "13",
"tempMaxF": "56",
"tempMinC": "12",
"tempMinF": "53",
"weatherCode": "266",
"weatherDesc": [
{
"value": "Light drizzle"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png"
}
],
"winddir16Point": "SE",
"winddirDegree": "141",
"winddirection": "SE",
"windspeedKmph": "12",
"windspeedMiles": "7"
},
{
"date": "2012-05-10",
"precipMM": "11.1",
"tempMaxC": "18",
"tempMaxF": "64",
"tempMinC": "6",
"tempMinF": "43",
"weatherCode": "353",
"weatherDesc": [
{
"value": "Light rain shower"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0009_light_rain_showers.png"
}
],
"winddir16Point": "SSW",
"winddirDegree": "209",
"winddirection": "SSW",
"windspeedKmph": "30",
"windspeedMiles": "19"
}
]
}
}
I have tried a couple of scripts to try and get the data and take bits out to display in a div. The first one looks like this:
$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805"
dataType: 'json',
success: function(data) {
jQuery.each(data, function() {
alert("HELLO");
alert("Current Cloud Cover = " + this.data.current_condition.cloudcover);
alert("Current Humidity = " + this.data.current_condition.humidity);
});
}
});
the second one looks like this:
var postcode = document.getElementById("address").value;
function getWeather(userName, count) {
$.getJSON(
'http://free.worldweatheronline.com/feed/weather.ashx?q' + postcode + '&format=json&num_of_days=2&key=ec9c2dc5ba201904120805',
{},
showWeather,
//'jsonp'
);
}
function showWeather(day) {
var str = '<ul>';
str += '<h2>Tweets from ' + postcode + '</h2>';
var i = 0;
$.each(day, function(index, value) {
if (i == count) return;
var dt = new Date(value.date);
str += '<p>';
str += value.temp_C; //gets "text" from JSON
str += '</p>';
str += '';
str += '';
i++;
});
}
I want to get the weather information from the JSON URL and display some of the information in a div, can anybody explain how to do this is these two scripts dont work.
$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805",
dataType: 'jsonp', // You need to use 'jsonp' here because it is cross domain request
success: function(data) {
$.each(data, function(index, value) {
alert(value.current_condition[0].cloudcover);
alert(value.current_condition[0].humidity);
alert(value.current_condition[0].weatherDesc[0].value);
alert(value.request[0].query);
alert(value.request[0].query);
$.each(value.weather, function(i, val) {
alert(val.precipMM);
alert(val.weatherDesc[0].value);
})
});
}
});
DEMO
There are a few problems... the following should work (modification of the first block of code).
$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805&callback=?",
dataType: 'jsonp',
success: function(data){
jQuery.each(data, function(){
alert(JSON.stringify(this));
alert("Current Cloud Cover = " + this.current_condition[0].cloudcover);
alert("Current Humidity = " + this.current_condition[0].humidity);
});
}
});
To recap:
You need to use JsonP to circumvent cross-site-scripting restrictions (do that by adding "&callback=?" to the AJAX URL.
The root of the JSON response is data, so you need to write data.data.
The current_condition property is an array-- have to add an indexer (ie, [0]) to access it.

Categories