I've created a guess-the-number game using jQuery and PHP, and while it works fine when a number is entered (and also handles non-numbers well), when 0 is entered the Ajax call fails. As far as I can tell, when 0 is entered the variable $guess
sent to the server-side code isn't set properly, but I can't work out why - any ideas?
Form input:
<form id="guess" action="magicgubbins.php" method="get">
<p><input type="text" id="newguess" name="guess" value="" />
<input type="submit" value="Guess"></p>
</form>
jQuery:
<script type="text/javascript">
$(function() {
var magicno = Math.floor(Math.random()*11);
$('#guess').submit(function() {
var newguess = $('#newguess').attr('value');
if (!newguess) {
newguess = 'nonumber';
}
var form = $(this),
//formData = form.serialize(),
formData = {guess: newguess, magic: magicno},
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#magicbox');
//show waiting message
responseMsg.hide()
.addClass('response-waiting')
.text('Please wait...')
.fadeIn(200);
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success: function(data){
// parse returned data
var responseData = jQuery.parseJSON(data),
klass = '';
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
// show new response message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
if (responseMsg.hasClass('response-success')) {
$('#description').hide();
$('#magicbox').hide();
$('#status').text('You win!').show();
}
// timeout response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
});
},3000);
});
});
}
});
return false;
});
});
</script>
Server-side code:
<?php
$magic = htmlentities($_GET['magic']);
$guess = htmlentities($_GET['guess']);
if(empty($magic)){
$status = "error";
$message = "No magic number set!";
} else if (empty($guess)) {
$status = "error";
$message = "Take a guess!";
} else {
if(is_numeric($guess)) {
if($guess == $magic) {
$status = "success";
$message = "Correct! " . $magic . " is the magic number.";
} else {
if ($guess > $magic) {
$status = "error";
$message = "Wrong! " . $guess . " is too high.";
} else {
$status = "error";
$message = "Wrong! " . $guess . " is too low.";
}
}
} else {
$status = "error";
$message = "That's not a number!";
}
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>