This is the code (refer to CODE) I use when I try to create new CouchDB document. The document contains one or more existing CouchDB documents (history tracking). The resulting json (refer to JSON) for the newly created doc is something like:
JSON:
{
"_id": "b3360050039389801524044daf1c963c",
"_rev": "1-2a5da40ce9a191b4decc27411ec9a181",
"hodoc_type": "INCOMMING DELIVERY NOTE",
"user_from": "ANS USER",
"status": "INSTALLED ON SITE",
"category": "ASET",
"location": "MTX SPARE",
"doctype": "hodoc",
"items": [
{
"serial_number": "310310007590",
"status": "STORED IN WAREHOUSE",
"doctype": "data",
"supplier": "INTRACOM",
"po": "0",
"category": "SPARE PART",
"user_out": "IGOR JURUKOV",
"mac": "NULL",
"eqtype": "IDU",
"location": "MTX SPARE",
"location_comment": "NULL",
"date_in": "2011-05-06",
"date_out": "2011-05-06",
"prf": "0",
"part_number": "Z00-404/63.01",
"user_in": "KOTE JANAKIEVSKI",
"bar_code": "0",
"manufacturer": "INTRACOM",
"rma": "NULL",
"product_name": "PSU for IDR-SM"
},
{
"serial_number": "310407016955",
"status": "STORED IN WAREHOUSE",
"doctype": "data",
"supplier": "INTRACOM",
"po": "0",
"category": "SPARE PART",
"user_out": "IGOR JURUKOV",
"mac": "NULL",
"eqtype": "IDU",
"location": "MTX SPARE",
"location_comment": "NULL",
"date_in": "2011-05-06",
"date_out": "2011-05-06",
"prf": "0",
"part_number": "Z00-404/63.02",
"user_in": "KOTE JANAKIEVSKI",
"bar_code": "0",
"manufacturer": "INTRACOM",
"rma": "NULL",
"product_name": "PSU for IDR-SM"
}
]
}
CODE:
var docids = new Array();
var items = new Array();
$('div#divitemsout').find('img.item-out-remove').each(function () {
var id = $(this).attr('attrid');
if (docids.indexOf(id) == -1) {
docids.push(docid);
}
var item = new Object;
$.getJSON('/whdb/' + id, function(data) {
$.each(data, function(key, val) {
if (key !== "_id" && key !== "_rev") {
item[key] = val;
}
});
// Check No.1
//alert(item.manufacturer);
});
// Check No.2
//alert(item.manufacturer);
items.push(item);
});
The problem and the question are: When the line bellow Check No.2 is comented, the “items” part of the resulting json document is []. When the alert(item.manufacturer) bellow Check No.2 is uncommented, I get alerts with contents “undefined”, but the “items” part of the resulting json document is properly set, just like show in the example. Any suggestion?
The problem is just timing. The function you pass to
getJSONisn’t called until the web server returns a response to your request. Soitemwill not be defined immediately after the call togetJSON. Adding thealertcalls just slows things down so that the asynchronous call has time to complete.Try moving the
items.push(item)line inside thegetJSONcallback.Edit
To make things clear, try this (in Chrome or Firefox with Firebug open, so that you have a proper
console.logfunction):