How use the success call back in a delete ajax [NODE.JS] - javascript

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.

Related

How to re render a .ejs page with new data after ajax request

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
}
});

Why am I getting Ajax error {"readyState":0,"responseText":"","status":0,"statusText":"error"}

Okay so I have a node js server running on my local machine and I'm trying to make an Ajax call to my server, the server is accepting the request and the request is executing successfully on the server side but on the client side I'm always getting the error response,
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
My code to make Ajax request is as below,
$(document).ready(function() {
$("#button").click(function(e) {
e.preventDefault();
$.ajax({
crossDomain: true,
type: 'GET',
url: 'http://192.168.1.3:8080/insertintoplaylist?videoid=' + $("#videoid").val(),
async: true,
dataType: 'json',
success: function(res) {
alert("response"+res);
},
error: function(error) {
alert("error!" + JSON.stringify(error));
}
});
});
});
Here is the code snippet which will be executed when client makes a request to the path as mention in the url parameter of ajax call,
var req = youtube.videos.list({
id: video,
part: 'snippet,id'
},function(err,data,response){
if(err){
console.error('Error: ' + err);
}
if(data){
console.log(data.items);
var dataItem = data.items[0];
writeUserData(dataItem.id,dataItem.snippet.title,dataItem.snippet.thumbnails.medium.url,function(){
res.json({msg:'Saved'});
});
}
if(response){
console.log('Status code: ' + response.statusCode);
}
});
function writeUserData(videoId, title, thumbnail,cb) {
console.log("\nWriting data for video ");
firebase.database().ref('kidspoemTesting/' + videoId).set({
title: title,
thumbnail: thumbnail,
},function(err){
if(err){
console.log("Failed to save data"+err);
console.log("\nWriting data failed for video ");
}
else {
console.log("Data saved");
console.log("\nWriting data succeed for video ");
cb();
}
});
}

Passing parameters to routes in node.js

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;
}
});

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');
}
});
}
});
});

catch response when send jsonp request phonegap

I write application by phonegap
Server Side I write by nodejs
exports.login = function(request, response) {
var keys = Object.keys(request.query);
request.body= JSON.parse(keys[1]);
Accounts.findOne({
name : request.body.name
}, function(err, docs) {
if (!docs) {
response.json('{"error": "user-not-found"}');
} else {
console.log("docs: ", docs);
Accounts.validatePassword(request.body.password, docs['hashedPass'], docs['salt'], function(error, res) {
if (error) {
response.json(error);
}
if (res) {
generateToken(request.body.name, request.body.device, function(res) {
if (res) {
response.json('{"token": "' + res + '"}');
} else {
response.json('{"error": "cant-create-token"}');
}
});
} else {
response.json('{"error": "invalid-password"}');
}
});
}
})
}
Phonegap: I write function to login
function LoginUser(info)
{
var varUrl=server+"/auth/login";
$.ajax({
url:varUrl,
type:"GET",
contentType:"application/json",
headers: {
Accept:"application/json",
"Access-Control-Allow-Origin": "*"
},
data:info,
dataType:"jsonp",
success:function(data)
{
console.log("HERE");
console.log(data);
},
error: function(err){
console.log(err);
}
});
}
and I request it will like this http://localhost:3000/auth/login?callback=jQuery161014894121675752103_1361459462241&{%22name%22:%22fdfdfd%22,%22password%22:%22fdfdfdfd%22}&_=1361459615743
and when I see in the response of tab network of developer of chrome is "{\"error\": \"user-not-found\"}"
but I can not catch this repsonse in function LoginUser(info) above
How to get it because in console it print error: function(err){
console.log(err);
}
I dont know why.
Can you help me.
On the server side you have to use callback and in the response of your
jsonp file you need to do:
jQuery161014894121675752103_1361459462241({"error": "user-not-found"})
Where the function name comes from the callback variable in your jsonp request.
Cause a jsonp request just "include" a script tag in your site, which can execute js (basically).

Categories

Resources