The purpose of this example is to demonstrate how you can interact with the server through ajax requests.
The server chooses a number and the user needs to guess the number.
Whenever the user presses on the Guess button a request is sent to the Guess handler:
The request is sent with this JavaScript / JQuery code (the code is in index.html file):
The $.post method sends a post request to 'guess' with the number parameter. The callback function is raised after the server response. 'data' holds the server response.
There is another button which tells the server to reset the number:
The project is attached.
As you can see in the above screenshot I'm using FireBug to monitor the requests and to debug the JavaScript code. I highly recommend you to work with such tool.
Note that this example is not suited for multiple users. All users will need to guess the same number and if a user presses on the reset button then the number will be changed for all users. A "user session" is missing here. The session can be managed with cookies.
The server chooses a number and the user needs to guess the number.
Whenever the user presses on the Guess button a request is sent to the Guess handler:
B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)
Dim n As String = req.GetParameter("number")
If IsNumber(n) = False Then
resp.Write("Please enter a valid number.")
Else
If n > Main.myNumber Then
resp.Write("My number is smaller.")
Else If n < Main.myNumber Then
resp.Write("My number is larger.")
Else
resp.Write("Well done!!!")
End If
End If
End Sub
The request is sent with this JavaScript / JQuery code (the code is in index.html file):
B4X:
$("#btnGuess").click(function(){
$.post("guess", "number=" + txtNumber.value,
function(data) {
$("#result").html(data);
$("#txtNumber").focus();
$("#txtNumber").select();
}
);
});
There is another button which tells the server to reset the number:
B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)
Main.myNumber = Rnd(1, 101)
End Sub
B4X:
$("#btnReset").click(function(){
$.post("reset");
});
The project is attached.
As you can see in the above screenshot I'm using FireBug to monitor the requests and to debug the JavaScript code. I highly recommend you to work with such tool.
Note that this example is not suited for multiple users. All users will need to guess the same number and if a user presses on the reset button then the number will be changed for all users. A "user session" is missing here. The session can be managed with cookies.