0

I've basically been trying to make a simple game where the user can submit their high-score to a Node.js server. I'm just trying to do something very simple but can't seem to find much to help me online!

At the moment I've got the main page to connect and respond to the server using AJAX.

Here's the HTML:

<div id="test"></div> 
<h3>Upload your high-score:</h3>
Your score: <input type="text" name="yourScore">
<button id="SubmitBtn" type="submit">Submit</button>

Here's the JavaScript which triggers when the "Submit" button is clicked and appends the "test" div when successfully connected (Just to show it responds):

<script> 
$(document).ready(function() {
$('#SubmitBtn').click(function (event) {
    $.ajax({ 
        url: 'http://localhost', 
        dataType: "jsonp", 
        jsonpCallback: "_testcb", 
        cache: false, 
        timeout: 5000, 
        success: function(data) { 
            $("#test").append(data); 
        }, 
        error: function(jqXHR, textStatus, errorThrown) { 
            alert('Error connecting to the Node.js server... ' + textStatus + " " + errorThrown); 
        } 
    }); 
});

});

And here's my Node.js at the moment where it runs and responds:

var http = require('http'); 
console.log('Game server running...'); 
http.createServer(function (req, res) { 
console.log('Submit button has been clicked.'); 
res.writeHead(200, {'Content-Type': 'text/plain'}); 
res.end('_testcb(\'{"message": "Welcome! Node.js Responding!"}\')'); 
}).listen(80); 

So yeah, if anyone knows how I can get my Node.js server to read the data in the "yourScore" text field and when the "SubmitBtn" button has been clicked to send the data to the server, I would be most thankful!

2 Answers 2

1

First

You are not sending any data with your AJAX request.

Possible solution (it is better if you get score input element using an ID or serializing the form element):

$.ajax({ 
    url: 'http://localhost',
    data: { score : $("input[name='score']").val() },
    dataType: "jsonp", 
    jsonpCallback: "_testcb", 
    cache: false, 
    timeout: 5000, 
    success: function(data) { 
        $("#test").append(data); 
    }, 
    error: function(jqXHR, textStatus, errorThrown) { 
        alert('Error connecting to the Node.js server... ' + textStatus + " " + errorThrown); 
    } 
});

Second

Inside your NodeJS request handler you can get the sent data using the request object.

Possible solution:

var http = require('http'); 
http.createServer(function (req, res) {
      var score = req.body.score;
      console.log(score);
      //do whatever you want
      res.writeHead(200, {'Content-Type': 'text/plain'}); 
      res.end('_testcb(\'{"message": "Welcome! Node.js Responding!"}\')'); 
}).listen(80); 
Sign up to request clarification or add additional context in comments.

7 Comments

Hi, thanks for your answer, however I get an issue when running the Node.js server with the added code you suggested, here's the error: ReferenceError: request is not defined at Object.<anonymous> (C:\Users\Mike\SnakeServer.js:2:13) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:901:3 Any idea how to solve this? Thanks
@Mike it had a mistake. change request to req. See my answer again.
Hi thanks for the reply, but when I change it to "var score = req.body.score;" it says "Cannot read property 'score' of undefined", even though both the "name" and "ID" attributes of the input text field are called "score".. Any ideas? Thanks
if you are inside this scope http.createServer(function (req, res) {}); req.body must be defined. Check your code to see if you are missing something
are you using connect's bodyParser middleware? You need it to have request.body object available. If not you need to parse data yourself using req.on('data', function(chunk) { } );
|
0

You need to send a POST to the server, check out this simple example

in your script:

$.ajax({
    type: "POST",
    data: {
        yourScore: $('input[name="yourScore"]').val()
    }, 
    //other parameters

and in your server

http.createServer(
   //...
   if (req.method == 'POST'){
      console.log(req.body.yourScore)

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.