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');
}
});
}
});
});
Related
I need to re render my homepage.ejs with new data on the server side after an ajax request. I know you can (somehow) re render the elements in the ajax callback but I was wondering if I could just re render my homapage.ejs since I have if statements that look for vacations, and current_user variables to set the right partialview.ejs
my ajax method:
function user_login(email, password) {
var data = {};
data.email_login = email;
data.password_login = password;
var message_header = $("#message_header");
$.ajax({
url: "/sign_in",
method: 'POST',
data: data
}).done(function (res) {
if (!res.success) {
message_header.text("Incorrect email of password. Please try again.").css("color", "red");
$("#username_textfield").val("");
$("#password_textfield").val("");
}
if (res.success) {
console.log("user logged");
}
});
my server side (inside of a query callback)
get_all_vacations(function (error, vacations) {
if (error) {
console.log("error when getting vacations " + error);
response.json({ success: false });
} else {
request.session.vacations = vacations;
response.render('the_vacation.ejs', { vacations : vacations, current_user : new_current_user }, function() {
response.json({success : true});
console.log("in render method");
});
}
});
i tried this but it does not work.
response.render('the_vacation.ejs', { vacations: vacations, current_user: new_current_user });
I think the simplest way, based on how your code is written would be to use window.location.reload(); when the login is successful.
function user_login(email, password) {
var data = {};
data.email_login = email;
data.password_login = password;
var message_header = $("#message_header");
$.ajax({
url: "/sign_in",
method: 'POST',
data: data
}).done(function (res) {
if (!res.success) {
message_header.text("Incorrect email of password. Please try again.").css("color", "red");
$("#username_textfield").val("");
$("#password_textfield").val("");
}
if (res.success) {
console.log("user logged");
window.location.reload(); // <--- Cause the browser to reload the EJS
}
});
I am very new to Web Development. I used to do desktop development using WPF and C#. Now I am learning Node.js
I have a model called Party.js in which I define two exports as follows:
module.exports.getAllParties = function(callback){
Party.find().lean().exec(function(err, parties){
if (err) return callback(err, null);
callback(null, parties);
});
};
module.exports.getPartyByPartyCode = function(partyCode, callback){
Party.find({partyCode: partyCode}).exec(function(err, party){
if(err) return callback(err, null);
callback(null, party);
});
};
Now, I also have a route called Party.js in which I have two get methods as follows:
router.get('/', function(req, res, next){
//retrieve all parties from Party model
Party.getAllParties(function(err, parties) {
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//response in dust or jade files
html: function(){
res.render('Party', {
title: 'Party',
"parties" : parties
});
},
//JSON response will show all parties in JSON format
json: function(){
res.json(parties);
}
});
}
});
});
router.get('/:partyCode', function(req, res, next){
Party.getPartyByPartyCode(function(err, party) {
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//response in dust or jade files
html: function(){
res.render('Party', {
title: 'Party',
"party" : party
});
},
//JSON response will show all parties in JSON format
json: function(){
res.json(party);
}
});
}
});
});
Now, when I use ajax:
var inputElem = $('#partyForm :input[name="partyCode"]'),
inputVal = inputElem.val(),
data = { partyCode : inputVal },
eReport = ''; //error report
$.ajax(
{
type: "GET",
url: "/Party",
dataType: "json",
data: data,
beforeSend: function(jqXHR, settings)
{
console.log(settings.url);
},
success: function(party)
{
if (party)
{
console.log(party);
return 'Party ' + party.partyName + ' has already taken party code: ' + party.partyCode + '. Please choose a different PartyCode.';
}
else
{
console.log("party does not exist.");
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
alert('ajax loading error... ... '+url + query);
return false;
}
});
My question is: Why the above ajax call returns me all the parties? I just want to get a party whose patyCode is passed in to the ajax call's data....
There are some errors in both your router response code and ajax function:
First correct your router code:
You were not using the provided party code in your model.
router.get('/:partyCode', function (req, res, next) {
var partyCode = req.param('partyCode');
Party.getPartyByPartyCode(partyCode, function (err, party) {
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//response in dust or jade files
html: function () {
res.render('Party', {
title: 'Party',
"party": party
});
},
//JSON response will show all parties in JSON format
json: function () {
res.json(party);
}
});
}
});
});
Correct Ajax function calling
You must provide the party code as a URL parameter as your router indicates like that /:partyCode. Try the following:
var inputElem = $('#partyForm :input[name="partyCode"]'),
inputVal = inputElem.val(),
eReport = ''; //error report
$.ajax({
type: "GET",
url: "/"+inputVal,
dataType: "json",
data: data,
beforeSend: function (jqXHR, settings) {
console.log(settings.url);
},
success: function (party) {
if (party)
{
console.log(party);
return 'Party ' + party.partyName + ' has already taken party code: ' + party.partyCode + '. Please choose a different PartyCode.';
}
else
{
console.log("party does not exist.");
return true;
}
},
error: function (xhr, textStatus, errorThrown) {
alert('ajax loading error... ... ' + url + query);
return false;
}
});
I'm running into a scenario where my meteor server call is posting to a remote URL and then returning the result. However, my meteor client is expecting a result right away and its receiving an empty string (the default return).
What is the correct way of implementing this?
Meteor.methods({
run: function(options){
return HTTP.post(apiUrl, {
params:
{
"headers": headers
}
},
function (error, result)
{
if (error)
{
console.log("error: " + error);
}
else
{
console.log("result: " + JSON.stringify(result));
console.log(result.content);
}
})
});
on my client
Meteor.call('run', '1', function(err,response) {
if(err) {
console.log(err);
return;
}else{
r = response;
console.log(JSON.stringify(r));
FileSystem.update({ _id: fileid }, { $set: {taskid:taskid} }, function (e, t) {
if (e) {
}else{
}
});
}
});
I'm expecting on the client side that it waits for the full result to come in which contains the desired data to save to data base (taskid).
You are calling HTTP.post asynchronously. Just remove the callback function and it becomes synchronous, i.e., you will get a return value that contains the result of the call:
Meteor.methods({
run: function(options){
return HTTP.post(apiUrl, {
params:
{
"headers": headers
}
});
});
});
I'm using the following code to delete a collection in my db:
Client:
$('.destroy').click(function() {
if(confirm("Are u sure?")) {
$.ajax({
type: 'DELETE',
url: '/destroy/' + dataId,
success: function(response) {
console.log('Success');
}
});
} else {
alert('Cancelled');
}
});
Server:
app.get('/destroy/:id', function(req, res) {
var id = req.param("id");
MyModel.remove({
_id: id
}, function(err){
if (err) {
console.log(err)
}
else {
console.log('Collection removed!');
}
});
});
Is working, if i click in the destroy button and reload the page, the collection will not be there, but the success callback function with the: [console.log('Success');] is not running..
I need send a callback from the server to the client ir order to make the success function run???
How make the console.log('Success'); run??
Thanks.
The ajax call probably just times out, as it's never getting a response back from the server.
Send a response from the server
app.get('/destroy/:id', function(req, res) {
var id = req.param("id");
MyModel.remove({
_id: id
}, function(err){
if (err) {
res.end('error');
}
else {
res.end('success');
}
});
});
Then catch it
$.ajax({
type : 'DELETE',
url : '/destroy/' + dataId,
success : function(response) {
if ( response === 'error' ) {
alert('crap!');
} else if (response === 'success' ) {
alert('worked fine!');
}
}
});
This is a simplified example, you can return whatever you like, send statusCodes or whatever.
var Attendance = require('../../../collections/attendance').Attendance;
var moment = require('moment');
module.exports = function(app) {
app.get('/api/trackmyclass/attendance', function(req, res) {
var data = req.body;
data['user'] = req.user;
Attendance.getByUser(data, function(err, d) {
if (err) {
console.log('This is the err' + err.message);
res.json(err, 400);
} else {
var job = d['attendance'];
if (typeof job != undefined) {
res.json(job);
console.log('This is it' + job['status']);
} else
res.json('No data Present', 200);
}
});
});
app.post('/api/trackmyclass/attendance', function(req, res) {
var data = req.body;
data['user'] = req.user;
Attendance.create(data, function(err, d) {
if (err) {
console.log('This is the err' + err.message);
res.json(err, 400);
} else {
var attendance = d['attendance'];
if (typeof job != undefined) {
console.log('Attendance record created' + attendance);
res.json(attendance);
} else
res.json('No data Present', 200);
}
});
});
}
This is the api code I to which I need to make the GET and POST request. But I have no idea how to do it.
It looks like your code is using express which would normally be good for building and API for your app. However to make a simple request to a third party api and staying in node.js why not try the request module which is great. https://www.npmjs.org/package/request
Your example does not show what the path of the request is or if you need any additinal headers etc but here is a simple example of a GET request using request.
var request = require('request');
function makeCall (callback) {
// here we make a call using request module
request.get(
{ uri: 'THEPATHAND ENDPOINT YOU REQUEST,
json: true,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
}
},
function (error, res, object) {
if (error) { return callback(error); }
if (res.statusCode != 200 ) {
return callback('statusCode');
}
callback(null, object);
}
);
}
or jquery .ajax from a front end client direcct to your path
$.ajax({
url: "pathtoyourdata",
type: "GET",
})
.done(function (data) {
//stuff with your data
});