4

I want to send form data to node.js server using Ajax and I am fallowing the below approach to send data.

I am not getting how receive it in node.js server program I am not using express framework for node.js

client.HTML

<script>
 function myFunction() {
   var region = document.getElementById("region").value;
   var os = document.getElementById("os").value;
   var data = {};
   data.region = region;
   data.os = os;
   $.ajax({
     type: 'post',
     datatype: 'jsonp',
     data: JSON.stringify(data),
     contentType: 'application/json',
     url: 'http://127.0.0.1:8083/', //node.js server is running
     success: function(data) {
       alert("success");

     }
   });

</script>
<form>
<select id="region" name="region" class="region"></select>
<select id="os" name="os" class="os"></select>  
<input type="button" value="search" class="fil_search" onclick="myFunction()"/>
</form>

server.js

var http = require('http');
var fs = require('fs');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var express = require('express');
var bodyParser = require('body-parser');
var app     = express();
var result1=[];
var result2=[];
var result3=[];
var result4=[];
var result5=[];
var result6=[];
var result7=[];
var i=0;
var region;
var os;
app.use(bodyParser.urlencoded({ extended: true })); 

MongoClient.connect("mongodb://192.168.1.22:27017/test", function(err, db) {

if(err) { return console.dir(err); }
else {
app.get('/',function(req, res) {

var url_parts = url.parse(req.url, true);
var url_parsed = url.parse(req.url, true);

"i want data here from ajax to perform"

console.log("connected");


var instance = db.collection('instance');
var region = db.collection('region');

region.findOne(({$and: [{"region_name": region_name},{"os_type": os}]}), function(err, result){
if(err){    
throw(err);
}
else{
console.log(region);
var newr = result.inst_name;

instance.find({ "inst_id": { "$in": newr } }).toArray(function(err, resultn){
if(err){
throw(err);
}
else{       
    var len=resultn.length;

    console.log(resultn);
    console.log(len);

    for(var i=0;i<len;i++)
    {
        result1[i]=resultn[i].inst_type;
        result2[i]=resultn[i].vcpu;
        result3[i]=resultn[i].memory_gib;
        result4[i]=resultn[i].storage;
        result5[i]=resultn[i].phy_processor;
        result6[i]=resultn[i].clock_spd;
        result7[i]=resultn[i].netwk_pef;            
    }
    var wstream = fs.createWriteStream('myOutput.txt');
    wstream.write(result1.toString()+"~"+result2.toString());       
    //var str = "Hi man"
    res.writeHead(200, {'Content-Type':'text/html'});
    //res.end(url_parsed.query.callback+'("'+resultn.toString()+'")'); 
    res.end(url_parsed.query.callback+'("'+result1.toString()+"~"+result2.toString()+"~"
    +result3.toString()+"~"+result4.toString()+"~"+result5.toString()+"~"+result6.toString()
    +"~"+result7.toString()+'")');      
}
});
}
}); 
}).listen(process.env.PORT || 8083);

}
});

I am not getting how to receive data in node.js server program and after receiving data I want process on that data and send back processed data to same HTML page.

5
  • Is this your actual code? You have in both the server and the client code a syntax error which will prevent the code from running at all. You say I am not using express, but app.use(bodyParser.urlencoded({ extended: true })); looks like epress, so you should tell which framework you use instead of express. Commented Oct 6, 2015 at 5:35
  • it is actual code but i have pasted imp part of my code where i want to send and recieve data from HTML form. just i want a solution how to get the data in node.js server? Commented Oct 6, 2015 at 5:44
  • Ok but you have a syntax error here '("' + result1.toString()'"); so your server code wont run at all. And you have a missing } at the end of your myFunction function on the client side, so this code won't run either. And you still didn't tell what framework you use instead of express. What is app if not an express application? Commented Oct 6, 2015 at 5:45
  • @t.niese pls check my progrm once again i have uploaded full working program and pls give me solution. how to receive a data in node.js server and i want query it on and again send back data to that HTML page Commented Oct 6, 2015 at 9:29
  • please somebody help me to get resolve this.thanks in advance Commented Oct 6, 2015 at 12:22

1 Answer 1

2

If you have app.use(bodyParser.urlencoded({ extended: true })); in your server.js file then using bodyParser you can retrieve data from ajax as given below:

app.post('/', function(req, res) { //your ajax should also post to url: '/'
    var region = req.body.region,
    os = req.body.os;
    // ...
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.