I'm trying to display Objects received through JSON arrays, communicating in AJAX with my backend server (Django). All the AJAX/Communication part works well. I want to display the received objects in a chatbox.
This is my arrays
However, my code gets undefined variables when displaying the Arrays.
HTML:
<div id="display"></div>
JS:
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: 'GET',
url : "/checkview",
success: function go(response){
console.log(response);
$("#display").empty();
for (var model in response.models_to_return)
{
var temp="<div class='container darker'><b>"+ model.user_id +"</b><p>"+ model.room +"</p><span class='time-left'>"+ model.datetime +"</span></div>";
$("#display").append(temp);
}
},
error: function(response){
//alert('An error occured')
}
});
},1000);
})
</script>
Front-end ouput
You can use forEach for json array loop.
Here is code.
response.models_to_return.forEach(function(model, index) {
console.log(model);
});
Full exmaple:
const models = [
{fname:"John", lname:"Doe", age:25},
{fname:"John2", lname:"Doe2", age:26},
{fname:"John3", lname:"Doe3", age:27}
];
models.forEach(function(model) {
console.log(model.fname);
});
Use for...of to loop over the elements of an array. for...in should instead be used for iterating over properties.
for (const model of response.models_to_return)
Related
I have a well running AJAX request that queries data from a third party API that returns the data in JSON. I now want to assign the values from the returned JSON data to javascript variables to make further manipulation to the data itself in my AJAX success function before updating the frontend.
In the below example I would like to assign the value of key name to my Javascript team variable.
What would be the best way to accomplish this?
This is the returned structure:
{
"api":{
"results":1,
"teams":[
{
"team_id":66,
"name":"Barcelona",
"code":null,
"logo":"Not available in Demo",
"country":"Spain",
"founded":1899,
"venue_name":"Camp Nou",
"venue_surface":"grass",
"venue_address":"Carrer d'Ar\u00edstides Maillol",
"venue_city":"Barcelona",
"venue_capacity":99787
}
],
This is my AJAX request:
$('ul.subbar li a').on('click', function(e) {
e.preventDefault();
var team_id = $(this).attr("id");
console.log(team_id);
$.ajax({
method: "GET",
dataType: "json",
url: "https://cors-anywhere.herokuapp.com/http://www.api-football.com/demo/api/v2/teams/team/" + team_id,
success: function(response) {
var team_data = response
console.log(team_data)
team = // how to assign team name from API callback to variable
console.log(team)
$("#selectedClub").html(response);
}
});
});
You can use dot notation to navigate through objects
team_data.api.teams[0].name //output: "barcelona"
In you example there is only one item inside teams array, so the above example should works fine, but let's suppose that in your response there is more than 1 team on teams then you could do something like this:
var teamList = [];
$.each(team_data.api.teams, function(index, team){
teamList.push(team.name);
})
and it will give an array with all team names from your ajax response
put JSON in js obj variable
var obj = JSON.parse('{ <key:value>,<key:value>...}');
Make sure the text is written in JSON format, or else you will get a syntax error.
Use the JavaScript object in your page:
Example
<p id="demo"></p>
<script>
document.getElementById("name").innerHTML = obj.name + ", " + obj.country;
</script>
I am trying to get data from my form and then send it to a servlet. But then I notice that the json object that I am getting after serializing my form is not a valid json object. What could I be doing wrong? This is what I tried so far.
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var data = $("#register").serialize().split("&");
var obj={};
for(var key in data)
{
console.log(data[key]);
obj[data[key].split("=")[0]] = data[key].split("=")[1];
}
console.log(obj);
// store json string
$.ajax({
type: "POST",
url: "HomeServlet",
dataType: "text",
contentType: "application/json",
data:{"res":obj},
success: function(data){
console.log(data);
},
error:function(){
console.log("error");
},
});
});
</script>
The json object that i am getting from the form is -
{
apiname: "jdjdj",
apiendpoint: "sdjsdj",
apiversion: "djdjd",
source: "internet"
}
This is what I want -
{
"apiname": "jdjdj",
"apiendpoint": "sdjsdj",
"apiversion": "djdjd",
"source": "internet"
}
There is nothing wrong with the json you Got .
Just stringify it to get the desired object
var myJSON1 = JSON.stringify(data);
this will work
YOu may try it
JSON.stringify(json_data);
As others have noted, your passing a raw javascript object.
What you must do is convert this object prior to sending it over the wire.
JSON.stringify(json_data);
Instead of this foreach loop only use serializeArray() then json_parse() these two functions will work for you.
var data = $("#register").serializeArray();
var obj= JSON_parse(JSON_stringify(data));
please use JSON.stringify(obj, undefined, 2);
First time question, hoping for some advice:
Code on webpage:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response);
}
});
});
});
};
</script>
</form>
This returns a string that I would like to work with that looks like this:
Answer:
[{"id":"1","answer":"Pull logging","question_id":"5","feature_id":"1","answer_id":"9"}]
Ideally what I would like to do is only select the 'value' to the maxmail_answer 'key' (hopefully those are the right terms?) to the webpage instead. Right now there is only one value but there will be more in the future so something that could parse this string for a specific key and only output those values.
Visually I would see:
Answer: Pull logging ( and then another Answer: for each value I pull out )
First time ever using this site and these languages so total noob and would appreciate some guidance.
Thanks!
You do not to stringify the JSON response, you can get the value of the key you want using the object notation . as follows:
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
//var response = JSON.stringify(data); // no need for this line
$('#response').delay(3600).fadeIn(600);
// catch the answer here
// your result returns within an array so you need to catch the first index
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
});
});
});
};
Besides, ids are unique, you can only access a single element via id selector #, you do not need a .each
What you are receiving from your server is an array of objects in the JSON format. The sample that you have put has the length of "1" and therefore, if want to reach the "id" of the first array, it would be like this:
// var response = JSON.stringify(data); (// don't stringify it!
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+data[0].id);
You need here a loop to go through your array of results and display each result
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$.each(response,function(index,value){//the each loop
$('#response').append("<p>Answer: </p>"+value.answer);//get the answer using . notation
});
}
Json.stringify() returns your javascript object as json data, but i think in your case your response is a json data which you need to manipulate. Json.parse() does this for you and you can access your answer as a property of the javascript object.
success: function(data) {
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
if your json data has multiple result and you need to work through all of them use a loop.
$.each(response,function(index, object){
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+object.answer);
});
First of all. Thank you to everyone who commented on this to help me get started in the right direction. I was able to get what I needed working!! Here is the solution:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#controlpanel:input').each(function () {
var iv = $(this).val();
$('#response').html("");
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var newdata = JSON.stringify(data);
var response = JSON.parse(newdata);
$('#response').delay(3600).fadeIn(600);
$.each(response, function(array, object) {
$('#response').append("<p>Answer: </p>"+object.answer);
});
}
});
});
});
};
</script>
</form>
I needed to parse the data correctly. So I used JSON.stringify to get the data into a string that JSON.parse could use to manipulate the data. But function(index,object) wouldn't work because my output was not an index, but an array. So when changing to function(array,object) this allowed me to get my data just the way that I needed.
Again thanks to everyone for their help!
I have an object returned from a $.ajax request. This is an example:
[{"id":"14","branchName":"Catcliffe","address1":"26 Main Street","address2":"","address3":null,"city":"Catcliffe","county":"South Yorkshire","postcode":"S60 5SR","country":"UK"}]
I am having a brain freeze on how to access items in the array, for example how would I set a variable to the 'branchName'...
This is the code I used to get the data:
$("#branchID").change(function(){
var id = $(this).val();
$.ajax({
url: "/admin/getBranchInfo.php?branchID=" + id,
success: function(branch){
$("div#results").html(branch);
}
});
});
You need to get the first element in the returned array using it's index, [0], then you can grab the property you want from that, .branchName.
$("div#results").html(branch[0].branchName);
Example fiddle
I just assumed that you are holding that object in a variable called xObj.
Try,
console.log(xObj[0].branchName)
But you should parse it before accessing the values since you have not mentioned the type,
var xObj = JSON.parse(branch);
console.log(xObj[0].branchName)
You have to use indexer, to access the element of array. As array contains object you go to use dot . operator to access object properties like branchName
Live Demo
$("div#results").html(branch[0].branchName);
Your code would be
$("#branchID").change(function () {
var id = $(this).val();
$.ajax({
url: "/admin/getBranchInfo.php?branchID=" + id,
success: function (branch) {
$("div#results").html(branch[0].branchName);
}
});
});
You would get the branchName property from the first (and only) item in the array:
$("div#results").html(branch[0].branchName);
use object and using its property we can access it branch[0].branchname
$("#branchID").change(function()
{
var id = $(this).val();
$.ajax(
{
url: "/admin/getBranchInfo.php?branchID=" + id,
success: function(branch)
{
var branchname= branch[0].branchname;
$("div#results").html(branch);
}
});
});
To handle multiple objects you can loop the result using a for loop like the one given below:
for(var i in branch)
{
var id = branch[i].id;
var branchName = branch[i].branchName;
//....
//Iterate other objects as well
}
Using Javascript. I'm trying to loop through an array encoded with JSON. Here is a sample of the array:
{"test1":"some info","test2":"more info","test3":"more stuff"}
Inside each loop I am checking to see if a DIV id exists with the name of the keys.
<div id="test1"></div>
<div id="test2"></div>
<div id="test3"></div>
I'm using a for() loop, but I can't get it to work. If I remove the for() loop it works just fine if I search for only 1 DIV id.
for(var key in responseText)
Here is the script. Does anyone know how I can loop through the array from responseText using the array keys as the names of the DIV id's?
<script>
function loadInfo() {
var req = new Request({
method: 'get',
url: 'getinfo.php,
noCache: true,
onRequest: function() {
for (var key in responseText) {
if (document.getElementById(key)) {
$(key).set('html', 'Loading');
}
}
},
onComplete: function(responseText, responseHtml) {
if (JSON.decode(responseText) != null) {
var data = JSON.decode(responseText);
for (var key in responseText) {
if (document.getElementById(key)) {
$(key).set('html', data[key]);
}
}
}
},
onFailure: function() {
for (var key in responseText) {
if (document.getElementById(key)) {
$(key).set('html', '-');
}
}
}
}).send();
}
window.addEvent('domready', function() {
loadInfo();
});
</script>
You have to decode the JSON before you iterate over the keys. So, where you say:
for(var key in responseText) {
replace that with:
for(var key in data) {
assuming
var data = JSON.decode(responseText);
Also, some of your callback functions don't specify responseText as a parameter. If you want to access this for each callback, you have to explicitly include responseText as a parameter. Example:
onRequest: function(){
should be:
onRequest: function(responseText){
I think the problem is that you're using the wrong variable name.
var data = JSON.decode(responseText);
for(var key in responseText) {
Should read
var data = JSON.decode(responseText);
for(var key in data) {
Note that instead of responseText after in, it reads data.
Are you sure you don't want JSON.parse? This would parse the JSON response into a javascript object that you can use the for/in against.
var data = JSON.parse(responseText);
Also, you're missing a closing quotation mark after the url:
url:'getinfo.php', // Closed the quote