Cannot call method 'send' of undefined(response is undefined) in express js

Problem

I have tried to pass a variable from my index.html to the database(maildata.js) through app.js(server) and get the corresponding data I am able to get the data from the database but couldnt send that back to the server(app.js)

app.js

var express = require('express');
var maildata= require('./maildata');
var app = express();
app.configure(function(){
app.use(express.bodyParser());
});

app.get('/', function(request, response){
response.sendfile(__dirname + '/mailbox.html');
});
app.post('/mailboxpost',function(request, response) {
    var input=request.query.search;     
var result=maildata.getMailData(input); 
response.send(result);
response.end();
});

app.listen(8888);
console.log('Server is running on port 8888'); 

maildata.js

    exports.getMailData=function(data,response) {

    var stop_name= data;    
    connection.query("select stop_name,stop_comment from stoplist where stop_name=        '"+stop_name+"' limit 1",function(err, rows) {    

    if (err) {
        console.log('error in fetching  ' + err);   
    }
    else{    
        var jsonString1= JSON.stringify(rows);
    connection.query("select mailbox_sequence_no from stoplist where stop_name= '"+stop_name+"'",function(err, rows) {  

    if (err) {
        console.log('error in fetching  ' + err);   
    }
    else{    
        var jsonString2 = JSON.stringify(rows);
         connection.query("select party_head from stoplist where stop_name= '"+stop_name+"'", function(err, rows) { 
     if (err) {
        console.log('error in fetching  ' + err);   
     }
     else{  
        var jsonString3 = JSON.stringify(rows);
        var result=jsonString1+'/'+jsonString2+'/'+jsonString3;  
        response.send(result);    
      }    
    });
   }    
  });    
 }    
});    
}

Thanks in Advance

Problem courtesy of: Dhivi

Solution

I have used asynchronous callback method in my app.js.

I got the result

var result=maildata.getMailData(input,response,function(data){
response.send(data);
response.end();
});

Thanks all

Solution courtesy of: Dhivi

Discussion

How about sending response along when you call the function?

var result=maildata.getMailData(input); // something missing here

Discussion courtesy of: npup

Your getMailData function expects two arguments:

exports.getMailData=function(data,response) { ... }

but you give it only one:

var result=maildata.getMailData(input); 

Which makes the value of the response argument undefined.

Here is what you should do:

app.post('/mailboxpost',function(request, response) {
  var input=request.query.search;     
  maildata.getMailData(input, response); 
});

and let maildata.getMailData handle the response sending, as you did in response.send(result);

Discussion courtesy of: Paul Mougel

This recipe can be found in it's original form on Stack Over Flow.