Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

JQuery/NodeJS AJAX Response Help

js jquery nodejs

This topic has been archived. This means that you cannot reply to this topic.
No replies to this topic

#1 Poe

Poe

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 81 posts

Posted 27 January 2016 - 06:45 PM

I'm trying to implement AJAX using JQuery and Node.  But i'm running into problems pulling data from the node server when posting data using JQuery's $.ajax function.

 

When I use console.log in node I can tell the post data is being posted, but I cannot get back the proper response i'm looking for.

 

Frontend

<html>
 <head>
  <style>
   body,html {
	padding:0;
	margin:0;
   }
  </style>
  <script type="text/javascript" src="/head/jquery.min.js">
  </script>
  <script>
	$(document).ready(function() {
		
		$("#submitButton").click(function(event) {
			$.ajax({
				
				type: "POST",
				url: "/action",
				data: {'inputText': 'hello'},
				success: function(msg) {
						alert("Form Submitted: " + msg.responseText);
						console.log(msg);
						$("#result").html(msg);
					}
				
			});
		});
		
	});
  </script>
 </head>
 <body>
  <table border="0" width="100%">
	<tr>
	 <td style="background-color:#111;">&nbsp;</td>
	</tr>

	<tr>
	 <td height="100px;">&nbsp;</td>
	</tr>
	
	<tr>
	 <td style="background-color:#111;">&nbsp;</td>
	</tr>
	
	<tr>
	 <td>
	  <form id="inputForm" method="post">
	   <input type="text" id="textInput" name="textInput" /> <input type="button" value="Go!" id="submitButton" />
	  </form>
	  <div id="result"></div>

The Node Server

#!/usr/bin/node
var http = require("http");
var qs = require('querystring');
var func = require('./functions');
var server = http.createServer(function(req, res) {
	res.writeHead(200);
	//res.end("** Worl");
    if (req.method == 'POST') {
        var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) { 
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
            console.log(data);
        });
        req.on('end', function () {

            var POST = qs.parse(body);
            // use POST
			console.log(POST.textInput);
			res.end(POST['textInput']);
			console.log(POST);
        });
    }
});

console.log("Server running...");
server.listen(1500);

Here's the console running the server:

 

[dylan@localhost src]$ jobs/base-server.js
Server running...
<Buffer 69 6e 70 75 74 54 65 78 74 3d 68 65 6c 6c 6f>
undefined
{ inputText: 'hello' }

I get either nothing, or undefined back from the server

 

The server is bound to /action on my nginx instance.


Edited by Poe, 27 January 2016 - 06:46 PM.

"Portability is for those who can't write new programs" - Linus Torvalds