javascript - wrong ajax response on nodejs -
i playing ajax on nodejs, can better understand node.
the form (client-side)
<form id="fruitform" method="post" action="/"> <div class="table"> <div class="row"> <div class="cell label">bananas:</div> <div class="cell"><input name="bananas" value="2"/></div> </div> <div class="row"> <div class="cell label">apples:</div> <div class="cell"><input name="apples" value="5"/></div> </div> <div class="row"> <div class="cell label">cherries:</div> <div class="cell"><input name="cherries" value="20"/></div> </div> <div class="row"> <div class="cell label">total:</div> <div id="results" class="cell">0 items</div> </div> </div> <button id="submit" type="button">submit form</button> </form> <div id="results"></div> <script type="text/javascript"> document.getelementbyid("submit").onclick = handlebuttonpress; //var httprequest; function handlebuttonpress(e) { e.preventdefault(); var formdata = ""; var inputelements = document.getelementsbytagname("input"); (var = 0; < inputelements.length; i++) { formdata += inputelements[i].name + "=" + inputelements[i].value + "&"; } formdata = formdata.slice(0, -1); var hr = new xmlhttprequest(); hr.open("post", "/", true); hr.setrequestheader("content-type", "application/x-www-form-urlencoded"); hr.onreadystatechange = function() { if(hr.readystate == 4 && hr.status == 200) { document.getelementbyid("results").innerhtml = hr.responsetext; } } hr.send("formdata="+encodeuricomponent(formdata)); } </script>
just form fields, each field has number. js creates json structure. formdata
contains bananas=2&apples=5&cherries=20
.
now, minimalistic server far. works, how can access data came form via request
?
also, in client side, dont rrr
in "results" div
, getting whole html
of page again , form again. why that? dont it.
i want understand node , please dont suggest me express, or other modules. want know why simple code wont work
thanks in advance
server
//requires var http = require ('http'); var fs = require ('fs'); var path = require ('path'); var mime = require ('mime'); //set server var server = http.createserver(function (request, response){ var filepath = false; if (request.url == '/'){ filepath='public/index.html';//default static file } else{ filepath='public'+request.url;//set relative file path } var abspath = './'+filepath; servestatic(request, response, cache, abspath); }); server.listen(4000, function(){ console.log("chatrooms server on port 4000"); } ); //read file function servestatic(request, response,cache, abspath){ fs.readfile(abspath, function(err, data){ sendfile(request, response, abspath, data); }) } //serve file function sendfile(request, response, filepath, filecontents){ response.writehead( 200,{"content-type":mime.lookup(path.basename(filepath))} ); response.end(filecontents); formpro(request, response);//now done sending, lets check form } function formpro(request, response){ if (request.method=="post"){ var rrr="rrr";//insted of rrr, see form again response.writehead(200,{"content-type":"text/plain"}); response.write(rrr); response.end(); } }
edit guess response
gets overwritten. code works but, response
contains rrr, since httpserver responses last, response
transmits page again, @ end. there way independently listen form events, without using httpserver?
i think following code fixes lot of problems. credits , cudos orangedog's answer here, ampersand's answer here , book "node.js in action" mike cantelon, marc harter, t.j. holowaychuk , nathan rajlich, ©2014 manning publications, chapters 4.3 - 4.4
<html> <head> <title>chatrooms</title> </head> <body> <form id="fruitform" method="post" action="/"> <div class="table"> <div class="row"> <div class="cell label">bananas:</div> <div class="cell"><input name="bananas" value="2"/></div> </div> <div class="row"> <div class="cell label">apples:</div> <div class="cell"><input name="apples" value="5"/></div> </div> <div class="row"> <div class="cell label">cherries:</div> <div class="cell"><input name="cherries" value="20"/></div> </div> <div class="row"> <div class="cell label">total:</div> <div id="results" class="cell">0 items</div> </div> </div> <button id="submit" type="button">submit form</button> </form> <div id="results"></div> <div id="de"></div> </body> </html> <script type="text/javascript"> document.getelementbyid("submit").onclick = handlebuttonpress; function handlebuttonpress(e) { e.preventdefault(); var formdata = ""; var inputelements = document.getelementsbytagname("input"); (var = 0; < inputelements.length; i++) { formdata += inputelements[i].name + "=" + inputelements[i].value + "&"; } formdata = formdata.slice(0, -1); document.getelementbyid("de").innerhtml = formdata; var hr = new xmlhttprequest(); hr.open("post", "/formhandler", true); hr.setrequestheader("content-type", "application/x-www-form-urlencoded"); hr.onreadystatechange = function() { if(hr.readystate == 4 && hr.status == 200) { document.getelementbyid("results").innerhtml = " "; document.getelementbyid("results").innerhtml = hr.responsetext; } } hr.send(formdata); } </script>
server side
//dependencies var http = require ('http'); var fs = require ('fs'); var path = require ('path'); var mime = require ('mime'); var qs = require('querystring'); //this http server var server = http.createserver(function (request, response){ var filepath = false; if (request.url == '/'){ filepath='public/index.html';//default static file sendthis(response, filepath); return; } if (request.url == '/formhandler'){ var body=''; if (request.method=="post"){ request.on('data', function (data) { body += data; }); request.on('end', function () { var aa = qs.parse(body); var c= aa['apples']; response.writehead(200,{ 'content-type': 'text/plain' }); response.end(c, "utf-8"); }); } return; } else{ filepath='public'+request.url+'.html';//set relative file path sendthis(response, filepath); return; } }); server.listen(4000, function(){ console.log("chatrooms server on port 4000"); } ); function sendthis(response, filepath){ var stream = fs.createreadstream(filepath); stream.pipe(response); stream.on('error', function(err){ if('enoent'==err.code){ response.statuscode = 404; response.end('not found'); } else{ response.statuscode = 500; response.end("internal server error"); } }) }
Comments
Post a Comment