how to insert data into same pouchdb with same id - javascript

I have scenario that first onload page i put data into one pouchdb and with same pouchdb with other event of click it have to go server and fetch data in same pouch but it create two id ,but i need is second time it have into same pouch with first time create id how can i do this??
out put:
first time:
ressss---->:{"rows":[{"value":{"existing":[{"pattano":1843,"surveyNo":"156 ","subdivNo":"3B","ownerDetails":[{"relNo":1,"ownerNo":1,"RelationCode":"3","status":"Existing","udsRatio":"0","MaxOwnNumb":"1","relation":"மகள்","owner":"த்ஃப்க்","surveyNo":"156 ","statofown":"E","relative":"த்ஃப்க்","subDivNo":"3B"}]}],"_id":"6163ED1A-B1E8-4A90-8EEF-BF4B1A1E6132","_rev":"1-dea5c55e64c7543a26f24192ec5e94a5"}}]}
second time:
ressss---->:{"rows":[{"value":{"existing":[{"pattano":1843,"surveyNo":"156 ","subdivNo":"3B","ownerDetails":[{"relNo":1,"ownerNo":1,"RelationCode":"3","status":"Existing","udsRatio":"0","MaxOwnNumb":"1","relation":"மகள்","owner":"த்ஃப்க்","surveyNo":"156 ","statofown":"E","relative":"த்ஃப்க்","subDivNo":"3B"}]}],"_id":"6163ED1A-B1E8-4A90-8EEF-BF4B1A1E6132","_rev":"1-dea5c55e64c7543a26f24192ec5e94a5"}},{"value":{"existing":[{"pattano":457,"surveyNo":"111","subdivNo":"4","ownerDetails":[{"relNo":2,"ownerNo":1,"RelationCode":"1","status":"Existing","udsRatio":"0","MaxOwnNumb":"4","relation":"மகன்","owner":"மணிவேல்","surveyNo":"111","statofown":"E","relative":"ஆலப்பன்","subDivNo":"4"}]}],"_id":"E421B84D-2481-4ED1-ABDD-0C0B24BAEB91","_rev":"4-6713d5be5336f69b0f6c776b5c343d49"}}]}
my function is:
function fetchOwners(existingOwnersObj)
{
//alert("in fetch owners");
var inputVal = JSON.stringify(existingOwnersObj);
//alert("inputVal===> "+inputVal);
var hash1 = cal_hmac(inputVal);
var m = "";
document.getElementById('imgdiv')
.style.display = 'block';
$
.ajax(
{
url: urlService + serviceName + '/getPattaOwnersforJoint?jsoncallback=?',
headers:
{
"emp_value": ses,
"signature": hash,
"roleId": roleId,
"timestamp": t,
},
type: 'POST',
dataType: 'jsonp',
data: inputVal.toString(),
// jsonpCallback:"aaa",
contentType: "application/json",
success: function(data)
{
// alert("im in success===>"+JSON.stringify(data));
existown = {};
existown.existing = data;
//existown.slNno=slNno++;
str = JSON.stringify(existown);
//alert("str----->"+str);
var str1 = JSON.parse(str);
//new Pouch('idb://tamilNilamExist', function(err, db)
Pouch(puch, function(err, db)
{
var doc = existown;
db.put(doc, function(err, doc)
{
if (err)
{
return console.error(err);
}
else
{
//alert("Data Locally Stored Successfully adkkdd exizthhh");
$("#imgdiv")
.hide();
}
});
});
// getexist();
//
},
error: function(jqXHR, exception)
{
// alert("Error:"+JSON.stringify(jqXHR));
alert("Error Occured");
document.getElementById('imgdiv')
.style.display = 'none';
}
});
}

It looks like you are using a very old version of PouchDB. If you update to 3.4.0, you should be able to easily do something like:
// only need to instantiate the PouchDB once
var db = new PouchDB('mydb');
// inside of asynchronous functions, just call the db directly
function asyncSomething() {
function asyncSomethingElse() {
db.put(...)
}
}

Related

jQuery Execute function after asynchronous data load

