Problem with append json_encode - javascript

I want append service by jQuery.each(), but it in my js code not worked?
This is my output from PHP code:
{
"data": [{
"service": ["shalo", "jikh", "gjhd", "saed", "saff", "fcds"],
"address": "chara bia paeen"
}, {
"service": ["koko", "sili", "solo", "lilo"],
"address": "haminja kilo nab"
}, {
"service": ["tv", "wan", "hamam", "kolas"],
"address": "ok"
}]
}
This is is my jQuery code:
$.ajax({
type: "POST",
dataType: "json",
url: 'get_residence',
data: dataString_h,
cache: false,
success: function (respond) {
$.each(respond.data, function (index, value) {
$('ol li').append('' + value.service + '');
});
},
"error": function (x, y, z) {
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
What do i do?

You will need another $.each loop because service is an Array:
$.each(respond.data, function (index, value) {
$.each(value.service, function () {
$('ol li').append('' + this + '');
});
});
to just format the array:
$.each(respond.data, function () {
$('ol li').append('' + this.service.join(', ') + '');
});

Related

Unable to parse JSON filename object

I am unable to parse a JSON object (whatever.png) for some reason, I get [object%20Object] which is strange as I never have this issue, as its clearly simple to resolve or stringify and debug if in doubt.
My jQuery code:
$(function () {});
$.ajax({
url: '/shouts/get/ajax',
method: 'GET',
dataType: 'JSON',
success: function (res) {
res.forEach((element, i) => {
data = {
message: element['message'],
date: element['date'],
descr: element['descr'],
last_login: element['last_login'],
added: element['added'],
user: element['user'],
username: element['username'],
user_id: element['user_id'],
avatar: element['avatar'],
badges: element.badges
}
var result = XBBCODE.process({
text: data.message,
removeMisalignedTags: false,
addInLineBreaks: false
});
let allstring = '<div class="shoutbox-container"><span class="shoutDate" style="width:95px">' + jQuery.timeago(data.date) + ' <span style="color:#b3b3b3">ago</span><span id="user_badge_' + i + '"></span></span><span class="shoutUser"><a class="tooltip-shoutuser" title="' + data.username + '" href="/user/?id=' + data.user_id + '"><img src="' + data.avatar + '" class="shout-avatar" /></a></span><span class="shoutText">' + result.html + '</span></div><br>';
document.getElementById('shoutbox').innerHTML += allstring;
let badges = [];
data.badges.forEach(badge => {
badges.push('<img src="/images/avatars_gear/' + badge + '">').innerHTML += badges; // <--- Object bug
});
badges.forEach(badge => {
document.getElementById('user_badge_' + i).innerHTML += badge;
});
});
$('.shoutbox-container').filter(function () {
return $(this).children().length === 3;
}).filter(':odd').addClass('shoutbox_alt');
$('.shoutbox-container').each(function () {
$(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('shoutbox_alt');
});
$('.tooltip-shoutuser').tooltipster({
animation: 'grow',
delay: 200,
theme: 'tooltipster-punk'
});
}
});
JSON output from PHP:
[
{
"badges": [],
"username": "tula966",
"message": "perk added for [url=/user/?id=39691]tula966[/url]",
"avatar": "images/avatars/0f885488eb90548b5b93899615c5b838d2300bdb_thumb.jpg",
"date": "2022-02-04 01:00:01",
"last_login": "2022-02-03 12:36:06",
"user_id": "39691"
},
{
"badges": [
{
"image": "star.png",
"descr": " Star Power"
},
{
"image": "toolbox.png",
"descr": "Worker"
}
],
"username": "Tminus4",
"message": "testing testing",
"avatar": "images/avatars/8cc11eb4cb12c3d7e00abfba341c30b32ced49be_thumb.jpg",
"date": "2022-02-04 01:00:00",
"last_login": "2022-02-03 10:52:08",
"user_id": "1"
}
]
badge is not pushing the PNG file names from the JSON response to the DIV. I cant figure this out. This same code structure works perfectly on 3 other areas using the same JSON structure and logic, in fact more complex in our Site Polls area without any issues.
I also attempted to force the object with json_encode($array, JSON_FORCE_OBJECT) on the PHP side, which breaks the JS - and I have never needed to utilize that before in any case.
However this seems to differ greatly in this case. Any help is appreciated.

How to set json model with array of data returned from function

I have a sapui5 application:
I have an xml view called "Submission.view and corresponding controller called "submission.controller".
I have method which is fetching some question id's from a service using certain input parameters.
For example if i pass "null" and "previous" it gives me a json response as:
[
{
"__type__": "QuestionOutput",
"QuestionType": "",
"QuestionID": 51,
"YesNo": "",
"Mandatory": false
},
{
"__type__": "QuestionOutput",
"QuestionType": "",
"QuestionID": 52,
"YesNo": "",
"Mandatory": false
},
{
"__type__": "QuestionOutput",
"QuestionType": "",
"QuestionID": 53,
"YesNo": "",
"Mandatory": false
}
]
Now i want to pass each of the questionid's like 51,52,53 to another method which calls a rest service to fetch the descriptions for the above questionid's from hana data base.
getBpmRules: function(sToken, sQuestionId, sAnswer) {
var that = this;
this.showBusy();
jQuery.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
async: false,
url: "/bpmrulesruntime/rules-service/v1/rules/invoke?rule_service_name=SelfServiceRule::QuestionRuleService",
context: that,
xhrFields: {
withCredentials: true
},
headers: {
'X-CSRF-Token': sToken
},
data: JSON.stringify([{
"__type__": "QuestionInput",
"QuestionID": "" + sQuestionId + "",
"Answer": "" + sAnswer + ""
}]),
error: function(jqXHR, textStatus, errorThrown) {
that.hideBusy();
sap.m.MessageBox.alert(textStatus + " - " + errorThrown + " : " + jqXHR.responseText, {
icon: sap.m.MessageBox.Icon.ERROR,
title: this.getText("error")
});
},
success: function(data, textStatus, jqXHR) {
var questiondesc = [];
if (data.length !== 0) {
var desc = [];
//this.getModel("questionModel").setProperty("/questionDescription", data);
for (var i = 0; i < data.length; i++) {
desc = that.getQuestionDescriptionById(data[i].Question, sToken);
}
}
that.hideBusy();
this._oManagerBusy.setVisible(false);
this._showSendDialog();
}
});
}
After getting the json data i am just looping and passing the question ids to another method to get the description for each question which again is a json response.
getQuestionDescriptionById: function(id, token) {
jQuery.sap.log.debug("Getting question by Id");
var questionDescription = [];
this.getComponent().ajax({
method: "GET",
url: "/selfservice/rest/question/admin/questionid/" + id,
contentType: "application/json",
context: this,
headers: {
'X-CSRF-Token': token
},
error: function(jqXHR, textStatus, errorThrown) {
this.getModel("resources").setProperty("/ticketSubmitMessage", this.getModel("i18n").getProperty("sendDialogText"));
this._oManagerBusy.setVisible(false);
this._showSendDialog();
},
success: function(data, textStatus, jqXHR) {
//oModel.loadData(“json/Item.json”);
// this.getView().setModel(new JSONModel(data.question,"questionDescription"));
if (data.length !== 0) {
questionDescription.push(data);
}
}
});
return questionDescription;
},
Issue:
I am not able to set the model for the view with the json response that i am getting from the second method since for each questionid it goes to the next method "getQuestionDescriptionById" and even though i return the response..it doesn't work.
Can you please let me know how to set a json model for each response that i get for each question id.
Thanks !!

jquery autocomplete json response not filling up the textbox

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"
}
]

