Hello there I will try and keep this simple and short
I have a getJSON function that runs every 5 seconds. Now when I display the data using document.write function it dosent seem to want to update. The page is stuck in a loading loop. How can I get the data to display on my page? My JSON is fine but I will show you anyways.
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
setInterval(function(){ $.getJSON('names.json', function(data) {
for(i in data) {
document.write(data[i] + "<br/>");
}
});
},5000);
</script>
This is the JSON object
{
"one": "",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Don't actually use document.write. Once the page is loaded, that will erase the page. Use (jQuery's) DOM methods to manipulate the DOM.
$.getJSON('names.json', function(data){
for(var i in data){
$('#myDiv').append(data[i]);
}
});
I would recommend you use jQuery,
I used this to create a form from my json item, I hope this helps...
function jsonFormCreator(frmJSON)
{
var createdHTML = ""; var elementType, id;
console.log(JSON.stringify(frmJSON));
for(item in frmJSON)
{
formElement = frmJSON[item]; elementType = formElement.elementType; id = formElement.id;
if(elementType == "input")
{
createdHTML += "<input id='" + id +"'";
if(formElement.type == "checkbox")
{createdHTML += " type='" + formElement.type + "' checked='" + formElement.checked + "'";}
else{createdHTML += "type='" + formElement.type + "' value='" + formElement.value + "' onclick='" + formElement.onclick + "'";}
createdHTML += "/><br>"
}
else if(elementType == "textarea")
{createdHTML += "<textarea id='" + formElement.id + "' rows='" + formElement.rows + "' cols='" + formElement.cols + "' value='" + formElement.value + "'></textarea><br>";}
else if(elementType == "select")
{
var options = formElement.values;
createdHTML += "<select id='" + formElement.id+ "'>";
for(i = 0 ; i < options.length ; i++)
{createdHTML += "<option value='" + options[i][0] + "'>" + options[i][1] + "</option>";} //Adding each option
createdHTML+= "</select><br>";
}
}
console.log("Complete");console.log(createdHTML);
document.getElementById('mainContainer').innerHTML = createdHTML;//Adding to the DOM
}
And my JSON would look like this
{
"0": {
"elementType": "input",
"id": "frm1",
"type": "text",
"value": "form Liam",
"label": "Test Text Input"
},
"itemBTN": {
"elementType": "input",
"id": "frmAlert",
"type": "button",
"onclick" : "loader(homePage);",
"value": "Home Page",
"label": ""
},
"item2": {
"elementType": "textarea",
"id": "frm2",
"rows": 5,
"cols": 30,
"value": "helddddddddlo",
"label": "Test Textarea"
},
"item3": {
"elementType": "select",
"id": "frm3",
"values": [
[
"value1",
"Pick Me"
],
[
"value2",
"UserDis2"
],
[
"value3",
"UserDis3"
],
[
"value4",
"UserDis4"
],
[
"value5",
"UserDis5"
],
[
"value6",
"UserDis6"
]
],
"label": "Test Select"
},
"item4": {
"elementType": "input",
"id": "frm4",
"label": "Checkbox",
"type": "checkbox",
"checked": true
}
}
This code adds the form in to my div tag with the id mainContainer
I know its alot of code, but i hope it helps !
You want to render dom which will contain the data, then when you get the data update the dom.
As an exceedingly simple example, on your page have a container
<div id="one"></div>
and then in your ajax success handler
$("#one").text(json.one);
This uses jquery to grab the dom element with id "one", and update its text.
Related
I want to make a dropdown in my table which is populated with the dynamic data coming from ajax response and append to the table.
My postman collection looks like this.
{
"createdDate": "2022-04-06T11:42:37.360Z",
"enabled": true,
"_id": "62502b868daa3b1cdbdc98e8",
"CNIC": "40740c7d9f3a11d93e76af7f2f60887a",
"employeeID": "LE44337",
"fName": "HUSNAIN",
"company": "6249fdf91399dc7a14173dcd",
"fatherName": "husnain",
"motherName": "momutaz",
"spouse": "no spouse",
"children": [{
"_id": "62502b868daa3b1cdbdc98e9",
"name": "hunsian",
"age": 23232
}, {
"_id": "62502b868daa3b1cdbdc98ea",
"name": "hunsian",
"age": 12121
}, {
"_id": "62502b868daa3b1cdbdc98eb",
"name": "momin",
"age": 2323
}
}
And below is my ajax response code in which I am appending the data into table.
success : function(response){
var trHTML = '';
$.each(response.doc, function (i, item) {
trHTML += '<tr><td>' + item.fName + '</td><td>' + item.CNIC + '</td><td>' + item.spouse + '</td><td>'+ item.fatherName + '</td><td>' + item.motherName +'</td><td>'+ item.employeeID +'</td><td>' + item.children.map(({name, age}) => `Name: ${name} Age: ${age}`).join(' || ') +'</td></tr>';
});
$('#records_table').append(trHTML);
}
The itme.children name , age I want to make a dropdown of it into table so it looks good.
If you mean a dropdown like a select menĂº, this should do the job
trHTML += `... <td>
<select>
<option selected disabled>Click me</option>` +
item.children.map(({name + age}) => `<option>Name: ${name}, Age: ${age}</option>`).join('') +
`</select></td>`;
Good Morning, using ajax call I am trying to return the values of a nested json array, I was successful to pull the data except for the nested array "booking_status". When I try loop through the 'booking_status', I git the value [object Object],[object Object],[object Object] . If I try to specify a value for example item.booking_status.status I get this undefined.
This is my nested array
[
{
"id": 1,
"item_name": "Misrry",
"author": "Stephen King",
"booking_status": [
{
"check_in": "2021-09-22T08:27:00+04:00",
"check_out": "2021-09-23T08:27:00+04:00",
"status": "Currently Booked"
},
{
"check_in": "2021-09-25T08:37:00+04:00",
"check_out": "2021-09-26T08:37:00+04:00",
"status": "Currently Free"
},
{
"check_in": "2021-09-27T08:37:00+04:00",
"check_out": "2021-09-28T08:37:00+04:00",
"status": "Currently Free"
}
]
{
"id": 2,
"item_name": "Rose Red",
"author": "Stephen King",
"booking_status": [
{
"check_in": "2021-09-22T08:27:00+04:00",
"check_out": "2021-09-23T08:27:00+04:00",
"status": "Currently Booked"
},
{
"check_in": "2021-09-25T08:37:00+04:00",
"check_out": "2021-09-26T08:37:00+04:00",
"status": "Currently Free"
}
]
}
]
and this is my script:
<script>
$(document).ready(function () {
$.ajax({
url: 'http://localhost:8000/',
dataType: 'JSON',
success: function (data) {
for (var i = 0; i < data.length; i++) {
$(document).ready(function () {
var content = ''
data.forEach(item => {
content += "<tr><td>"
+ item.item_name + "</td><td>"
+ item.author + "</td><td>" + item.booking_status
+ "</td></td></tr>"
})
$('#table_body').html(content);
})
}
}
});
});
</script>
You have a couple of mistakes in your code.
You're iterating over data twice. (for loop and data.forEach);
Remove the for loop, it's redundant.
booking_status is an array, so you're going to have to stringify it, or iterate over it somehow.
You don't need to nest $(document).ready. The inner calls can be removed.
$(document).ready(function() {
$.ajax({
url: 'http://localhost:8000/',
dataType: 'JSON',
success: function(data) {
var content = '';
data.forEach(item => {
content += "<tr><td>" +
item.item_name + "</td><td>" +
item.author + "</td><td>" + item.booking_status.map(s => s.status).join('<br/>') +
"</td></td></tr>";
});
$('#table_body').html(content);
});
});
});
I am making a CMS with an edit button. When you click the edit button it should everything from the JSON file back to the CMS side so you can actually edit.
However when I try to fetch my word I can only fetch one while I have 2 word in my JSON.
This is how my JSON looks like:
{
"main_object": {
"id": "new",
"getExerciseTitle": "TestToConfirm",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "TestToConfirm",
"language": "nl_NL",
"exercises": [{
"word": "huishoudelijk",
"syllables": [
"huis",
"houdelijk",
"",
""
]
},
{
"word": "Kleedt u zich maar uit.",
"syllables": [
"Kleed",
"u",
"zich",
"uit"
]
}
]
},
"dataType": "json"
}
}
This is how I am trying to loop through my word so I can fetch it all. I do have to note that I am going to fetch the syllables aswell and i'm not entirely sure if it's bad to create 2 different loops to fetch the data. Or is it recommended to do it both in 1 loop?
$(document).ready(function() {
$.getJSON('json_files/jsonData_' + ID + '.json', function(json) {
// console.log(json);
var exercisetitle = json.main_object.getExerciseTitle;
// console.log(exercisetitle);
$("#getExerciseTitle").val(exercisetitle);
var exercise = json.main_object.main_object.exercises;
$.map(exercise, function(exercise, i) {
var myindex = 1;
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + myindex).val(exercise.word)
myindex++;
});
});
});
The code of exerciseGetWordInput_:
The #addOpdracht is just a button that creates new exercise blocks. I don't think that has much to do with how to loop or the possible cause of my app failing.
function getWordInput(id, cValue) {
cValue = cValue || '';
var wInput = $('<input/>', {
'class': 'exerciseGetWordInput_' + id + ' form-group form-control ExerciseGetWordInput',
'type': 'text',
'name': 'question_takeAudio_exerciseWord[' + exerciseAudioInput + ']',
'placeholder': 'Exercise',
'id': 'exerciseGetWordInput',
'required': true
});
return wInput;
}
Move var myindex = 1 outside the loop
var myindex = 1;
$.map(exercise, function(exercise, i) {
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + myindex).val(exercise.word)
myindex++;
});
OR you can also avoid use of extra variable like following and use each instead
$.each(exercise, function(exercise, i) {
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + i).val(exercise.word) // starts with 0
});
Use each
use IDs
execute the function you would normally execute on click.
var data = {
"main_object": {
"id": "new",
"getExerciseTitle": "TestToConfirm",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "TestToConfirm",
"language": "nl_NL",
"exercises": [{
"word": "huishoudelijk",
"syllables": [
"huis",
"houdelijk",
"",
""
]
},
{
"word": "Kleedt u zich maar uit.",
"syllables": [
"Kleed",
"u",
"zich",
"uit"
]
}
]
}
}
}
$.each(data.main_object.main_object.exercises, function(_,exercise) {
addOpdracht(exercise)
});
function addOpdracht(exercise) {
var $container = $("#exerciseContainer"),
count = $container.length,
$div = $("<div/>").addClass("exerciseDiv"),
$input = $("<input/>", {
type: "text",
id: "exerciseGetWordInput_" + count,
value: exercise.word
})
$div.append($input);
$container.append($div);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="exerciseContainer"></div>
I'm having an
Uncaught TypeError cannot read property 'image' of undefined
error when calling some Json data. My js is the following:
$.getJSON('/js/data.json', function (json) {
Object.keys(json).forEach(function (country) {
$(".marker." + country.toLowerCase()).on("click", function () {
$("#show").html(
"Image: <img src=" + json[country][0].image + ">" +
"| Description: <h1>" + json[country][0].description) + "</h1>";
});
});
});
and my data.json the following:
{
"france": {
"image": "img/ausralia.jpg",
"description": "number django 1"
},
"australia": {
"image": "img/ausralia.jpg",
"description": "number django 2"
},
"uk": {
"image": "img/ausralia.jpg",
"description": "number django 3"
}
}
ON click, no data are being display and I'm having that error being display in my console.
The weird thing is that If i call the data like this in my js, the error doesn't appear and everything works correctly. But I need to be able to call the data from an external file.
var json = {
"France": [{
"image": "img/ausralia.jpg",
"description": "number django 1"
}],
"Australia": [{
"image": "img/ausralia.jpg",
"description": "number django 2"
}],
"uk": [{
"image": "img/ausralia.jpg",
"description": "number django 2ee"
}]
}
Object.keys(json).forEach(function (country) {
$(".marker." + country.toLowerCase()).on("click", function () {
$("#show").html(
"Image: <img src=" + json[country][0].image + ">" +
"| Description: <h1>" + json[country][0].description) + "</h1>";
});
});
Any help will be amazing, I know there is post about this error, but I cant find any solution to make it work !
Hope it make sense , thanks for your time !
Try this,
Object.keys(json).forEach(function (country) {
if(typeof json[country][0].image !== "undefined" && typeof json[country][0].description !== "undefined" ) {
$(".marker." + country.toLowerCase()).on("click", function () {
$("#show").html( "Image: <img src=" + json[country][0].image + ">" + "| Description: <h1>" + json[country][0].description) + "</h1>";
});
}
});
Below is my json data which is stored in Checklistdata.json, i want to display the key and the labels as check boxes using jquery,my jquery will only display the label with check box.Any help, i will be grateful.
[
{
"Beginning": [
{
"label": "Enter basic information"
},
{
"label": "Enter name of Vendor "
}
]
}
]
Below is my jquery!!
$.getJSON('Checklistdata.json', function (data) {
$.each(data, function (i, entity) {
$('#Checklist').append($('<input />', { 'type': 'checkbox','label': entity.label, 'value': entity.is_correct })).append(entity.answer + '<br />');
});
$("#checkboxes").on('change', '[type=checkbox]', function () {
console.log($(this).val());
});
});
The way you are iterating around the data is the problem. After you change data to:
var data= [
{
"Beginning": [
{ "label": "Enter basic information","id":1 },
{ "label": "Enter name of Vendor ","id":2 }
]
}
];
Change your line of code:
$.each(data, function(key, val) {
to
$.each(data[0].Beginning, function(key, val) {
That is because data is an array of object. After you make this change you will see it moving a step closer to what you want to achieve! That should give you idea to modify your code further to do what you want it to do.
Here is a FIDDLE that will probably get you started.
The arrays would be the equivalent of your json data.
You'd need to style it and change the format to suit your needs.
It's not very elegant, but seems to work.
JS
var myarray1 = ['y', 'n', 'y', 'y', 'y'];
var myarray2 = ['A', 'B', 'C', 'D', 'E'];
$('#mybutton').click(function(){
$.each(myarray2, function(key, value){
$('#holderdiv').append(value + "<input type='checkbox' />" + '<br />');
});
$('input[type=checkbox]').each(function(index){
if(myarray1[index] == 'y')
{
$(this).prop('checked', true);
}
});
});
EDIT:
Ok, here's the new FIDDLE that works with your array.
It's a good idea to use jsonlint.com to check the validity of your json array.
New JS
var mydata = {
"Beginning": [
{ "label": "Enter basic information", "id": 1 },
{ "label": "Enter name of Vendor ", "id": 2 }
]
};
var firstvar = mydata.Beginning[0].id;
$('#mybutton').click(function(){
$.each(mydata.Beginning, function(key, value){
$('#holderdiv').append(mydata.Beginning[key].label + "<input type='checkbox' />" + '<br />');
});
$('input[type=checkbox]').each(function(index){
if( mydata.Beginning[index].id == 1)
{
$(this).prop('checked', true);
}
});
});
I have got my answer. have to made some changes to JSON data storing, but it satisfies my requirement. So below is the answer with fiddle. http://jsfiddle.net/Suma_MD/fWLgD/2/
var data = getData(),
$checklist = $('#checklist');
data.forEach(function (v) {
var Description = v.Description;
$checklist.append('<br>' + Description);
var Array1=v.Checklist;
var Array2;
Array1.forEach(function(d){
Array2 = d.label;
$checklist.append('<br>' +"<input type='checkbox' />" + Array2 );
});
});
function getData() {
return [
{
"Description": "Beginning1",
"Checklist": [
{
"label": "Enter basic information",
},
{
"label": "Enter basic information",
},
{
"label": "Enter basic information",
},
{
"label": "Enter basic information",
}
]
},
{
"Description": "Beginning2",
"Checklist": [
{
"label": "Enter basic ",
},
{
"label": "Enter basic ",
},
{
"label": "Enter basic ",
},
{
"label": "Enter basic ",
}
]
}
];
}
HTML : <div id="checklist"></div>