I have created a jQuery function extending its own object $. This function translate those elements attached to the element this:
$.fn.extend({
translate: function(sourceLang, targetLang) {
if($(this).text().trim().length < 1 || !isNaN(parseInt($(this).text().trim())) || sourceLang == targetLang)
return;
let $function = this;
$($function).each(function() {
let $each = this;
$.ajax({
url: 'https://translate.yandex.net/api/v1.5/tr.json/translate',
method: 'GET',
dataType: 'JSONP',
crossDomain: true,
data: {
key: /* my-secret-key */,
text: $($each).text(),
lang: sourceLang + '-' + targetLang
},
success: function(response) {
try {
if(response.code !== 200)
throw "Response: " + response.code;
$($each).text(response.text[0])
} catch(error) {
console.error('Translation error on element: ', $($function).text());
console.error('Message returned by the server:', error);
}
},
error: function(xhr, status, error) {
console.error('Translation error on element: ', $($function).text());
console.error('Message returned by the server:', xhr.responseText);
}
});
});
}
});
After loading the code I do this:
$(document).ready(function() {
let lang = $('html').attr('lang').split('-')[0];
$('td td:visible').translate(lang, "en");
});
Note: the HTML tag looks like this <html lang="es-ES"> depending on the logged user language.
The issue I have is the table loads after a couple of seconds (since we are not in Production environment they could be more than 30). Therefore the previous code block is not useful.
Note: the <tbody> tag is created when the data is added.
What I have tried is:
1. Create a setInterval() and clearInterval() when the $('td:visible').length is greater than 0:
let iv = setInterval(function() {
let lang = $('html').attr('lang').split('-')[0];
let rows = $('tbody td:visible');
if(rows.length > 0) {
rows.translate(lang, "en");
clearInterval(iv);
}
}, 1000);
2. Set a .delay() before the translation:
let isTranslated = false;
while(!isTranslated) {
let lang = $('html').attr('lang').split('-')[0];
let rows = $('tbody td:visible');
if(rows.length > 0) {
rows.delay(1000).translate(lang, "en");
isTranslated = true;
}
}
The memory consumed by the browser is greater than 200MB. I also tried with $('table').on('DOMSubstreeModified', 'tbody', function() {}) but it didn't work.
So, what approach would you recommend to use this translation plugin on this table after it loads its tbody?
Edit 1:
I have changed my code so I perform less API requests, thanks to the recommendation of #lucifer63:
let $function = this;
let collection = [];
let translation = '';
$(this).each(function() {
collection.push($(this).text());
});
let text = collection.join('::');
$.ajax({
url: 'https://translate.yandex.net/api/v1.5/tr.json/translate',
method: 'GET',
dataType: 'JSONP',
crossDomain: true,
data: {
key: /* my-secret-key */,
text: text,
lang: sourceLang + '-' + targetLang
},
success: function(response) {
try {
if(response.code !== 200) {
throw "Response: " + response.code;
}
translation = response.text[0].split('::');
$($function).each(function() {
$(this).text(translation.shift());
});
} catch(error) {
console.error('Message returned by the server:', error);
}
},
error: function(xhr, status, error) {
console.error('Message returned by the server:', xhr.responseText);
}
});
But still, I need to figure out how to print after data has loaded.
Well... I think I found the answer I was seeking:
$('body').on('DOMNodeInserted', 'table', function() {
$('td:visible').translate('es', 'en');
});
It seems it is working correctly.

How to save data in Vue instance

The question is quite simple,
All I want is to get the data after the AJAX post saved in Vue instace's data.
Here is my code:
const VMList = new Vue({
el: '#MODAL_USER_DATA',
data: {
user: []//,
//userAcc: []
},
methods: {
getUserAcc: function ( userID ) {
this.user = { _id : userID };
var self = this
$.ajax({
url: "/listuser",
type: "POST",
data: this.user,
success: function(data) {
this.user = data ;
//this.userAcc = Object.assign({}, this.userAcc, data );
alert(JSON.stringify(this.user));//show the user correctly (e.g user = data)
$('#popupDeleteModal').modal('show');
alert(JSON.stringify(data));//show data,the entire json object,everything is good
},
error: function(err) {
console.log('error: ',err);
},
});
}
}
});
And after I trigger the getUserAcc(id) method,I try to verify the VMList.user value in browser console,and I get only the id.Seems like after the function is over the data is reset.How could I store the data from the AJAX post request in the user object from data:{...} ?
Thank you for help!!!
The problem is that this inside your ajax return function doesn't refer to the vue instance anymore.
The solution is to save the this keyword into a variable inside the function. Example:
getUserAcc: function ( userID ) {
var that = this;
this.user = { _id : userID };
$.ajax({
url: "/listuser",
type: "POST",
data: this.user,
success: function(data) {
that.user = data;
//Rest of your code
},
error: function(err) {
console.log('error: ',err);
},
});
}
Here is more information about the behavior of the keyword this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Pass javascript array to c# array/list using $.post without specifing datatype as json

