wait for parse.com delete to finish before rendering screen - javascript

My code below will delete my row but it will display the error message.
Any ideas?
delete: function(id) {
// Check login
if (!Parse.User.current()) {
this.navigate('#/login', { trigger: true });
} else {
var query = new Parse.Query(Blog);
query.get(id, {
success: function(id) {
id.destroy({});
alert('Delete Successful');
},
error: function(blog, error) {
console.log(error);
alert('Error in delete query');
}
});
}
}
});
My script for parse is..
<script src="//www.parsecdn.com/js/parse-1.2.19.min.js"></script>

Related

Parse Cloud Code query after save don't works

After saving an array of objects, I do a query for count the number of elements of a class, but the code doesn't run.
Parse.Cloud.define("saveItem", function(request, response) {
Parse.Cloud.useMasterKey();
... (Updating objects...)
Parse.Object.saveAll([item, activity], {
success: function(list) {
response.success("saved"); // <--- THE OBJECTS ARE SAVED, ALLRIGHT
var query = new Parse.Query("Item"); // <--- FROM HERE
query.count({
success: function(count) {
console.log("inside count"); // <--- NOT ENTER HERE!!
},
error: function(error) {
// The request failed
}
});
},
error: function(error) {
response.error(error);
},
});
You need to complete your operations before calling response.success("saved")
Calling response.success is effectively killing the rest of your code.
Parse.Cloud.define("saveItem", function(request, response) {
Parse.Cloud.useMasterKey();
//... (Updating objects...)
Parse.Object.saveAll([item, activity], {
success: function (list) {
var query = new Parse.Query("Item");
query.count({
success: function (count) {
response.success(count);
},
error: function (error) {
// The request failed
response.error("Unable to count items...");
}
});
},
error: function (error) {
response.error(error);
},
});
});

Relation field query not working as expected

I have an Event table and it has a column called "attendees" which is a Relation type to _User [many to many].
I have tried the following to get a list of all _Users who are attending an Event based on the objectId for the event. In my code below the success and error callbacks are not being called. (Neither SUCCESS or ERROR is being printed to the error log.)
Parse.Cloud.define("cancelEvent", function(request, response) {
var query = new Parse.Query("Event");
query.get(request.params.eventId, {
success: function(event) {
// event.set("status", "cancelled");
// event.save();
// notify attendees of cancellation
var relation = event.relation("attendees");
var innerQuery = relation.query();
innerQuery.find({
success: function(attendees) {
console.error("SUCCESS");
},
error: function(error) {
console.error("ERROR");
}
});
event.save();
response.success();
},
error: function(object, error) {
console.error("Failed to cancel event.");
response.error(error);
}
});
});
Move event.save();
response.success();
to inside the success callback like this
Parse.Cloud.define("cancelEvent", function(request, response) {
var query = new Parse.Query("Event");
query.get(request.params.eventId, {
success: function(event) {
// event.set("status", "cancelled");
// event.save();
// notify attendees of cancellation
var relation = event.relation("attendees");
var innerQuery = relation.query();
innerQuery.find({
success: function(attendees) {
console.error("SUCCESS");
event.save();
response.success();
},
error: function(error) {
console.error("ERROR");
}
});
},
error: function(object, error) {
console.error("Failed to cancel event.");
response.error(error);
}
});
});

node-mssql transaction not committing

I am trying to run queries again my database using node-mssql. Everything works perfect. But when I try to execute queries within a transaction, transaction gets committed but tables remain empty. Can someone check whats wrong with the code:
var transaction = new sql.Transaction(/* [connection] */);
transaction.begin(function(err) {
// ... error checks
console.log("[Info]","Begin Transaction.");
if(err) {
console.log(err);
process.exit(-1)
}
var request = new sql.Request(transaction);
var transactionFailed = false;
var request = new sql.Request(transaction);
//request.multiple = true;
request.verbose = true;
request.query(upsertQuery);
console.log("[Info]",request)
request.on('error', function(err) {
transactionFailed = true;
console.log(['Error'],err.toString())
});
request.on('done', function(errs) {
if(transactionFailed) {
transaction.rollback(function(err) {
if(err) {
console.log(err);
process.exit(-1)
}
else {
process.exit(-1)
}
});
}
else {
transaction.commit(function(err) {
if(err) {
console.log(err);
process.exit(-1)
}
else {
console.log("Transaction Committed!")
}
});
}
});
});
Issue was with my sql query. the above code works fine

Page not uploading after res.send()

I am building a node.js web app and have a delete function that queries a mongo database, deletes a document and then sends the user to another page.
However, after the function is invoked the new page doesn't reload even though the document is deleted and I can manually load that page. Instead the existing page just sits there.
Here is GET message I see from the terminal after the function completes:
GET /students 200 9ms - 5.64kb
The delete function:
remove: function(req, res) {
function(err, result) {
Models.Student.remove({myid:{$regex:req.params.students_id}},function(err,removed) {
if (err){
throw err;
}
else{
res.send('/students');
}
})
},
The function to render the new page:
index: function(req, res) {
var viewModel = {
student: [],
};
Models.Student.find({},function(err, student) {
if (err) { throw err; }
if (student) {
viewModel.student=student;
res.render('../views/students.handlebars',viewModel);
}
else {
res.redirect('/');
}
});
},
The Jquery script:
$(function(){
$('#btn-delete').on('click', function(event) {
event.preventDefault();
var $this = $(this);
var remove = confirm('Are you sure you want to delete this student?');
if (remove) {
var studentid = $(this).data('id');
$.ajax({url: '/students/'+studentid, type: 'DELETE'}).done(function(result) {
if (result) {
$.ajax(
{type: 'GET',
url:'/students',
success: function(){
console.log('success');
}
}
)
}
else{
console.log('Unable to delete');
}
});
}
});
});
And the routing:
app.get('/students',students.index);
I really appreciate any help given.
After res.send (), call return next (); with no parameter to trigger next middleware which will send 200 status along with /students string. Only then the done () resolver in ajax will be trigger.
I managed to get the new page to load by adding a window command after done():
$.ajax({url: '/students/'+studentid, type: 'DELETE'}).done(function(result) {
if (result) {
$.ajax(
{type: 'GET',
url:'/students',
success: function(){
console.log('success');
window.location.href='/students';
}
}
)
}
else{
console.log('Unable to delete');
}
});
}
});
});

