CuriousFellow CuriousFellow - 6 months ago 22
Javascript Question

AJAX call and getting return data in Node

I'm wanting to make an ajax call from the client to the backend. I get a successful call from the success function, however, I can't understand how I get data from the server to return from the client.

currently my error trying to use res.send is:

Error: Can't set headers after they are sent.


AJAX



function getProfessorResults() {
var textData = $('#inputsm').val();

var data = {user:"gopal@gmail.com"};
$.ajax({
url: 'http://localhost:3000',
data: { theme: "somevalue", snippet: { name: "somename", content: "somevalue" } },
method: 'POST',
async: false,
cache: false,
timeout: 5000,
contentType: "application/json",
success: function(data) {
console.log("success");
},
complete: function(data) {
console.log("completed");
},
error: function(jqXHR, textStatus, errorThrown) {

alert('Error connecting to the Node.js server... ' + textStatus + " " + errorThrown);
}
});
}


JS Backend



exports.home = function(req, res) {


function passList(profArray, callback) {
setTimeout(function () {
callback(profArray);
}, 1000);
}


function getProfs(teacher_name, successCallback) {

google.resultsPerPage = 10
var nextCounter = 0

google(teacher_name, function (err, res){
if (err) console.error(err)
var teacher_results = []; //Hold all the teachers returned from the function
for (var i = 0; i < res.links.length; ++i) {
var link = res.links[i];
if (!link.title.includes('Add') || !link.title.includes('RATINGS') || !link.title.includes("Hint")) {

teacher_results.push(link.title);

}//End if for comparisons ||
} //End For
successCallback(teacher_results);
}); //End google function
teacher_results = ['tester1', 'tester2'];
successCallback(teacher_results);
} //End searchForProfessor


getProfs(teacher_name, function(data) {
prof_list = data;
console.log(prof_list);
return true;
});


if (req.method == 'POST'){
console.log("true");
// dataReceived = JSON.parse(req);
// console.log(dataReceived);
var obj = {
tid: 'ryan'
};

res.send(JSON.stringify(obj));
}



res.render('home', {
profs: prof_list,
dataStuff : dataReceived
});
};

Answer

In the backend, you should have some route where your AJAX call lands. In there, you can invoke send on your response.

In node.js/express, this would look something like

app.get('/ajaxURL', function (req, res) {
  res.send('I want this string to return to the client');
});

To access the data from the frontend, access it in your AJAX callback:

$.ajax({url: '/ajaxURL'}).done(function (data) {
    console.log(data);
});