I have a model created in javascript as follows
function Vehicle() {
this.type = 'Vehicle';
this.data = {
VehicleKey: null
}
};
I have a similar model created in c# as follows
public class Vehicle
{
public string VehicleKey { get; set; }
}
Now I am building an array of VehicleKeys in javascript as follows
function GetVehicleDetails(inputarray) {
var vehicleKeys = [];
for (var i = 0; i < inputarray.length; i++) {
var vehicleObject = new Vehicle();
vehicleObject.data.VehicleKey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
vehicleKey.push(vehicleObject.data);
}
return vehicleKeys ;
}
I am calling the $.post(url, data) as follows
var objectToSend = GetVehicleDetails(selectedVehicles);
var data = JSON.stringify({
'vehicles': objectToSend
});
$.post(url, data)
.done(function (result) {
if (result) {
download(result, 'VehicleReport.xlsx', { type: 'application/octet-stream' });
console.log("Report created successfully");
}
else {
console.log("Error creating report");
}
}).fail(function (error) {
console.log("Error creating report.");
});
The MVC Controller has a method to accept Vehicles with multiple VehicleKeys coming from javascript
public byte[] CreateVehicleReport(List<Vehicle> vehicles)
{
//Generation of report and pass it back to javascript
}
Here I am able to submit the data in javascript as 10 and 11 for Vehicles but when it catches the c#, the count is coming as 0.
Any help would be greatly appreciated.
$.post is not posted Content-Type json data so you need to use $.ajax
function GetVehicleDetails(inputarray) {
var vehicleKeys = [];
for (var i = 0; i < inputarray.length; i++) {
var vehicleObject = {}; // Set Object
vehicleObject.VehicleKey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
vehicleKeys.push(vehicleObject);
}
return vehicleKeys;
}
var objectToSend = GetVehicleDetails(selectedVehicles);
$.ajax({ type: 'POST',
url: url,
data: JSON.stringify(objectToSend),
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('data: ' + data);
},
}).done(function () {
if (result) {
console.log("Report created successfully");
}
else {
console.log("Error creating report");
}
}).fail(function () {
console.log("Error creating report.");
});
C# Method
[HttpPost("CreateVehicleReport")]
public byte[] CreateVehicleReport([FromBody]List<Vehicle> vehicles)
{
return null;
//Generation of report and pass it back to javascript
}
I used a similar approach once but with ajax and it went like this:
fill your array directly with the properties inside your class as object { } make sure the names are exactly the same:
function GetVehicleDetails(inputarray) {
var data_Temp = [];
for (var i = 0; i < inputarray.length; i++) {
var _vehiclekey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
data_Temp.push({ VehicleKey : _vehiclekey });
});
return data_Temp;
}
var objectToSend = GetVehicleDetails(selectedVehicles);
var JsonData = JSON.stringify({ vehicles: objectToSend });
$.ajax({
type: "POST",
contentType: "application/json",
url: "/controllerName/actionName", //in asp.net using mvc ActionResult
datatype: 'json',
data: JsonData,
success: function (response) {
},
error: function (response) {
console.log(response);
}
});
And the ActionResult in the controller should look like this:
[HttpPost]
public ActionResult Create(List<Vehicle> vehicles)
{
//do whatever you want with the class data
}
I don't know if this is helpful for you but this always works for me and i hope it helps.

How to combine similar functions - Javascript

I have two functions that are very similar and I would like if possible to combine them. The only issue that I have is one function is accepting 2 arguments and the other one is accepting 3. Is there a way to do this or these two functions have to stay separated by design?
function getClientData(id, command) {
var formData = {
'method': command,
'id': id
};
getEntityData(formData);
}
function getLocation(id, clientid, command) {
var formData = {
'method': command,
'locationid': id,
'clientbrandid': clientid
};
getEntityData(formData);
}
Update
function getEntityData(data) {
var url = '/../admin/miscellaneous/components/global.cfc?wsdl';
var ajaxResponse = $.ajax({
url: url,
dataType: 'json',
data: data,
global: false,
async:false,
cache: false,
success: function(apiResponse){
return apiResponse;
}
}).responseJSON;
var response = ajaxResponse[0];
for (var i in response) {
if (response.hasOwnProperty(i)){
$("#edit"+i).val(response[i].trim());
}
}
}
yes you can, I prefer instead of passing each parameter you can pass a js object, and decide wich params it contains for example:
function getLocation(options) {
getEntityData(options);
}
and your call should be:
getLocation({'method': command,'id': id})
Update
or you can just avoid getLocation function and just call getEntityData
getEntityData({
'method': command,
'id': id
});
I would go with:
function getWhatever(id, command, clientId) {
var formData = { method: command };
if (typeof clientId === 'undefined') {
formData.id = id;
} else {
formData.locationid = id;
formData.clientbrandid = clientId;
}
getEntityData(formData);
}
function getLocation(id, clientid, command) {
var formData = {
'method': command,
'locationid': id
};
if (clientid) {
formData['clientbrandid'] = clientid;
}
getEntityData(formData);
}
// With
getLocation(1, 2, 'doStuff');
// Without
getLocation(1, '', 'doStuff');
Maybe a more rational order of arguments:
function getLocation(id, command, clientid) {
var formData = {
'method': command,
'locationid': id
};
if (clientid) {
formData['clientbrandid'] = clientid;
}
getEntityData(formData);
}
// With
getLocation(1, 'doStuff', 2);
// Without
getLocation(1, 'doStuff');
And if locationid and id are different:
function getLocation(id, command, clientid) {
if (clientid) {
var formData = {
'method': command,
'locationid': id,
'clientbrandid': clientid
};
} else {
var formData = {
'method': command,
'id': id,
};
}
getEntityData(formData);
}
// With
getLocation(1, 'doStuff', 2);
// Without
getLocation(1, 'doStuff');
I guess it really depends on what your arguments actually are, but this is also a solution. (Assuming that client id is an object).
function getLocation(id, command, clientid) {
var _clientId = clientid || {};
var formData = {
'method': command,
'locationid': id,
'clientbrandid': _clientid
};
getEntityData(formData);
}

