How to deal AJAX or XRH post request in ExpressJs, where the request use JSON from front-end to back-end? - ajax

environment:
-> Front-end: jquery that randle ajax request
-> Back-end: nodejs, expressjs (v.3.4.8).
I trying to create a simple contact form.
my front-end code:
var nome = $('#nome').val();
var email = $('#email').val();
var assunto = $('#assunto').val();
var mensagem = $('#mensagem').val();
var info = {'nome':nome, 'email':email, 'assunto':assunto, 'mensagem':mensagem};
$.ajax({
type: "POST",
url: "/contact",
data: { info: JSON.stringify(info) }
}).done(function(retorno){
//do something important
});
this work fine, i tested and on firebug everything from front-end is ok.
but i dont know how to deal with express that need read json from post request.
I just have it:
app.post('/contact', function(req, res){
});

The problem is in:
var info = {'nome':nome, 'email':email, 'assunto':assunto, 'mensagem':mensagem};
Just change the JSON ' ' to " " and works fine. I came from php and php recognize both ' ' and " " on a JSON, but nodejs just recognize strictly " ".
After some coding the result for a simple example of contact form is:
In a file common.js (front-end):
var nome = $('#nome').val();
var email = $('#email').val();
var assunto = $('#assunto').val();
var mensagem = $('#mensagem').val();
var info = {"nome":nome, "email":email, "assunto":assunto, "mensagem":mensagem};
$.ajax({
type: "POST",
url: "/contact",
data: JSON.stringify(info),
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(retorno){
//do something at the end
}
In a file app.js or server.js or anything else (back-end):
var http = require("http")
, express = require('express')
, nodemailer = require('nodemailer')
, app = express();
app.use(express.json());
app.use(express.static(__dirname+'/public'));
app.post('/contact', function(req, res){
var name = req.body.nome;
var email = req.body.email;
var subject = req.body.assunto;
var message = req.body.mensagem;
var mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "your.user#gmail.com",
pass: "your.password"
}
});
mailOpts = {
from: name + ' <' + email + '>', //grab form data from the request body object
to: 'recipe.email#gmail.com',
subject: subject,
text: message
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.send(false);
}
//Yay!! Email sent
else {
res.send(true);
}
});
});
app.listen(80, '127.0.0.2');
From this example: http://blog.ragingflame.co.za/2012/6/28/simple-form-handling-with-express-and-nodemailer

Related

Is there a way to show "Loading data.." option in Rally Grid(ext JS) while making the Ajax request to load the data?

I am trying to set the message to "Data Loading.." whenever the data is loading in the grid. It is working fine if I don't make an Ajax call. But, when I try to make Ajax Request, It is not showing up the message "Loading data..", when it is taking time to load the data. Can someone please try to help me with this.. Thanks in Advance.
_loadData: function(x){
var that = this;
if(this.project!=undefined) {
this.setLoading("Loading data..");
this.projectObjectID = this.project.value.split("/project/");
var that = this;
this._ajaxCall().then( function(content) {
console.log("assigned then:",content,this.pendingProjects, content.data);
that._createGrid(content);
})
}
},
_ajaxCall: function(){
var deferred = Ext.create('Deft.Deferred');
console.log("the project object ID is:",this.projectObjectID[1]);
var that = this;
console.log("User Reference:",that.userref,this.curLen);
var userObjID = that.userref.split("/user/");
Ext.Ajax.request({
url: 'https://rally1.rallydev.com/slm/webservice/v2.0/project/'+this.projectObjectID[1]+'/projectusers?fetch=true&start=1&pagesize=2000',
method: 'GET',
async: false,
headers:
{
'Content-Type': 'application/json'
},
success: function (response) {
console.log("entered the response:",response);
var jsonData = Ext.decode(response.responseText);
console.log("jsonData:",jsonData);
var blankdata = '';
var resultMessage = jsonData.QueryResult.Results;
console.log("entered the response:",resultMessage.length);
this.CurrentLength = resultMessage.length;
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:resultMessage
});
this.pendingProjects = resultMessage.length
console.log("this testcase store:",resultMessage);
_.each(resultMessage, function (data) {
var objID = data.ObjectID;
var column1 = data.Permission;
console.log("this result message:",column1);
if(userObjID[1]==objID) {
console.log("obj id 1 is:",objID);
console.log("User Reference 2:",userObjID[1]);
if (data.Permission != 'Editor') {
deferred.resolve(this.testCaseStore);
}else{
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:blankdata
});
deferred.resolve(this.testCaseStore);
}
}
},this)
},
failure: function (response) {
deferred.reject(response.status);
Ext.Msg.alert('Status', 'Request Failed.');
}
});
return deferred;
},
The main issue comes from your Ajax request which is using
async:false
This is blocking the javascript (unique) thread.
Consider removing it if possible. Note that there is no guarantee XMLHttpRequest synchronous requests will be supported in the future.
You'll also have to add in your success and failure callbacks:
that.setLoading(false);

I need to connect my front-end Javascript code to my sever-side NodeJS code. How do I do this?

