How to read this JSON response from AJAX - javascript

This is my response from AJAX call
{"screen":[{"screen_name":"SCR1","screen_id":"1"},{"screen_name":"SCR2","screen_id":"2"},{"screen_name":"SCR3","screen_id":"3"},{"screen_name":"SCR4","screen_id":"4"},{"screen_name":"SCR5","screen_id":"5"},{"screen_name":"BIGSCR","screen_id":"6"}]}
success: function(response) {
var jsondata = JSON.stringify(response);
console.log(jsondata);
var html = '';
for (var i = 0; i < jsondata.screen.length; i++) {
var screenName = jsondata.screen[i].screen_name;
var screenId = jsondata.screen[i].screen_id;
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
}
But I keep on getting
Uncaught TypeError: Cannot read property 'length' of undefined at for loop

Try this: It Works. As smooth as silk: (See comment for explanation)
<select id="SCname"></select>
<script>
$.ajax({
dataType: 'json',
//This JSON datatype returns a json encoded response
url:"api/test.php",
//This is the URL From where you fetch the JSON Data
success: function(response){
//Since the response array object has a single array element "screen", we make it myArray
myArray = response["screen"];
console.log(myArray);
//We get six Objects in myArray.
//Thsese are Arrays of your six screens . Now Using Loops
var html = '';
for (var i = 0; i < myArray.length; i++) {
// Each element is inside DOuble Array like: myArray[0]["screen_name"]
var screenName = myArray[i]["screen_name"];
var screenId = myArray[i]["screen_id"];
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
//Check your console ouput
console.log(html);
}
});
</script>

JSON.stringify(object) returns a string. You want a JSON.parse(string) – which returns an object. Alternatively, if your response is already an object, then you don't have to parse it at all:
success: function(jsonData) {
var html = '';
for (var i = 0; i < jsonData.screen.length; i++) {
var screenName = jsonData.screen[i].screen_name;
var screenId = jsonData.screen[i].screen_id;
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);

You don't want to stringifybut to parse. Correct it must be:
var jsondata = JSON.parse(response);
But keep in mind that jQuery possibly is already parsing the JSON for you.

Related

How to print out all array in JS?

I have managed to print out one array but how to do print out all arrays as this is for forum.
$(document).ready(function() {
var comments = document.getElementById("allcomments").value;
//Get Storage
var username = window.localStorage.getItem("username");
// Call Ajax for existing comments
$.ajax({
type: 'GET',
url: 'URL',
success: function(result) {
var arr = JSON.parse(result);
for(var i = 0; i < arr.length; i++) {
var obj = arr[i];
console.log(obj);
var output = document.getElementById("allcomments");
output.innerHTML = (obj.username + ' ' + obj.comment + ' ' + obj.commDate + ' ' + obj.sentiment);
}
}
});
return false;
});
Since you're using jQuery, you should consider using the append() function instead of innerHTML. There are not a lot of valid use cases for innerHTML, you should try to avoid it.

How to Bind to DropDown using Jsonp response?

Hi i am using jQuery Ajax to bind data to dropdown.I am using arcgis rest services as source.I am able to get response but not able to bind to dropdown.Can anybody help this done.
$.ajax({
url: "url",
data: { f: "json", where: "1 = 1 ", returnGeometry: false },
dataType: "jsonp",
success: function(response) {
console.log( response );
var len = response.length;
$("#ddlDistrict > option").remove();
$('#ddlDistrict').append("<option value='-- Select --'>-- Select --</option>");
for (var i = 0; i < len; i++) {
$('#ddlDistrict').append('<option value="' + response[i].DistrictName + '">' + response[i].DistrictName + '</option>');
}
}
});
My console output is
success: function(response) {
console.log( response, typeof response );
if(typeof response == 'string') {
response = JSON.parse(response);
}
var len = response.features.length;
$("#ddlDistrict > option").remove();
$('#ddlDistrict').append("<option value='-- Select --'>-- Select --</option>");
for (var i = 0; i < len; i++) {
console.log(response.features[i]);
$('#ddlDistrict').append('<option value="' + response.features[i].DistrictName + '">' + response.features[i].DistrictName + '</option>');
}
}
From the response it seems you want to display displayFieldName which has a value of 'DistrictName'
SO you have to pass the key name
for (var i = 0; i < len; i++) {
$('#ddlDistrict').append('<option value="' + response[i].displayFieldName+ '">' + response[i].displayFieldName+ '</option>');
}
Now from response I see displayFieldName is just a key., where as features,fieldAliases,fields are array,object & array of object again.
I am not sure if you want to target fields which have name as key and DistrictName as value. If it is o then loop condition need to be changes
for (var i = 0; i < response.fields.length; i++) {
$('#ddlDistrict').append('<option value="' + response.fields[i].displayFieldName+ '">' + response.fields[i].name+ '</option>');
}

How can I print values of nested objects of JSON string?

I have the following JSON response after an XMLHttpRequest:
{
"success":true,
"result":{"1":{"id":"1","question":"What is one + two","answer":"three"},
"2":{"id":"2","question":"two + four","answer":"six"},
"3":{"id":"3","question":"one + three","answer":"for"}
}
}
I want to display all the questions in a bulleted list and all the answers in a bulleted list side-by-side. Right now I have the following (I included this code to add the JSON.parse functionality, should work):
<script type="text/javascript" src="json2.js"></script>
// ...
var response = JSON.parse(xhr.requestText);
var list = document.getElementById('listQuestions');
for (var i = 0 ; i < response.length; i++){
list.innerHTML += '<li>' + response[i].question + '</li>'; // I'm certain this is wrong--I also tried the following but it's not what I'm looking for:
// for (var key in response) {
// console.log("Key: "+key+" value: "+response[key]);
// }
}
// ...
</script>
The result property in your JSON response is an object and not an array. Also, the response variable does not point to the result object but rather the parent, container object so you'll have to access the result object by calling response.result.
var jsonText = '{"success":true,"result":{"1":{"id":"1","question":"What is one + two","answer":"three"},"2":{"id":"2","question":"two + four","answer":"six"},"3":{"id":"3","question":"one + three","answer":"for"}}}';
var response = JSON.parse(jsonText);
var list = document.getElementById('listQuestions');
var results = Object.keys(response.result);
for (var i = 1 ; i <= results.length; i++) {
list.innerHTML += '<li>' + response.result[i].question + ' - ' + response.result[i].answer + '</li>';
}
<div id="listQuestions">
</div>
https://jsfiddle.net/djqrt8z9/
Based on your description I wasn't sure if you wanted two lists because you say you wanted a bulleted list of questions and bulleted list of answers.
var response = {
"success":true,
"result":{
"1":{"id":"1","question":"What is one + two","answer":"three"},
"2":{"id":"2","question":"two + four","answer":"six"},
"3":{"id":"3","question":"one + three","answer":"for"}
}
}
var questions = document.getElementById('listQuestions');
var answers = document.getElementById('listAnswers');
var result = response.result
Object.keys(result).forEach(function(key){
var question = document.createElement('li');
questions.appendChild(question);
question.innerHTML = result[key].question;
var answer = document.createElement('li');
answers.appendChild(answer);
answer.innerHTML = result[key].answer;
})
<ul id="listQuestions"></ul>
<ul id="listAnswers"></ul>
let response = JSON.parse(xhr.requestText);
let qs = [];
for (let obj of response.result) qs.push("<li>"+obj.question+"<\/li>");
document.getElementById('listQuestions').innerHTML = qs.join('');
The above uses the for ... of construct to loop through the values of an object.

Can't return only usernames from json data fetched through a php page

I am able to get json data from an external php page and print it on the JavaScript console. But these are in the form objects. The following is the data I recieved on my console:
[{"id":"1","username":"iammuneeb","password":"4297f44b13955235245b2497399d7a93","name":"Mirza Muneeb"},{"id":"2","username":"iamfaiz","password":"4297f44b13955235245b2497399d7a93","name":"Faiz"}]
How can I extract only username and turn it into an ordered list. (ol)
This is what I have done so far:
$(document).ready(function (e) {
$('#delete').click(function (e) {
var jsonData = getResultsInJson(username);
jsonData.success(function (data) {
var output = "<ol>";
for (var i in data) {
output += "<li>" + data.username + "</li>";
}
output += "</ol>";
$('#placeholder').html(data);
console.log(data.username);
});
});
});
This is getResultsInJson():
function getResultsInJson(sql) {
return $.ajax({
url: 'commands.php',
data: 'results=' + sql,
dataType: 'json'
});
}
when you use the for(x in y) format, x is the key, and y is the array or object. Since i is just the key, you need to use it as one:
for (var i in data) {
output += "<li>" + data[i].username + "</li>";
}
Do you need them in alphabetically?
Try something like this:
$(document).ready(function() {
var json = [{"id":"1","username":"iammuneeb","password":"4297f44b13955235245b2497399d7a93","name":"Mirza Muneeb"},{"id":"2","username":"iamfaiz","password":"4297f44b13955235245b2497399d7a93","name":"Faiz"}];
var usernames = new Array();
$.each(json, function(index, object) {
usernames[index] = object.username;
});
var sorted = usernames.sort();
var output = '';
$.each(sorted, function(index, value) {
output += '<li>' + value + '</li>';
});
$('#placeholder').html('<ol>' + output + '</ol>');
});

how to view json file data in view source code

Let suppose i have a json file
and i can read this file in my script like this
$(document).ready(function () {
$.ajax({
type: "GET",
url: "Package.html",
dataType: "json",
success: function (data) {
var t = '';
for (var i = 0; i < data.yearData.length; i++) {
var mainStoryTitle = data.yearData[i].players;
for (var j = 0; j < mainStoryTitle.length; j++) {
var storyTitle = mainStoryTitle[j].name;
var topStoryContent = mainStoryTitle[j].description;
var storyImage = mainStoryTitle[j].image;
t = t + '<div class="content">';
t = t + '<article class="topcontent">';
t = t + '<header class="top" id="top1"><h2>' + storyTitle + '</h2></header>';
t = t + '<header class="bottom">';
t = t + '<h6><img src="' + storyImage + '" height=150 width=200>' + '</h6></header>';
t = t + '<content class="hide" id="content_' + j + '"><p>' + topStoryContent + '</p></content>';
t = t + '</article>';
t = t + '</div>';
}
}
$(".content").html(t);
},
error: function (e, ts, et) { alert(ts) }
})
});
and then i put this script in my html file.
So when i run this, it works properly but the problem is when i click on view source then inside it shows the path of json instead of exact data.
Hope you got the problem and please revert me asap.thanx
Instead of using alert, use console.log(ts) this will post the JSON file into your console. From there you can easily look around and see the JSON file by clicking the down arrow.
console.log(data); shows as:
> Object {Data: Array[2], ResponseMessage: "", Success: true}
console.log(JSON.stringify(data)); shows as:
{"Data":[{"ControllerID":2,"Description":"Aeon Power Monitor","DevType":1,"ID":1,"Name":"Power Monitor"},{"ControllerID":2,"Description":"Aeon Power Switch","DevType":2,"ID":2,"Name":"Switch"}],"ResponseMessage":"","Success":true}

Categories