How do I load initial data via javascript? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I want to preload 9000 records via either a file or a whatever is best. The idea is I want to have there 9000 records somewhere and I want to load them into a sqlite DB via phonegap. I have all this working other then loading the data from somewhere. Here is what i have so far
I have a file records.csv file and here is my code
function populate_events_from_csv(db){
var event_data;
$.ajax({
type: "GET",
url: "records.csv",
dataType: "text/csv",
error: function (request, status, error) {
console.log('fail');
console.log(request.responseText);
},
success: function(data) {
console.log('success');
event_data = $.csv.toObjects(data); }
});
console.log(event_data);
db.transaction(function(tx) {
var q = 'INSERT INTO Events (id, name) VALUES (?, ?)';
_(event_data).each(function(row) {
tx.executeSql(q, [row.id, row.name]);
});
});
}
This approach would work but it fails because of the double and single quotes in the records csv
If anyone sees what i am doing wrong or another solution to initially inserting these 9000 records

function populate_events_from_csv(db) {
var event_data;
$.ajax({
type: "GET",
url: "records.csv",
dataType: "text/csv",
error: function (request, status, error) {
console.log('fail');
console.log(request.responseText);
},
success: function (data) {
console.log('success');
event_data = $.csv.toObjects(data);
db.transaction(function (tx) {
var q = 'INSERT INTO Events (id, name) VALUES (?, ?)';
_(event_data).each(function (row) {
tx.executeSql(q, [row.id, row.name]);
});
});
}
});
}

Why not convert the data into JSON, which will make it load faster into your javascript (minimal parsing), and simplify your code at the same time?
Once JSONized, you will be able to write
function populate_events(db, url) {
$.getJSON(url).done(function(data) {
db.transaction(function (tx) {
var q = 'INSERT INTO Events (id, name) VALUES (?, ?)';
$(data).each(function (index, row) {
tx.executeSql(q, [row.id, row.name]);
});
});
}).fail(function(request, status, error) {
console.log('fail');
console.log(request.responseText);
});
}
Converting CSV to JSON is left as an exercise, but there are many tools out there that can handle the task. I would use a Python script (csv + json libraries).

Related

Sending a string format date from html to javascript function. Javascript receives only a different year

I'm sending the expected return date (of a book to its owner) to a javascript function.
<td onclick="setApproved(#item.SchoolBook.Id,0,#item.Requestor.Id,#item.ExpectedReturnDate)"><button class="button-green" title="Approve">Approve</button></td>
When debugging I see that #item.ExpectedReturnDate which is a string is rendered properly, but the function receives something else entirely.
For example: #item.ExpectedReturnDate is 2019-06-27, the javascript function receives 1986.
The Javascript function:
function setApproved(bookId, type, requestorId,erd) {
$.ajax({
type: "get",
url: "/Books/SetApproved",
dataType: "json",
data: {
bookId: bookId,
type: type,
requestorId: requestorId,
erd: erd
},
success: function (response) {
if (response == "success")
//reload page
location.href = `/Books/BooksToLend`;
else
if (response == "fail")
//load error page
location.href = `/User/Error`;
},
failure: function (response) {
location.href = `/User/Error`;
},
error: function (response) {
location.href = `/User/Error`;
}
});
}
Here are snapshots of the debugging in the browser:
What is sent to function
What function receives
I would appreciate all help on this.
Thank you
The problem is that you are sending the date like a number, but then you have the - character.
For it to work you should send the date as a string, or creating a new Date object.
Something like this:
setApproved(5, 0, 323214, 2019-06-27)
setApproved(5, 0, 323214, '2019-06-27')
setApproved(5, 0, 323214, new Date('2019-06-27'))
function setApproved(bookId, type, requestorId,erd) {
console.log(bookId);
console.log(type);
console.log(requestorId);
console.log(erd);
}

How to use KnockoutJS to save data into SQL database?

Good day everybody. I have a question about how to use the right way to save data into SQL database through KnockoutJs. The record are display well in the table. It should be able to save the data via this pop-up Modal. But after I click the Create button in that modal, it only pop-up a failed Message. Can anybody please help me to solve this problem? Thank you very much.
Below is extract from main js file about Save function
var data = ko.toJSON(self.Profiles());
$.ajax({
type: 'POST',
url: '/ajaxCall/insertProAjax',
data: "{ Customer:" + ko.utils.stringifyJson(self.Name) + ",customerRemove:" + ko.utils.stringifyJson(self.CustomerRemove) + "}",
contentType: "application/json",
success: function (data) {
alert("Record has been saved Successfully");
MarkCustomerAsSaved();
$('#AddNewModel').modal('hide');
},
error: function () {
alert("Failed");
}
}).fail(function (xhr, textStatus, err) { alert(err); });
Below is extract from the ViewModel about save function
var Customer = {};
Customer.Id = c.Id;
Customer.Name = c.Name;
Customer.Age = c.Age;
Customer.Address = c.Address;
if (isNewRecord === false) {
$.ajax({
type: "PUT",
url: "/api/CustomerAPI/" + c.Id,
data: Customer
})
.done(function (resp) {
self.Message("Record Updated Successfully ");
self.reset();
})
.fail(function (err) {
self.Message("Error Occures, Please Reload the Page and Try Again " + err.status);
self.reset();
});
}
if (isNewRecord === true) {
isNewRecord = false;
$.ajax({
type: "POST",
url: "/api/CustomerAPI",
data: Customer
})
.done(function (resp) {
self.Message("Record Added Successfully ");
self.reset();
loadData();
}).fail(function (err) {
self.Message("Error Occures, Please Reload the Page and Try Again " + err.status);
self.reset();
});
}
Knockout and Javascript (in this manner) are being processed client side. You will need to create something on the back end to accept your data payload and save it to the database. If you want to stay in the JavaScript family, I would recommend
node.js. Alternatively this is where php, or C# would come into play.

