Tuesday, 16 May 2017

Ajaxcall doesn't send inputs (MongoDB Database)

I'm currently working on a Project with Phaser.js and I'm running into a problem when working on my Highscore. When the game goes into the last state called "end", it opens a Bootstrap Modal Dialog with the achieved Score and an input where you can put your name. When I hit "send" it should put the value of both inputs into the ajaxcall and send it to "/". But the inputs end up being empty, a console.log(input1 + " and " + input2); brings out nothing but the "and". I have not a clue what the problem could be since I'm not getting ANY errors. Any help is appreciated.

index.ejs:

<div class="col-md-12" id="popup">
    <!-- Modal -->
    <div class="modal fade" id="myModal" role="dialog">
      <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Modal Header</h4>
          </div>
          <div class="modal-body">
            <label for="score">Your Score:</label>
            <input value="" class="form-control" id="score"><br>
            <label for="name">Your Name:</label>
            <input value="" class="form-control" id="name"  placeholder="Choose a name for the leaderboards...">
          </div>
          <div class="modal-footer">
            <button type="button" id="send" class="btn btn-success">Send</button>
            <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
          </div>
        </div>

      </div>
    </div>
  </div>

ajaxcalls.js

var input1 = $('#name').val();
var input2 = $('#score').val();



$('#send').click(function(){
    console.log(input1 + 'x' + input2);
    $.ajax({
        method: "POST",
        url: "/",
        data: {
            Name: input1,
            HScore: input2
        },
        success: function(data){
            console.log('success');
            $('#myModal').modal('hide');
        }
    });
});

index.js

router.post('/', function (req, res) {
  var Name = req.body.Name;
  var HScore = req.body.HScore;

  mongoose.model('hs').create(
      {
        player: Name,
        score: HScore
      },
      function (err,player) {
        if(err){
          res.send('Errortext!');
        }
        console.log('POST creating new Player: ' + player);
        res.redirect('/');
      });
});

mongo.js

var mongoose = require('mongoose');

var highScore = new mongoose.Schema({
    player: String,
    score: Number
});

mongoose.model('hs', highScore);



via rekalar

No comments:

Post a Comment