Basic Ajax send/receive with node.js
Your request should be to the server, NOT the server.js file which instantiates it. So, the request should look something like this:
xmlhttp.open("GET","http://localhost:8001/", true);
Also, you are trying to serve the front-end (index.html) AND serve AJAX requests at the same URI. To accomplish this, you are going to have to introduce logic to your server.js that will differentiate between your AJAX requests and a normal http access request. To do this, you'll want to either introduce GET/POST data (i.e. callhttp://localhost:8001/?getstring=true
) or use a different path for your AJAX requests (i.e. callhttp://localhost:8001/getstring
). On the server end then, you'll need to examine the request object to determine what to write on the response. For the latter option, you need to use the 'url' module to parse the request.You are correctly calling
listen()
but incorrectly writing the response. First of all, if you wish to serve index.html when navigating to http://localhost:8001/, you need to write the contents of the file to the response usingresponse.write()
orresponse.end()
. First, you need to includefs=require('fs')
to get access to the filesystem. Then, you need to actually serve the file.XMLHttpRequest needs a callback function specified if you use it asynchronously (third parameter = true, as you have done) AND want to do something with the response. The way you have it now,
string
will beundefined
(or perhapsnull
), because that line will execute before the AJAX request is complete (i.e. the responseText is still empty). If you use it synchronously (third parameter = false), you can write inline code as you have done. This is not recommended as it locks the browser during the request. Asynchronous operation is usually used with the onreadystatechange function, which can handle the response once it is complete. You need to learn the basics of XMLHttpRequest. Start here.
server.js:
var http = require('http'),
fs = require('fs'),
url = require('url'),
choices = ["hello world", "goodbye world"];
http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
if(path=="/getstring"){
console.log("request recieved");
var string = choices[Math.floor(Math.random()*choices.length)];
console.log("string '" + string + "' chosen");
response.writeHead(200, {"Content-Type": "text/plain"});
response.end(string);
console.log("string sent");
}else{
fs.readFile('./index.html', function(err, file) {
if(err) {
// write an error response or nothing here
return;
}
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(file, "utf-8");
});
}
}).listen(8001);
console.log("server initialized");
frontend (part of index.html):function newGame()
{
guessCnt=0;
guess="";
server();
displayHash();
displayGuessStr();
displayGuessCnt();
}
function server()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8001/getstring", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
string=xmlhttp.responseText;
}
}
xmlhttp.send();
}
You will need to be comfortable with AJAX. Use the mozilla learning center to learn about XMLHttpRequest. After you can use the basic XHR object, you will most likely want to use a good AJAX library instead of manually writing cross-browser AJAX requests (for example, in IE you'll need to use an ActiveXObject instead of XHR). The AJAX in jQuery is excellent, but if you don't need everything else jQuery offers, find a good AJAX library here: http://microjs.com/. You will also need to get comfy with the node.js docs, found here. Search http://google.com for some good node.js server and static file server tutorials. http://nodetuts.com is a good place to start. UPDATE: I have changed response.sendHeader()
to the new response.writeHead()
in the code above !!!
How to send response to ajax post request in express node.js?[answered]
Please use it as following in your html file. Should solve your problem
<body>
<form method="post" id="cityform">
<button id="submitBtn" type="submit">Search Weather</button>
</form>
</body>
<script>
$("#cityform").submit(function(e) {
e.preventDefault();
$.ajax({
url: "https://localhost:8443/getCity",
type: "POST",
data: {
'city': 'pune',
'country': 'India',
},
success: function(data){
console.log(data);
}
});
});
</script>
Post request should look like this, I'm calling some function as findCity, you don't have to use it. app.post("/getCity", (req, res) => {
var cityname= req.body.city;
var country= req.body.country;
city.findCity(cityname, country).then((cityID) => {
res.status(200).send({ cityID: '123' });
}).catch((e) => {
res.status(400).send(e);
});
});
Node.js send data to backend with AJAX
Note: This was written before the question was updated with the code so the field names and port numbers that I used here as examples may need to be updated with the correct values.
Client-side code - example with jQuery:
$.post('/email', { address: 'xxx@example.com' });
(this can take optional callbacks and it returns a promise that can be used to add a success/error handler)Server-side code - example with Express:
const express = require('express');
const bodyParser = require('body-parser');
const dir = path.join(__dirname, 'public');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/email', (req, res) => {
// you have address available in req.body:
console.log(req.body.address);
// always send a response:
res.json({ ok: true });
});
app.use(express.static(dir));
app.listen(4443, () => console.log('Listening on http://localhost:4443/'));
This assumes that your static files (HTML, client-side JavaScript, CSS) are in the public
directory relative to your server.js
file.See this for background on the JSON/form-encoding issue:
- Which method is prefer when building API
- How to serve an image using nodejs
How to pass the ajax get request data to nodejs GET route?
jQuery's .ajax()
method sends the data
property as a query string for GET requests, so in your Express code you have to retrieve that data from req.query
instead of from req.body
.
passing node js variable to html using ajax
try changing arguments in python results callback:
PythonShell.PythonShell.run('dbPrac.py', options, function(err, pythonRes) {
if(err) throw err;
console.log('pythonRes[0]: ', pythonRes[0]);
//res.render(__dirname + '/data.html');
res.send(pythonRes[0]);
How to read the data from node js post ajax request?
Use this npm package - https://www.npmjs.com/package/body-parser
and so server site parse like this:
request.body.{some field name}
AJAX and Node JS/Express post not sending or receiving data
It's good that you are using body-parser, but have you defined a JSON parser in your app?
You didn't paste all of your code so add this if you don't already have it:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser --> This is probably what you are missing
var jsonParser = bodyParser.json()
// POST /api/users gets JSON bodies --> Note how we use a jsonParser in our app.post call
app.post('/send', jsonParser, function (req, res) {
console.log(req.body);
console.log('Send button clicked');
})
Also, instead of constructing your data manually, just create an object and send it (remember JSON is short for - Java Script Object Notation)var myData = {};
myData.title = this.MessageInput.value;
Then in your Ajax code, just use myData
:$.ajax({
type: 'POST',
data: myData,
url: 'http://localhost:3000/send'
});
Note: most of this example is taken straight from the body-parser Github Page, it has plenty of well documented examples so if you're not sure how to use the module, check it out receive json content from node.js into html using AJAX
This is a "trick" from HTML... Any button in a <form>
will act like a submit button (event without type="submit"
attribute). You need to add a event.preventDefault()
in your click handler. In other words change
document.getElementById('get').onclick = function(){
bydocument.getElementById('get').onclick = function(event){
event.preventDefault();
// code continue here
Related Topics
Initializing Select with Angularjs and Ng-Repeat
Escaping Backslash in String - JavaScript
How to Get the Hue of a #Xxxxxx Colour
Localstorage Object Is Undefined in Ie
How to Export Socket.Io into Other Modules in Nodejs
Why Escape_JavaScript Before Rendering a Partial
Using the Haversine Formula in JavaScript
Difference Between Obtrusive and Unobtrusive JavaScript
Understanding Xmlhttprequest Over Cors (Responsetext)
JavaScript Get Object Key Name
Why Does JavaScript Getyear() Return 108
How to Send Email by Using JavaScript or Jquery
What's "This" in JavaScript Onclick
Regular Expression for Url Validation (In JavaScript)
Unexpected Token Illegal in Webkit
How to Auto-Slide the Window Out from Behind Keyboard When Textinput Has Focus