We are very new to programming and have a simple question. We are developing a very simple Google search app that searches strings on Google using client-server communication. We have a simple subset of Javascript here:
var firstName = some_string
var lastName = some_string
var googleSearch = firstName + lastName;
googleSearch = JSON.stringify(googleSearch);
We need to link this code to our NodeJS code to do the actual searching.
var google = require('google');
google.resultsPerPage = 25;
var nextCounter = 0;
google(googleSearch, function(err,res) { // Note googleSearch is from
// the frontend Javascript code
// that we want to pull the data from.
if (err console.error(err)
var link = res.links[0];
console.log(link.href);
var myLink = link.href;
})
We want to take the data from the googleSearch variable from our front-end code and utilize it in our server-side code. Then we want to display the data from myLink , which is in our server-side code, back into our front-end code.
What you need to do is make an Ajax request from your front end to your server.
If you use jquery, you can do something like this
$.ajax({
url: YOUR_SERVER_URL+"/getData",
data: {
"google_search": googleSearch,
},
method: "GET",
//use data type json if your server returns json
dataType: "json",
success: function(result) {
console.log("data fetched Successfully");
//result is the data your server returned.
console.log(result);
},
error: function() {
console.log("Something went wrong, data could not be fetched");
}
});
On your server side if you are using Express with Node,
you can return JSON by doing something like this:
var app = express();
app.get('/getData', function(req, res, next) {
var google = require('google');
google.resultsPerPage = 25;
var nextCounter = 0;
//getting query data that you passed from front end
var googleSearch = req.query.google_search;
google(googleSearch, function(err, res) {
if (err console.error(err) var link = res.links[0]; console.log(link.href);
var myLink = link.href;
})
//sending json data as response
res.json(myLink);
});
If you are using localhost, then your server url will be something like "https://localhost:5000".

AjAX post request trouble redirecting the page

I'm trying to redirect to a different webpage on the success of an AJAX post request with express, but I can't figure it out.
I've tried using res.redirect() on the server side, and window.location=url and location.href=url and location.replace(url) on the client side, but none of these are working for me.
Here's my jQuery ajax request:
function addContact(){
var contactName = $('#name').val();
var email = $('#email').val();
var newContact = {name: contactName, email: email};
$.post('/contacts/add', newContact)
.success(function(data){
location.href = data.redirect;
})
}
And here's my server code:
router.post('/add', function(req, res, next){
fs.readFile('./contacts.json', function(err, data){
if (err) return res.status(400).send(err);
var contactArr = JSON.parse(data);
var newContact = req.body;
contactArr.push(newContact);
fs.writeFile('./contacts.json', JSON.stringify(contactArr), function(err){
if (err) return res.status(400).send(err);
res.redirect('/');
});
});
});
Any help would be appreciated!
The server code needs to send the new URL, rather than a redirect, and the client code then uses that URL to redirect. So:
server code:
router.post('/add', function(req, res, next){
fs.readFile('./contacts.json', function(err, data){
if (err) return res.status(400).send(err);
var contactArr = JSON.parse(data);
var newContact = req.body;
contactArr.push(newContact);
fs.writeFile('./contacts.json', JSON.stringify(contactArr), function(err){
if (err) return res.status(400).send(err);
res.json({"redirect":"http:www.google.com"});//replace this with your redirect url
});
});
});
and client code:
function addContact(){
var contactName = $('#name').val();
var email = $('#email').val();
var newContact = {name: contactName, email: email};
$.post('/contacts/add', newContact)
.success(function(data){
window.location.href = data.redirect;
})
}
should do it.

how to extract URL parameter from POST request in nodejs and expressjs

REQUEST URL http://localhost:9090/rest-api/fetchDetailedProductInfo?prodId=1&tempId=123
fetchDetailedProductInfo: function (prodId) {
var self = this;
var URL = 'http://localhost:9090/rest-api/fetchDetailedProductInfo'
$.ajax({
url: URL,
dataType: 'json',
contentType:'json',
type:'GET',
data: {
'prodId':prodId,
'tempId':123
},
success:function(responce) {
self.renderUI(responce.json);
},
error: function (err) {
console.log('ERROR',err)
}
});
},
# SERVER SIDE
router.get('/rest-api/fetchDetailedProductInfo', function (req, res) {
var prodId = req.param('prodId');
var tempId = req.param('tempId');
res.send(prodId + '----' + tempId);
}
I think you confused with req.params and req.query. Here is link to another question
Use req.query
var prodId = req.query.prodId;
var tempId = req.query.tempId;
Please see this

Node.js modified AJAX insertion to MongoDB

I am succesfully posting an AJAX insert in my MondoDB database.
The user is supposed to fill in 3 fields,
Full Name
Email
Phone
What I would like to do is:
generate a random number in server-side and save it as a 4th field in my MongoDB.
Also I would like to post it as a response back to the user.
Here is my users.js file (server-side)
* POST to adduser.
*/
router.post('/adduser', function(req, res) {
var db = req.db;
var codeResponse = generateCode();
db.collection('userlist').insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '',code: codeResponse } : { msg: err }
);
});
});
function generateCode(){
var code = Math.random() *1000000;
code = Math.floor(code);
return code;
}
And this is my AJAX call(client-side)
var newUser = {
'id2': id2,
'fullname': $('#addUser fieldset input#inputUserFullname').val(),
'email': $('#addUser fieldset input#inputUserEmail').val(),
'phone': $('#addUser fieldset input#inputUserPhone').val(),
}
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
console.log(response);
}
else {
alert('Error: ' + response.msg);
}
});
Easy enough, add it to your object before insert and post back the object:
router.post('/adduser', function(req, res) {
var db = req.db;
var document = req.body;
var codeResponse = generateCode();
document.code = codeResponse;
db.collection('userlist').insert(document, function(err, result){
if (err) //do something
return;
else
res.send(document);
});
});

Resources