Unable to populate Table with Ajax Json response - javascript

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
}

Related

Jquery .GET function from JSON data

The jQuery below illustrates how I get the products from https://dummyjson.com/products. However, I don't know how to iterate the loop to retrieve each of the 30 products in the link and the details of each product.
$.get("https://dummyjson.com/products/1")
.done(function(data, textStatus, jqXHR){
console.log("typeof(data) is: " + typeof(data));
console.log("data is: "+ data);
console.log(data.length);
var result = [];
result = JSON.parse(JSON.stringify(data));
console.log(typeof(result));
console.log(result.length);
var keys = Object.keys(result);
keys.forEach(function (key) {
console.log("forEach");
console.log(key, result[key]);
//console.log(result[0]);
});
})
.fail(function(jqXHR, textStatus, errorThrown){
alert("error");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
You should iterate through the object itself instead of the keys. Also, use let instead of var (see here).
$.get("https://dummyjson.com/products/1")
.done(function(data) {
let result = JSON.parse(JSON.stringify(data));
$.each( result, function( key, value ) {
console.log( key + ": " + value );
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
For multiple products you need another for loop to iterate through each product:
$(document).ready(function() {
$.get("https://dummyjson.com/products")
.done(function(data) {
let result = JSON.parse(JSON.stringify(data));
$.each(result, function( key, products) {
for (let i = 0; i < products.length; ++i) {
console.log(products[i].id);
console.log(products[i].title);
console.log(products[i].description);
}
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Thats is totally depends upon how was your reponse are.
If your response like this.
{
"status": true,
"data" : [
{
"id": 1,
"name": "xyz",
},
{
"id": 2,
"name": "xyz",
}
]
}
then you have to use following code:
$.get('/your-url', function(response) {
if(response.status) {
$.each(response.data, function(index, item) {
console.log(item);
})
} else {
alert('Your API sent false status')
}
})
Otherwise your response something like this.
[
{
"id": 1,
"name": "xyz",
},
{
"id": 2,
"name": "xyz",
}
]
then you have to use following code:
$.get('/your-url', function(response) {
$.each(response, function(index, item) {
console.log(item);
})
})

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.

Populate SELECT with data from JSON file using ajax

I am new with using JSON file for web development and I got interest with it due to it usefulness and power in terms of data storage. Right now, I want to use JSON file via path instead of adding the JSON into the same page because it make the page full of JSON data. Yesterday I have the following codes but only adding the JSON file into the same page not into separate one. How can I use JSON file path instead of adding JSON into the same page?
HTML
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="form-group">
<label for="supplier_bank_name">Bank Name</label>
<select class="form-control selectpicker" data-live-search="true" id="supplier_bank_name" name="supplier_bank_name"></select>
</div>
</div>
PREVIOUS CODE
This code will work well but JSON only in the same page.
var allbanks = {
banks:[
{
"index": 0,
"bankname": "1st Source Bank",
"location": "USA",
"website": "www.1stsource.com"
},
{
"index": 1,
"bankname": "1st Summit Bank",
"location": "North America",
"website": "www.1stsummit.com"
},
{
"index": 2,
"bankname": "A.J. Smith Federal Savings Bank",
"location": "USA",
"website": "www.ajsmithbank.com"
}
]
};
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">Select Bank</option>';
for (var i = 0; i < allbanks.banks.length; i++) {
listItems += "<option data-tokens='" + allbanks.banks[i].bankname + "' value='" + allbanks.banks[i].bankname + "'>" + allbanks.banks[i].bankname + "</option>";
}
$("#supplier_bank_name").html(listItems);
});
SCRIPT TODAY
Not working and looking for solution
var allbanks = (function () {
var allbanks = null;
$.ajax({
'async': false,
'global': false,
'url': 'js/allbanks.json',
'dataType': "json",
'success': function (data) {
allbanks = data;
}
});
return allbanks;
})();
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">Select Bank</option>';
for (var i = 0; i < allbanks.banks.length; i++) {
listItems += "<option data-tokens='" + allbanks.banks[i].bankname + "' value='" + allbanks.banks[i].bankname + "'>" + allbanks.banks[i].bankname + "</option>";
}
$("#supplier_bank_name").html(listItems);
});
JSON
{
"banks": [
{
"index": 0,
"bankname": "1st Source Bank",
"location": "USA",
"website": "www.1stsource.com"
},
{
"index": 1,
"bankname": "1st Summit Bank",
"location": "North America",
"website": "www.1stsummit.com"
},
{
"index": 2,
"bankname": "A.J. Smith Federal Savings Bank",
"location": "USA",
"website": "www.ajsmithbank.com"
}
]
}
Since $.ajax is an asynchronous function, the code within allbanks will execute in this order:
Assign allbanks to null
Make ajax request
Return allbanks, which is still set to null because the ajax request has not returned yet.
Receive data and assign that to allbanks (This will not return out of the function and will not be set to the allbanks variable on the first line)
To fix this, you should use the data within the success portion of the ajax request.
function createSelectItems(data) {
var listItems = '<option selected="selected" value="0">Select Bank</option>';
for (var i = 0; i < data.banks.length; i++) {
listItems += "<option data-tokens='" + data.banks[i].bankname + "' value='" + data.banks[i].bankname + "'>" + data.banks[i].bankname + "</option>";
}
$("#supplier_bank_name").html(listItems);
}
$(document).ready(function () {
$.ajax({
'async': false,
'global': false,
'url': 'js/allbanks.json',
'dataType': "json",
'success': function (data) {
createSelectItems(data);
}
});
});
EDIT
See comments below:
allbank_connect.js
// Code goes here
var allbanks = (function () {
var allbanks = null;
$.ajax({
'async': false,
'global': false,
'url': 'js/allbanks.json',
'dataType': "json",
'success': function (data) {
allbanks = data;
}
});
return allbanks;
})();
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">Select Bank</option>';
for (var i = 0; i < allbanks.banks.length; i++) {
listItems += "<option data-tokens='" + allbanks.banks[i].bankname + "' value='" + allbanks.banks[i].bankname + "'>" + allbanks.banks[i].bankname + "</option>";
}
$("#supplier_bank_name").html(listItems);
});

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

Problem with append json_encode

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(', ') + '');
});

Categories

Resources