I want to add a new row to my JSON when the user clicks a link. Here's my javascript: It's not erroring, but I am not getting updated JSON in my alert.
$(document).ready( function(){
people = {
"COLUMNS":["NAME","AGE"],
"DATA":[
["Jon","16"],
["Jerry","23"]
]
}
members = people.DATA;
var nc = "<table border=1 width=500><tr><td>name</td><td>age</td><td></td></tr>";
for(var i=0;i<members.length;i++)
{
nc+= '<tr><td>' + members[i][0] + '</td>';
nc+= '<td>' + members[i][1] + '</td>';
nc+= '<td>add a new person</td></tr>';
}
nc += "</table>";
$("#result").html(nc);
$(".addlink").click( function(){
// add another row to our JSON
people.DATA['NAME'] = "new";
people.DATA['AGE'] = "99";
alert(people.DATA);
return false;
});
});
That's not JSON, it's a Javascript object.
To add another item in the array, you create an array and add to it, as it is an array of arrays:
people.DATA.push(["new", "99"]);
Related
I'm trying to get some value over my server using jquery's $.get method and store the result in an object.
What I'm doing is running my function inside a loop:
function renderTabelScheduledEmploye(employees) {
$('#containerDataStaff').empty();
let record = '';
let count = 1;
if (employees.length > 0) {
$.each(employees, function(key, value) {
getFromServerScheduleCount(employees[key].schedule_employee_id);
console.log(scheduleCountData);
record += '<tr>';
record += '<td>' + count + '</td>';
record += '<td>( ' + employees[key].emp_kode + ') - ' + employees[key].emp_full_name + '</td>';
record += '<td>' + scheduleCountData[0].work + '</td>';
record += '<td>' + scheduleCountData[0].offDay + '</td>';
record += '<td>' + scheduleCountData[0].leave + '</td>';
record += '<td>' + scheduleCountData[0].shiftCount + '</td>';
record += '<td>Set Shift</td>';
record += '</tr>';
count++;
});
}
$('#containerDataStaff').append(record);
}
Then I create a function to retrieve JSON data from my server using the $.get function, then store the data result to an object that has been declared:
var scheduleCountData = new Object();
function getFromServerScheduleCount(schedule_employee_id) {
let url = `{{ url('/departement/schedule/manage/schedule/count') }}`;
url = url + '/' + schedule_employee_id + '/get';
let data = {};
$.get(url, function(data) {
let obj = JSON.parse(data);
data.work = obj.work;
data.dayOff = obj.dayOff;
data.leave = obj.leave;
data.shifts = obj.shifts;
scheduleCountData.new = data;
})
}
I can see in the console that the object has filled with the data
[object success to fill][1]
But when i try to access in code like this
scheduleCountData[0]
and log the result to to the console, it shows undefined.
This little bit frustrating for me. I hope someone can help me. Thanks for community.
EDIT :
Sorry i miss
i try to call that object with code like this
scheduleCountData.new
but still undefined on console
Seems youre not waiting for the load to finish before trying to use the data:
// This has a get call, which is async (takes time to load)
getFromServerScheduleCount(employees[key].schedule_employee_id);
// The script will continue, without waiting for the load to finish, so can be empty
console.log(scheduleCountData);
I would suggest adding a callback, like this:
getFromServerScheduleCount(employees[key].schedule_employee_id, function(scheduleCountData) {
console.log(scheduleCountData);
});
function getFromServerScheduleCount(schedule_employee_id, callback) {
$.get(url, function(data) {
// ...
callback(data);
});
}
I am learning AJAX and not able to find how to refer a particular row in a table which is fetched from a .json file. Actually I want the respective data on click of the respective edit button in the row. It should be displayed in the <p> tag just below the table.
Heres my script
<script>
function myFunction() //on click function to fetch data from json
{
var counter;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if(xhttp.readyState == 4 && xhttp.status == 200)
{
var data = JSON.parse(xhttp.responseText);
mydata(data);
}
};
xhttp.open("GET", "employee.json");
xhttp.send();
counter ++ ;
}
function mydata(data){ //data to be shown and fetch
var output = "<table>";
var output = "<th>Employee Code</th>" +
"<th>Name</th>" +
"<th>Joining Date</th>" +
"<th>Salary</th>"+
"<th>Edit</th>";
//var i in each items[i]
for(var i in data)
{
output += '<tr>' +
'<td>' + data[i].empcode + '</td>' +
'<td>' + data[i].name + '</td>' +
'<td>' + data[i].joining + '</td>'+
'<td>' + data[i].salary + '</td>' +
'<td>' + '<button onclick="edit()">Edit</button>' +
'</tr>';
}
output +="</th>" + "</th>" + "</th>" + "</th>" + "</th>";
output += "</table>";
document.getElementById('demo').innerHTML = output;
function edit(){
document.getElementById("para").innerHTML = data[1].empcode;
}
}
function edit(){ //edit function to display related data from json file. Right now i can only display data which i mentioned in editTextData().
var edit = new XMLHttpRequest();
edit.onreadystatechange = function(){
if(edit.readyState == 4 && edit.status == 200){
var editData = JSON.parse(edit.responseText);
editTextData(editData);
}
};
edit.open("GET", "employee.json", true);
edit.send();
}
function editTextData(textData){
document.getElementById("para").innerHTML = textData[2].empcode;
}
</script>
This is the JSON data :
[{
"empcode" : 1,
"name": "sid",
"joining" : "13 march",
"salary" : 60000
},
{
"empcode" : 2,
"name": "andrew",
"joining" : "15 march",
"salary" : 65000
},
{
"empcode" : 3,
"name": "blake",
"joining" : "18 march",
"salary" : 70000
}
]
This is the html code :
<h1>AJAX Employee</h1>
<div>
<table id="demo"> </table>
</div>
<button onclick="myFunction()" ">Fetch Info</button>
<p id="para"> </p>
This is the result i am getting
Result table after clicking fetch button. When i click any edit button it shows the 3rd employee number
Your edit handler can figure out which button was clicked, which row it belongs to, and which empcode that was. The key is the this value that gets passed into the edit handler.
You're assigning the handler inline, which isn't ideal, so you will need to make a change to that part:
'<td>' + '<button onclick="edit(this)">Edit</button>'
Now the button is being passed into edit as the first parameter, so:
function edit(btn) { //edit function to display related data from json file.
// get the TR that this button is in
var tr = btn.parentNode.parentNode;
// get the collection of tds
var tds = tr.querySelectorAll("td");
// get the contents of the first TD, that should be the empcode
var empcode = tds[0].innerText;
// do whatever you need to with empcode, or the other values in this record
console.log("empcode = " + empcode + ", name = " + tds[1].innerText);
}
So I have 2 pages.
On one I have a table that is getting data from a JSON page and I inserted a button on each row that whenever is clicked it should get that item on an array.
And then, that array should give the results on the second page.
I can get the info from the JSON without problems, but cannot store the information on an array. Can someone help me? I'm quite new on JavaScript.
Page 1:
<script>
<!-- Retrieve data from file -->
var products=[];
var cartArray=[];
var product_array=[];
$.getJSON('products.json',function(data){
$.each(data.products, function(i, f){
var img = f.image_url;
var title = f.title;
var price = f.price;
var old_price = f.old_price;
product_array.push([img, title, price]);
var tblCell = "<tr><td class='prod_container'><tr><td class='prod_img_container'><img class='prod_img' src=" + img + "></td></tr>" + "<tr class='title_container'><td class='title'>" + title + "</td></tr>" + "<tr class='price_container'><td class='price'>" + price + "</td>" + "<td class='price_org'>" + old_price + "</td>" + "<td class='add_cart'><img class='add_cart_img' src='img/buynow-green-6.png' onClick='addToCart()'>" + "</td></tr>"
$(tblCell).appendTo("#list_products tbody");
});
});
<!-- Add To Cart -->
function addToCart(){
cartArray.push([product_array.title, product_array.img, product_array.price]);
window.alert(cartArray);
}
<!-- Store and go to checkout -->
function goToCheckout(){
$('#store').on('click', function(){
localStorage.cartArray = cartArray;
});
window.location.href="cart.html";
}
Not sure of your final data structure needs, but if you want a multi-dimensional array:
var cartArray = []
function addToCart(product_array){
cartArray.push([product_array.title, product_array.img, product_array.price];
window.alert(cartArray);
}
I want to print the data of an object in the form of a table using javascript. The code I have written does not display anything. Please tell me what am I doing wrong here.
Here is the code i wrote-
function Movie(id,movieName)
{
this.id = id;
this.movieName = movieName;
}
function MoviesWatched()
{
this.movies = new Array();
}
MoviesWatched.prototype.addMovie = function(id,name)
{
this.movies[id]=new Movie(id,name);
}
MoviesWatched.prototype.getTable = function()
{
var movie;
var table="<table border=1>";
for(movie in this.movies)
{
table += "<tr><td>";
table += movies[movie].id;
table += "</td><td>";
table += movies[movie].name;
table += "</td></tr>";
}
table += "</table>";
return table;
}
var myList=new MoviesWatched();
myList.addMovie(1,"Inception");
myList.addMovie(2,"Red");
document.write(myList.getTable());
In your getTable function, you need to change movies to this.movies and change name to movieName
var movie;
var table="<table border=1>";
for(movie in this.movies)
{
table += "<tr><td>";
table += this.movies[movie].id;
table += "</td><td>";
table += this.movies[movie].movieName;
table += "</td></tr>";
}
http://jsfiddle.net/fenderistic/9Gzdv/1/
I'm trying to make a <table> through a javascript function.
I'm getting a JSON element that looks like that :
header
["Nom", "Région", "Activité", 10 more...]
0 "Nom"
1 "Région"
2 "Activité"
// other fields
body
Object { entity0=[13], entity1=[13], entity2=[13], more...}
entity0
["Org2", "Org2", "Org2", 10 more...]
0 "Org2"
1 "Org2"
2 "Org2"
//Other fields
entity1
["gfhu", "rtyud", "dgud", 10 more...]
//Other entities
And I'm trying to decode it like that (I parse the JSON and give it to that function) :
function createTableEntity(tab, id){
table = '<table cellpadding="0" cellspacing="0" border="0" class="display" id="'+id+'">';
table = table + '<thead><tr>';
$(tab.header).children().each(function(){
table = table + '<td>' + this + '</td>';
});
table = table + '</tr></thead>';
table = table + '<tbody>';
$(tab.body).children().each(function(){
table = table + '<tr>';
$(this).children().each(function(){
table = table + '<td>' + $(this) + '</td>';
});
table = table + '</tr>';
});
table = table + '</tbody>';
table = table + '</table>';
//alert(table);
return table;
}
From the results I have, there are no children ($(tab.header).children().each(function(){});).
Where does it come from? How do I loop through the elements parsed from JSON?
You don't need jquery to loop through the result of a JSON parsing as it's a Javascript object.
If you have an array in tab.header, you simply can loop on it with
$.each(tab.header, function() {
Or more classicaly, without jquery, using
for (var i=0; i<tab.header.length; i++) {