AJAX not firing before Callback - javascript

I'm attempting to run an AJAX query and insert the results into a local database before moving onto a new window.location. However, the success function to insert the results does not run. Instead the callback function causes the new page to load. If I comment out the if (callback {callback();} then the AJAX completes the inserts, but the window.location code is obviously not called. The callback function seems to get called before the AJAX success function is completed. How do I get the AJAX success to insert the results before moving on? Here's the code I'm using:
<script>
var db = window.openDatabase("MantisMobileDB1", "", "MantisMobileDB", 1024 * 1000);
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 insertRoute(routeID, customerID, stopSeq, driverID) {
db.transaction(function (tx) {
tx.executeSql('INSERT INTO Routes (routeID, customerID, stopSeq, driverID) VALUES (?, ?, ?, ?)', [routeID, customerID, stopSeq, driverID], CountReturns);
});
}
function loadInitialRouteList(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(); }
}
});
}
if (localStorage.getItem('exitsatus') === null) {
CreateDB();
loadInitialRouteList(function () { window.location = 'Application.html'; });
}
else {
window.location = localStorage.getItem('exitsatus');
}
</script>

Related

Populate Select2 from function call with AJAX

I want to populate a select2 dropdown with an AJAX response function with data that will be called whenever the dropdown required for it changes value. I console logged to be sure that the function gets reached, but nonetheless, the instructions are not being ran by the machine:
create.tpl - Holds front-end code
$('.select2lead').select2({
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajaxLeadSearch.php',
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term
};
},
processResults: function (data) {
return {
results: data,
more: false
};
}
}
});
$('.select2lead').on("change", function() {
var value = $(this).val();
// console.log(value);
searchProjectsByLeadID(value);
});
function searchProjectsByLeadID(id){
$('.select2project').select2({
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajaxProjectSearch.php',
dataType: 'json',
delay: 250,
data: {
"id": id
},
processResults: function (data) {
return {
results: data,
more: false
};
}
}
});
console.log(id);
}
ajaxProjectSearch.php
<?php
require_once('../../config.php');
$login = new Login();
if (!$login->checkLogin()) {
echo lang($_SESSION['language'], "INSUFFICIENT_RIGHTS");
exit();
}
$db = new Database();
// Select the projects
$query = "
SELECT
ProjectID AS project_id,
ProjectSummaryShort AS project_summary,
FROM
`rapports_projectTBL`
INNER JOIN LeadTBL ON rapports_projectTBL.LeadID=LeadTBL.LeadID
WHERE
ProjectID > 0
AND
rapports_projectTBL.LeadID LIKE :leadId
ORDER BY
ProjectID
ASC
";
$binds = array(':leadId' => $_GET['id']);
$result = $db->select($query, $binds);
$json = [];
foreach ($result as $row){
$json[] = ['id'=>$row['project_id'], 'text'=>$row['project_summary']];
}
echo json_encode($json);
Network output in console
https://i.imgur.com/6ZmGGxa.png
*As we can see, the searchProjectsByLeadID(id) function gets called but we get nothing back. No errors nor any values. The only thing getting transported is the first select box, which fetches lead data upon whats typed in the searchbox. *
RESOLVED
Issue was called by having the SQL query looking for a LIKE rather than a DIRECT MATCH:
WRONG
WHERE
ProjectID > 0
AND
rapports_projectTBL.LeadID LIKE :leadId
CORRECT
WHERE
rapports_ProjectTBL.LeadID=:leadId

jquery ajax store variable and then retrieve later on

Hi i am using jquery and ajax to retrieve the user id of the logged in user, Im saving this into a variable as I want to be able to do some logic with it later on. however I am having trouble accessing it. My code is below:
$(document).ready(function () {
var taskBoard = {
fetch: function (url, data) {
$('.loading-icon').fadeIn();
$('.task_board').addClass('loading');
$.ajax({
url: url,
async: true,
dataType: 'json',
data: data,
type: 'POST',
success: function (json) {
$('.loading-icon').fadeOut();
$('#task_board').html($(json.data.taskBoard));
$('.task_board').removeClass('loading');
$('.update-results').hide();
} // end success
}); //end ajax
}, //end fetch function
authUser: function (url, data) {
$.ajax({
url: url,
async: true,
dataType: 'json',
data: data,
type: 'POST',
success: function (json) {
$.each($(json), function (index, item) {
taskBoard.storeUser(item.id);
});
} // end success
}); //end ajax
}, //end authUser function
storeUser: function (param) {
var authUserId = param;
return param;
// if I do an alert here the correct user id is returned.
},
} //end var taskBoard
//However if I do an alert here outside of the var taskBoard I get an undefined.
alert(taskBoard.storeUser());
});
Any ideas how I can get this globally assigned variable outside of this function?
change this
storeUser: function (param) {
var authUserId = param;
return param;
// if I do an alert here the correct user id is returned.
},
change to this:
authUserId : null,
storeUser: function (param) {
if (param)
{
this.authUserId = param;
}
return this.authUserId;
},
Now the var authUserId will be stored as a property in the taskBoard object.
When param is undefined it will return the value unupdated if not it will update it first and then returns it.
A more elegant solution would be to use Object.defineProperty here.
Delete the storeUser property and after the declaration of the taskBoard object add this:
Object.defineProperty(taskBoard, "storeUser", {
get : function(){ return this.StoreUserVar; },
set : function(value){ this.StoreUserVar = value; }
});
Now you can assign the userid with:
taskBoard.storeUser = item.id;
//-------- taskBoard object
success: function (json) {
$.each($(json), function (index, item) {
taskBoard.storeUser = item.id;
doOtherFunction();
});
//--------
function doOtherFunction()
{
//the callback function fired from the success.
alert(taskBoard.storeUser); //this will alert with the value set.
}
Well if you need a global variable then declare that variable before the document.ready, since variables defined in this function are only valid in this function
Javascript Scope Examples

how to insert data into same pouchdb with same id

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(...)
}
}

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.

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