Unable to populate Table with Ajax Json response

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
}

unable to read json file generated from gson library

This is part of javascript file I am using to read json file.
function initSearchInfo() {
var tagContent = "";
var tagsCount = 15;
var i = 0;
$.ajax({
type : "GET",
url : JSON_URL + SEARCH_HISTORY_JSON + EXT_JSON + versionParam,
dataType : "json",
contentType : "application/json",
async : false,
success : function(data) {
$.each(data.count, function(key, val) {
i++;
if (i > tagsCount) {
return false;
} else {
tagContent += "<li><a data-weight=" + val + " href='"
+ GLOBAL_SEARCH_URL + key + "'>" + key
+ "</a></li>";
}
});
$("#taglist").html(tagContent);
},
error : function(xhr, status, error) {
$("#tagCloud").html(getMessage(tagcloud.error));
$("#searchHistory").hide();
console.log(status);
}
});
}
I am able to read this json file(1) :
{
"count": {
"scm": {
"count": 22,
"date": "2013-05-08"
},
"java7": {
"count": 22,
"date": "2013-05-08"
},
"groovy": {
"count": 22,
"date": "2013-05-08"
},
"ldap": {
"count": 21,
"date": "2013-04-25"
}
},
"date": "10Oct2013"
}
But when I read this file (2):
{"count":"{\"ldap\":{\"count\":15,\"date\":\"2013-04-04\"},\"myplace\":{\"count\":12,\"date\":\"2013-05-08\"},\"ts-ws1\":{\"count\":11,\"date\":\"2013-05-08\"},\"hbase workshop\":{\"count\":11,\"date\":\"2013-05-08\"},"date":"11 Oct 2013"}
My code breaks when I try to read file (2).
File (2) is produced by gson library.But file (1) is written by me.
Seems like there is syntax error with the file giving error.
Value of "count" key is in double quotes and they don't end properly.
file(2) is not a valid json file. You can't have a double quote before the second { and also you can't have backslash before the double quotes. Please post your code that generates file(2).

Categories

Resources