I'm new to web development and I'm learning to use CherryPy as the backend for the web service. I was following this tutorial to send requests from client to server (I wonder if there is another way?). The server which is written in python using cherrypy then process the requests and should return a value(variable) to the client (html and js), this is where I'm stuck. How could the server return the variable back to the client? I'm quite confused and I don't see any example or tutorial explaining this.
For example, my client side has this code (saved as index.html):
<!DOCTYPE html>
<html>
<head></head>
<body>
<form method="get" action="generate">
<input type="text" value="8" name="length" />
<button type="submit">Give it now!</button>
</form>
</body>
</html>
my server side is:
import random
import string
import cherrypy
class StringGenerator(object):
@cherrypy.expose
def index(self):
return open("index.html")
@cherrypy.expose
def generate(self, length=8):
ranNum = ''.join(random.sample(string.hexdigits, int(length)))
return ranNum
if __name__ == '__main__':
cherrypy.quickstart(StringGenerator())
so when I submit the form, generate() function in the server side will be called and it will take the value I submitted as the parameter. But I don't want the web page to just show the return value as it is now, I want the server to send the return value back to the client (html and js) so that I can use it in my client side code. How could I do it?
Ok, here's what's up... when you use a form there is no need for js. The form just posts, or sends data, to the cherrypy handler. What you'll want to do is something like this with either js or jquery...
<form method="get" action="generate();">
</form>
<script>function generate() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","generate",true);
xmlhttp.send();
// your response will be here.
xmlDoc=xmlhttp.responseXML;
};</script>
Let me know if this doesn't make sense.
Andrew