I am getting proper json response and I put javascript alert to check it, but not able to fill the data into text box using the response,why following code is not returning the items list to text box dropdown.
response($.map(data, function (item) {
alert(item.task_id);
// getPreventDefault();
return { label: item.module_task, value: item.task_id};
}))
is not working, i.e. it is not filling out the text box even though I got item.task_id and item.module_task correctly inside the success block.
**
enter code here
(function( $ ){
$(document).ready(function(){
$(document).on('click', '.autocomplete', function(){
$('[id^="repairRecordsTask"]').each(function() {
$(this).autocomplete({
minLength:3,
open: function() {
// After menu has been opened, set width to 100px
$('.ui-menu')
.width(100);
} ,
source : function(request, response) {
//alert("inside the autocomplete ");
$.ajax({
// alert("inside ajax");
url : "<%=request.getContextPath()%>/Task_Search_Controller.do",
type : "GET",
minLength: 3,
contentType: "application/json; charset=utf-8",
autoFill: true,
//term is the input from request object
data : {
term : request.term
},
dataType : "json",
success : function(data) {
alert(data.toString());
response($.map(data, function (item) {
alert(item.task_id);
// getPreventDefault();
return { label: item.module_task, value: item.task_id};
}))
},
select: function (event, ui) {
alert("here");
$(this).val(ui.item.module_task);
//$(this).val(ui.item.value);
//$("#txtAllowSearchID").val(ui.item.value);
}
/* error: function(jqXHR, textStatus, errorThrown){
//alert("error is " + errorThrown.toString());
// alert("error is " + textStatus);
// alert("json reponse is " +jqXHR.responseJSON );
// alert("json reponse is " +jqXHR.responseJSON );
}*/
});
}
});
});
$(document).on('autocompleteselect', '.autocomplete', function( event, ui ) {
// alert("selected " + ui.item.value);
var selectedTask = ui.item.value;
lookUpDMCodeRea(selectedTask);
});
});
});
})( jQuery );
and my json looks like this
my json is like this
var data =[
{
"task_id": "1539",
"module_task": "810-01"
},
{
"task_id": "1540",
"module_task": "810-02"
},
{
"task_id": "1541",
"module_task": "810-04"
},
{
"task_id": "13175",
"module_task": "810-04"
}
]
i think that the source should be the server code url where you get the json , and this is working for me , with php
jQuery( this ).autocomplete({
source: "<?php echo site_url("search_users.php"); ?>",
minLength: 1,
select: function( event, ui ) {
//do something when a item is selected
console.log(ui.item.id);
}
}).data( "uiAutocomplete" )._renderItem = function( ul, item ) {
return jQuery( "<li></li>" )
.data( "item.autocomplete", item )
.append(
"<a style='cursor:pointer;'>"+
"<table>" +
"<tr>" +
"<td width='30'>" +
"<img src= '"+item.img+"' width='20' height='25' /> " +
"</td>" +
"<td>" +
item.label +
"</td>" +
"</tr>" +
"</table>"+
"</a>"
)
.appendTo( ul );
};
and my json is :
[
{
"label": "Juan Perez",
"value": "Juan Perez",
"id": 25,
"img": "http://localhost/admin/resources/as45265f."
},
{
"label": "Juan Perez",
"value": "Juan Perez",
"id": 25,
"img": "http://localhost/admin/resources/as45265f.jpg"
},
{
"label": "Juan Perez",
"value": "Juan Perez",
"id": 25,
"img": "http://localhost/admin/resources/as45265f.jpg"
},
{
"label": "Juan Perez",
"value": "Juan Perez",
"id": 25,
"img": "http://localhost/admin/resources/as45265f.jpg"
}
]
Related
I have this JSON response i need to get the values of some elements inside this response.
The values i want to display is the value of "makeup" which has to elements in it which are, "eyemakeup" & "lipmakeup"
i want to display it in an alert / or textbox.
[
{
"faceId": "90c30c46-2a51-4754-bff4-5079caf7e322",
"faceRectangle": {
"top": 91,
"left": 101,
"width": 121,
"height": 121
},
"faceAttributes": {
"smile": 0,
"headPose": {
"pitch": 0,
"roll": -0.8,
"yaw": -2.3
},
"gender": "male",
"age": 30.3,
"facialHair": {
"moustache": 0.1,
"beard": 0.5,
"sideburns": 0.3
},
"glasses": "NoGlasses",
"emotion": {
"anger": 0.013,
"contempt": 0.003,
"disgust": 0,
"fear": 0,
"happiness": 0,
"neutral": 0.983,
"sadness": 0.001,
"surprise": 0
},
"blur": {
"blurLevel": "medium",
"value": 0.28
},
"exposure": {
"exposureLevel": "goodExposure",
"value": 0.61
},
"noise": {
"noiseLevel": "medium",
"value": 0.39
},
"makeup": {
"eyeMakeup": false,
"lipMakeup": true
},
"accessories": [],
"occlusion": {
"foreheadOccluded": false,
"eyeOccluded": false,
"mouthOccluded": false
},
"hair": {
"bald": 0.02,
"invisible": false,
"hairColor": [
{
"color": "brown",
"confidence": 1
},
{
"color": "black",
"confidence": 0.78
},
{
"color": "blond",
"confidence": 0.23
},
{
"color": "other",
"confidence": 0.13
},
{
"color": "red",
"confidence": 0.09
},
{
"color": "gray",
"confidence": 0.03
}
]
}
}
}
]
The below is the javascript i have used so far and it is not giving me the correct values.
<script type="text/javascript">
function processImage() {
var subscriptionKey = "mysubkey";
var uriBase = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect";
// Request parameters.
var params = {
"returnFaceId": "true",
"returnFaceLandmarks": "false",
"returnFaceAttributes": "age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise",
};
// Display the image.
var sourceImageUrl = document.getElementById("inputImage").value;
document.querySelector("#sourceImage").src = sourceImageUrl;
// Perform the REST API call.
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
// Request body.
data: '{"url": ' + '"' + sourceImageUrl + '"}',
})
.done(function(data) {
// Show formatted JSON on webpage.
$("#responseTextArea").val(JSON.stringify(data, null, 2));
$("#demo2").val(this.responseText);
var data =[JSON.stringify(data, null, 2)];
var json = JSON.parse(data);
alert(json["eyeMakeup"]);
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Display error message.
var errorString = (errorThrown === "") ? "Error. " : errorThrown + "
(" + jqXHR.status + "): ";
errorString += (jqXHR.responseText === "") ? "" :
(jQuery.parseJSON(jqXHR.responseText).message) ?
jQuery.parseJSON(jqXHR.responseText).message :
jQuery.parseJSON(jqXHR.responseText).error.message;
alert(errorString);
});
};
</script>
First add contentType:"json" your $.ajax configuration,
Then you don't need to parse data to json since it's already json type
So remove this line.
var data =[JSON.stringify(data, null, 2)];
As per your json you added to question you receive a array of object
To get data from first object
Try this :
For eyeMakeup use :
data[0].faceAttributes.makeup.eyeMakeup
and for lipMakeup use
data[0].faceAttributes.makeup.lipMakeup
Or you can loop through your result data if you want to access multiple object data
$.each(data,function(obj,function(){
console.log(obj.faceAttributes.makeup.eyeMakeup);
console.log(obj.faceAttributes.makeup.lipMakeup);
})
$.ajax( {
url:'data.php',
data:{
'a' : 1,
'b': 2
},
type:'post',
cache:false,
dataType:'json',
success:function(data) {
do something...
},
error : function() {
do something
}
});
try use ajax like up above
I am sending this valid JSON as a response from my webservice call
[
[
{
"id": 123,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 1234,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 12345,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 123456,
"vendorName": "MahalakshmiCounter",
"item": "Chocltae"
}
]
]
This is my Jquery
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://192.168.2.46:8086/Poller/poll/initial',
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.id + '</td><td>' + item.vendorName + '</td><td>' + item.item + '</td></tr>';
});
$('#records_table').append(trHTML);
},
error: function (e) {
$("#divResult").html("WebSerivce unreachable");
}
});
});
<table id="records_table" border='1'>
<tr>
<th>Rank</th>
<th>Content</th>
<th>UID</th>
</tr>
With this the result is looking like this in browser
I am editing my question
Edited Part
Due to the cross domain restrictions , i am forming my JSON into jsonp as shown below
This is my ajax jquery request
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://192.168.2.46:8086/Poller/poll/initial',
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
jsonp: false,
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.id + '</td><td>' + item.vendorName + '</td><td>' + item.item + '</td></tr>';
});
$('#records_table').append(trHTML);
doPoll();
},
error: function (e) {
$("#divResult").html("WebSerivce unreachable");
}
});
});
Due to the jsonCallback , its not forming a valid JSON response and i am getting undefined when forming the table
IS there anyway i can from the valid JSON response ??
jsonCallback([
[
{
"id": 123,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 1234,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 12345,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 123456,
"vendorName": "MahalakshmiCounter",
"item": "Chocltae"
}
]
])
You have to have one more $.each() loop:
$.each(response, function (i, item) {
$.each(item, function(_, o){
trHTML += '<tr><td>' + o.id + '</td><td>' + o.vendorName + '</td><td>' + o.item + '</td></tr>';
});
});
You appear to be having another array in that result. Try to loop one more time, like this for instance: http://jsfiddle.net/yH942/1/
$.each(jsonResponse, function(key, array) {
$.each(array, function(k, object) {
// your code goes here
});
});
Parse your object after receiving or use $.getJSON instead of $.ajax. You are trying to use a string as an object.
success: function (response) {
response = JSON.parse(response);
}
your data is an array in an array, and you consider it only as an array
try to do the same each loop on response[0] for example
EDIT
I'm not sure you can use jquery each on a JSON object, instead you should use :
for(var i in response) {
response[i]; // do something with it
}
I have an endpoint with two JSON Objects as follows:
{
"main" {
"id": 1,
"title": Main Title,
},
{
"secondary" {
"id": 3,
"title": Secondary Title,
},
I am using backbone and have the following $each function, but using dot notation, I can't seem to be able to browse to the titles (ex. main.title or secondary.title). What am I missing?
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
$.each(response, function (index, value) {
console.log(value.main.title);
$("#test2").append('<li>' + value.main.title + '</li>');
});
In my console, it gives an error of: Uncaught TypeError: Cannot read property 'title' of undefined
Assuming your JSON is actually valid when returned (it isn't valid the way you show it), try
$("#test2").append('<li>' + value.title + '</li>');
Your actual JSON should look like:
{
"main": {
"id": 1,
"title": Main Title,
},
"secondary": {
"id": 3,
"title": Secondary Title,
}
}
If you just want the value of main, instead of using $.each(), remove that entire block and do:
$("#test2").append('<li>' + response.main.title + '</li>');
And your final code would look something like:
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
if (response.main.title !== 'undefined'){
$("#test2").append('<li>' + value.main.title + '</li>');
}else{
console.log('Main is undefined');
}
}
});
Final Edit: It looks like you want JSON like:
{
"main": [{
"id": 1,
"title": "Main Title"
}, {
"id": 2,
"title": "Main Title 2"
}, {
"id": 3,
"title": "Main Title 3"
}],
"secondary": [{
"id": 5,
"title": "Secondary Title 5"
}, {
"id": 34,
"title": "Secondary Title 34"
}, {
"id": 36,
"title": "Secondary Title 36"
}]
}
If that is the case your code would look like:
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
$.each(function(index, value){
$.each(item_index, item_value){
$("#test2").append('<li>' + item_value.title + '</li>');
}
});
}
});
The problem lies with input JSON, it should be
{
"main" :{
"id": 1,
"title": "Main Title"
},
"secondary":{
"id": 3,
"title": "Secondary Title"
}
}
I have 2 select menus on my page.
First have 3 values: All, Active, Unactive and second is filled with data that comes from server.
I need to connect them, so that when I select an option from the first select menu, the second select will have only certain options (filter second select menu)
My idea was to get data from server with 3 elements:
[ { "Id": 1, "Name": "Active One", "Active":true },
{ "Id": 2, "Name": "Active Two", "Active":true },
{ "Id": 3, "Name": "Unactive One", "Active":false },
{ "Id": 4, "Name": "Unactive Two", "Active":false } ]
Second thing that I do is adding all options with custom attribute to that select:
<option value=' + n[index].Id + ' data-active='+n[index].Active+'>' + n[index].Name + '</option>
I have problem with filtering second select.
I've wrapped filling second select inside a plugin so it will be easier to reuse it.
Here is jsFiddle demo: http://jsfiddle.net/Misiu/pr8e9/4/
What I would like this to work is after filling select from server user will be able to select every option from second select, but when he will change first select the second one will update-show only appropriate options.
So if he'll select Active he will be able to select only Active One or Active Two.
EDIT: This is working solution thanks to #oe.elvik
Alternative solution:
(function ($) {
var meinData;
$.fn.createOptions = function(filter) {
var $this = this;
var n = meinData
var list = "";
for (var index = 0; index < n.length; index++) {
if(filter == -1 || (filter == 1 && n[index].Active) || (filter == 0 && !n[index].Active)){
list += '<option value=' + n[index].Id + ' data-active='+n[index].Active+'>' + n[index].Name + '</option>';
}
}
$this.filter("select").each(function () {
$(this).empty();
$(this).append(list);
if ($.ui.selectmenu && defaults.selectmenu) {
$this.selectmenu();
}
});
}
$.fn.ajaxSelect = function (options) {
var $this = this;
//options
var settings = $.extend({}, defaults, options);
//disable select
if ($.ui.selectmenu && settings.selectmenu && settings.disableOnLoad) {
$this.selectmenu('disable');
}
//ajax call
$.ajax({
type: settings.type,
contentType: settings.contentType,
url: settings.url,
dataType: settings.dataType,
data: settings.data
}).done(function (data) {
meinData = data.d || data;
$($this).createOptions(-1)
settings.success.call(this);
}).fail(function () {
settings.error.call(this);
});
return this;
};
var defaults = {
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/echo/json/',
dataType: 'json',
data: null,
async: true,
selectmenu: true,
disableOnLoad: true,
success: function () {},
error: function () {}
};
})(jQuery);
$(function () {
var data = {
json: $.toJSON({
d: [{ "Id": 1, "Name": "Active One", "Active":true }, { "Id": 2, "Name": "Active Two", "Active":true },{ "Id": 3, "Name": "Unactive One", "Active":false }, { "Id": 4, "Name": "Unactive Two", "Active":false }]
}),
delay: 2//simulate loading
};
function ok() {
$('select#me').selectmenu({ select: function(event, options) {
$('select#mein').createOptions(options.value)
}
});
}
function error() {
alert('there was a problem :(');
}
$('select#me').selectmenu().selectmenu('disable');
$('select#mein').selectmenu().ajaxSelect({
data: data,
success: ok,
error: error
});
});
I need to fetch the values from this JSON in my java script this is coming from jsp:
[{
"selectionName": "Select",
"subSelections": [{
"id": 4,
"subSelectionName": "Select",
"description": "Deepmala"
}
]
}, {
"selectionName": "week14",
"subSelections": [{
"id": 7,
"subSelectionName": "1",
"description": ""
}
]
}, {
"selectionName": "test",
"subSelections": [{
"id": 6,
"subSelectionName": "test",
"description": ""
}
]
}, {
"selectionName": "select",
"subSelections": [{
"id": 3,
"subSelectionName": "sub-select",
"description": "Created by Prakash"
}
]
}, {
"selectionName": "testcreate",
"subSelections": [{
"id": 1,
"subSelectionName": "testcreate",
"description": ""
}
]
}, {
"selectionName": "by htmlwidget",
"subSelections": [{
"id": 5,
"subSelectionName": "by htmlwidget",
"description": "created by html widget"
}
]
}
]
Any suggestions? I am tring to fetch it like this:
function getSelection() {
var options = "";
$.getJSON('../r3/selection.jsp').done(function(json) {
//alert(json.selectionName);
// alert(json.subSelections);
// options += '<option value="' + value. selectionId + '">' + value.selectionName + '</option>';
$.each(json.subSelections, function(index, value) {
options += '<option value="' + value. subSelectionName + '">' + value. description + '</option>';
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$(document.body).append(select);
}).fail(function (jqxhr, textStatus, error) {
alert(' fail json : '+error);
});
}
//alert(json.selectionName);
// alert(json.subSelections); inside the loop gives me undefined value.
Try this:
$.each(json, function (key, data) {
$.each(data.subSelections, function (index, values) {
options += '<option value="' + values.subSelectionName + '">' + values.description + '</option>';
});
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$('body').append(select);