Mongo Returns data with \n

I am using a form builder(https://github.com/kevinchappell/formBuilder). I have been able to store the generated JSON data(note that i am not sure if the data produced is in JSON form I am just storing it in a JS var) into my MongoDB. Here is where the data is coming from:
document.getElementById('getJSON').addEventListener('click', function() {
var ans = formBuilder.actions.getData('json', true);
$.ajax({
type: "POST",
dataType: "json",
data: ans,
url: "/j",
success: function(){
console.log('success');
}
});
document.forms["myForm"].submit();
});
It is generated here and sent as an AJAX call to the node server. The server then does the follows:
mongo.connect(url, function (err, db) {
assert.equal(null, err);
db.collection('clauses').insertOne(req.session.fdata, function (err, result) {
console.log('New Clause Added');
db.close();
});
});
It appears like so in the command prompt
the standard JSON format in which data appears in MongoDB
However when i fetch this data it comes as such:
[ { _id: 596de520ef77eb2614cd1e47,
'[\n\t{\n\t\t"type": "number",\n\t\t"label": "Number",\n\t\t"description":
"total number",\n\t\t"placeholder": "0",\n\t\t"className": "form-
control",\n\t\t"name": "number-1500374279764"\n\t}\n]': '' },
{ _id: 596de520ef77eb2614cd1e48 } ]
Am I passing the data in the wrong form? Or is the inserted data not in JSON in the first place? I am new to working with JSON and NOSQL databases.

SyntaxError:JSON.parse:unexpected character at line 1 column 1 of the JSON data

I've been looking all over for the solution but I cannot find anything that works,I keep getting the following error,I have a submit event that will call the function SUValidation with the data thats being
submitted through a text box in php form,I have tried putting contentType: "application/json",//note the contentType defintion looking at other posts but nothing helped..can anyone provide guidance on how to debug this error or at the best provide a solution
Error:-
SyntaxError:JSON.parse:unexpected character at line 1 column 1 of the JSON data
RESPONSE OF SUVALID.py
Just outputs the content of the python script
Hi,
submit event:-
$("#su_validation").submit(function(event) {
console.log("su_validation.submit");
event.preventDefault();
//SUValidation('#su_validation', '#su_validation_table', '#gerrits_su_validation', showDialog, "#su_validation_dialog");
$("#SUValidation_su_validation_table").empty();
var data = { 'product_lines' : [], 'gerrits' : [], 'contacts' : []};
//find all pl's that are checked
data['product_lines'] = ($("#product_line_su_validation").val()).split(",");
data['gerrits'] = ($("#gerrits_su_validation").val()).split(",");
data['contacts'] = ($("#contacts_su_validation").val()).split(",");
console.log(data);
SUValidation(data, '#SUValidation_su_validation_table', '#gerrits_su_validation', "su_validation_form");
});
Function call:-
function SUValidation(data, table_name, gerrit_form, caller) {
console.log("su_validation_form");
console.log(data);
//console.log($(form_name).find('input, select, textarea').serialize());
su_validation_return = null;
//if maintained, we care if they are in ODS
//if not maintained, we don't really mind if they aren't in ODS database
var maintained = null;
console.log("start when");
$.when(
$.ajax({
dataType: "json",
type: "POST",
url: "scripts/suvalid.py",
timeout: 180000,
data: JSON.stringify(data),
success : function(response){
su_validation_return = [];
console.log("python");
console.log(response);
....
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("error");
//alert(xhr.status);
alert(thrownError);
}
})
).then(function() {
console.log("THEN");
var gerrits = data['gerrits'];
console.log(su_validation_return);
var valid_gerrits = true;
..................

Updating SQLite with AJAX data: how to handle two asynchronous calls

I'm trying to update SQLite with some JSON data fetched via AJAX.
This is my progress so far.
The problem is that this function always returns false. I know that this is because of the second asynchronous execution of the db.transaction. How can I solve this?
Thanks in advance!
function updateDb(url) {
$.ajax({url: url,
type: "get",
dataType: "jsonp",
async: true,
success: function (result) {
ajax.parseJSONP(result);
},
error: function (request,error) {
console.error('Network error while fetching IR JSON!');
}
});
var ajax = {
parseJSONP:function(result){
var db = window.openDatabase("Test", "1.0", "Test DB", 100000);
db.transaction(populateDB, errorCB, successCB);
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS testtable;');
tx.executeSql('CREATE TABLE IF NOT EXISTS testtable (id NUMERIC PRIMARY KEY, testtext TEXT)');
$.each( result, function(i, row) {
tx.executeSql('INSERT INTO testtable (id, testtext) VALUES (' + row[0] + ',\'' + row[1] + '\';');
});
}
function errorCB(err) {
console.error("Error processing SQL: "+err.message);
return false;
}
function successCB() {
console.info("Updating DB successful!");
return true;
}
}
}
}
Ok, I solved this by using two callbacks, one to parseJSONP and one to the success callback.
I think this is a valid solution, however, I really hate navigating only by callbacks.

Categories

Resources