Postponing window.location to allow time for AJAX

I have an index page which I'd like to use to set up a local database before moving on to another page. However, whenever I have the window.location code activated none of the other functions run, but when I comment it out the other functions run fine. Any ideas to what would be causing this and how I can get both the functions and the window.locations to work? Code is as follows:
<script>
var db = window.openDatabase("DB1", "", "DB", 1024 * 1000)
CreateDB(); //Creates local database tables
loadRouteList(); //Queries web server database using AJAX and inserts Routes
window.location = 'Application.html';
</script>
Functions Used:
function CreateDB() {
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Routes(id INTEGER PRIMARY KEY, routeID TEXT, customerID TEXT, stopSeq TEXT, driverID TEXT)', []);
});
};
function loadRouteList() {
var dataObject = {
postDesignator: 'routes',
};
$.ajax({
url: 'http://url.php',
data: dataObject,
dataType: 'json',
type: 'post',
success: function (Result) {
for (var i = 0, len = Result.records.length; i < len; ++i) {
var route = Result.records[i].record;
insertRoute(route.routeID, null, null, null);
}
}
});
}
use callbacks! I modified your code:
<script>
var db = window.openDatabase("DB1", "", "DB", 1024 * 1000);
CreateDB(); //Creates local database tables
loadRouteList(function() { window.location = 'Application.html'} );
</script>
Functions Used:
function CreateDB() {
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Routes(id INTEGER PRIMARY KEY, routeID TEXT, customerID TEXT, stopSeq TEXT, driverID TEXT)', []);
});
};
function loadRouteList(callback) {
var dataObject = {
postDesignator: 'routes',
};
$.ajax({
url: 'http://url.php',
data: dataObject,
dataType: 'json',
type: 'post',
success: function (Result) {
for (var i = 0, len = Result.records.length; i < len; ++i) {
var route = Result.records[i].record;
insertRoute(route.routeID, null, null, null);
}
// this is the so called callback, that gets executed AFTER the ajax has finished
if(callback) { callback(); }
}
});
}
By definition, AJAX is Asynchronous, so if you run those functions and you don't wait them to be completed, your code will go on without waiting them. So you arrive at the point that your location changes due to your line. You have to wait until all your requests are done before going on, and to do this you have to change the code inside your functions. If you post them we could help you.
EDIT
In my opinion, the best way to do it is to pass a callback to your function:
function CreateDB() {
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Routes(id INTEGER PRIMARY KEY, routeID TEXT, customerID TEXT, stopSeq TEXT, driverID TEXT)', []);
});
//if even this piece of code is async you should read docs and check how to call a function after the query executed
};
function loadRouteList(callback) {
var dataObject = {
postDesignator: 'routes',
};
$.ajax({
url: 'http://url.php',
data: dataObject,
dataType: 'json',
type: 'post',
success: function (Result) {
for (var i = 0, len = Result.records.length; i < len; ++i) {
var route = Result.records[i].record;
insertRoute(route.routeID, null, null, null);
}
if(callback) {
callback();
}
}
});
}
And then use it this way:
var db = window.openDatabase("DB1", "", "DB", 1024 * 1000)
CreateDB(); //Creates local database tables
loadRouteList(function() {
window.location = 'Application.html';
});

Categories

Resources