CasperJS weird evaluate behavior

So, I have this code...
var config = require('./config.js');
var casper = require('casper').create(config.casper);
casper.on("page.error", function(msg, trace) {
this.echo("Page Error: " + msg, "ERROR");
});
casper.on('remote.message', function(msg) {
this.echo('remote message caught: ' + msg);
});
function run () {
casper.start();
casper.thenOpen('https://twitter.com', function () {
if ( this.exists('form[action="https://twitter.com/sessions"].signin') ) {
this.echo('logging in...');
this.evaluate(function (username, password) {
document.querySelector('#signin-email').value = username;
document.querySelector('#signin-password').value = password;
document.querySelector('.flex-table-btn').click();
}, config.users.user.twitter.username, config.users.user.twitter.password);
} else {
this.echo('Alreaddy logged in, proceed...');
}
});
casper.waitForSelector('#tweet-box-mini-home-profile', function () {
if ( this.exists('#tweet-box-mini-home-profile') ) {
this.evaluate(function (text) {
document.querySelector('div#tweet-box-mini-home-profile.tweet-box.rich-editor.notie').innerText = text;
document.querySelector('button.btn.primary-btn.tweet-action.js-tweet-btn').click();
}, 'Test using automation');
this.wait(10000, function () {
this.echo ('Finished waiting, closing app now');
}); //wait for 10 seconds before closing
} else {
this.echo('Failed to logging in');
}
});
casper.run();
}
run();
The logging in part works just fine, I could logging in onto the dashboard.
But the second step, the tweeting step throw an error
Page Error: TypeError: 'null' is not an object (evaluating 'document.querySelector('div#tweet-box-mini-home-profile.tweet-box.rich-editor.notie').innerText = text')
and the tweet won't got posted. I've tried it manually on the browser and it works just fine.
var config = require('./config.js');
var casper = require('casper').create(config.casper);
casper.on('remote.message', function(msg) {
this.echo('remote message caught: ' + msg);
});
casper.on("page.error", function(msg, trace) {
this.echo("Page Error: " + msg, "ERROR");
});
function run () {
casper.start();
casper.thenOpen('https://twitter.com', function () {
if ( this.exists('form[action="https://twitter.com/sessions"].signin') ) {
this.echo('logging in...');
this.evaluate(function (username, password) {
document.querySelector('#signin-email').value = username;
document.querySelector('#signin-password').value = password;
document.querySelector('.flex-table-btn').click();
}, config.users.dida.twitter.username, config.users.dida.twitter.password);
} else {
this.echo('Alreaddy logged in, proceed...');
}
});
casper.waitForSelector('#tweet-box-mini-home-profile', function () {
if ( this.exists('#tweet-box-mini-home-profile') ) {
this.evaluate(function (text) {
console.log('=========== Putting text ============');
document.querySelector('#tweet-box-mini-home-profile > div').innerHTML = text;
}, 'Test using automation');
} else {
this.echo('Failed to logging in');
}
});
casper.then(function () {
if ( this.exists('.js-tweet-btn') ) {
//recheck the tweet
this.echo(this.getHTML('#tweet-box-mini-home-profile'));
this.echo('============= Clicking Submit Button ==============');
this.click('.js-tweet-btn');
this.wait(10000, function () {
this.echo ('Finished waiting, closing app now');
}); //wait for 10 seconds before closing
} else {
this.echo('Submit button not found');
}
})
casper.run();
}
run();
this works, but it only tweet : "Compose new Tweet"
as if the text never change.
So my question is, did I do something wrong or this is some kind of bug? If so, is that a workaround? Thank you in advance.
First of all, use fillSelectors() or fillXPath() methods for filling forms.
And make sure that selector 'div#tweet-box-mini-home-profile.tweet-box.rich-editor.notie' is correct.

Categories

Resources