I have a data
{
"data": {
"count": 8,
"rows": [
{
"session_name": "1_M1",
"date": "09-09-2021",
"p_id": "WEB506",
"sub_id": "Physiotherapy"
},
{
"session_name": "WEB506_09092021_M1",
"date": "09-09-2021",
"p_id": "WEB506",
"sub_id": "Physiotherapy"
},
{
"session_name": "WEB506_09092021_M1",
"date": "09-09-2021",
"p_id": "WEB506",
"sub_id": "Physiotherapy"
},
{
"session_name": "WEB506_09092021_M1",
"date": "09-09-2021",
"p_id": "WEB506",
"sub_id": "Physiotherapy"
},
{
"session_name": "WEB506_09092021_M1",
"date": "09-09-2021",
"p_id": "WEB506",
"sub_id": "Physiotherapy"
},
{
"session_name": "WEB506_09092021_M1",
"date": "09-09-2021",
"p_id": "WEB506",
"sub_id": "Physiotherapy"
},
{
"session_name": "WEB506_09092021_M1",
"date": "09-09-2021",
"p_id": "WEB506",
"sub_id": "Physiotherapy"
},
{
"session_name": "WEB506_09092021_M1",
"date": "09-09-2021",
"p_id": "WEB506",
"sub_id": "Physiotherapy"
}
]
}
}
which I get from a post API(nodejs, express) by handling an ajax. I'm saving this data in localstorage and accessing it by localstorage on the next page. Then I want to create dynamic cards with passing some values from this data. the problem is I'm getting this data inside my script on the next page but foreach is not working when I create cards. please help.
my ajax,
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
dataType: 'json',
url: "http://localhost:5000/SessionData",
success: function(data) {
console.log(data);
localStorage.setItem('myData', JSON.stringify(data));
window.location.href = 'nextpage'
},
error: function(){
alert("Error")
console.log('error occured')
}
})
and in my next page,
<script>
var data = localStorage.getItem('myData');
console.log(data);
var arr = new Array(data);
console.log(arr,"arr");
const container = document.getElementById('aa');
arr.data.forEach((result, idx) => {
// Create card element
const card = document.createElement('div');
card.classList = 'card-body';
// Construct card content
const content = `
<div class="card" style="width:700px;height: 150px">
<div class="card-body">
<li> Session Name :${result.sub_id}</li>
<li> Date :${result.date}</li>
<li> Patient ID : ${result.p_id}</li>
<button class="btn btn-link" style="width: 60px;height: 30px;background-color:#d1b147;color data-toggle="collapse" data-target="#collapse-${idx}" aria-expanded="true" aria-controls="collapse-${idx}">
View
</button>
</div>
</div>
</div>
</div>
`;
container.innerHTML = content;
})
</script>
CodePudding user response:
You need to convert the stored string
back to an object
,e.g. using JSON.parse()
:
const parsedData = JSON.parse(localStorage.getItem('myData'));
parsedData.data.rows.forEach((result, idx) => {
...
});