Simple Python and Ajax Example How to Send Response with Python?

clifgray picture clifgray · Jul 24, 2013 · Viewed 18.2k times · Source

I am testing out some code with Python and Javascript trying to get an Ajax system set up. Basically I just want to input a word and have the python code send it back. Here is my html/javascript:

<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari/Chrome
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText);
        }
    }
    self.xmlHttpReq.send(getquerystring());
}

function getquerystring() {
    var form     = document.forms['f1'];
    var word = form.word.value;
    qstr = 'w=' + escape(word);  // NOTE: no '?' before querystring
    return qstr;
}

function updatepage(str){
    document.getElementById("result").innerHTML = str;
}
</script>
</head>

<body>

<form name="f1">
  <p>word: <input name="word" type="text">  
  <input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/ajaxtest")'></p>
  <div id="result"></div>
</form>

</body>

</html>

and here is my python:

class AjaxTest(BlogHandler):
    def get(self):
        user = self.get_user()       
        self.render('ajaxtest.html', user = user)
    def post(self):
        user = self.get_user()
        word = self.request.get('w')
        logging.info(word)
        return '<p>The secret word is' + word + '<p>'
        #having print instead of return didn't do anything

When I do logging the word shows up correctly and when I hardcode str in:

function updatepage(str){
    document.getElementById("result").innerHTML = str;
}

It displays that correctly but right now without hardcoding it shows nothing. How am I supposed to send the response? I am using webapp2 as my Python framework and Jinja2 as the templating engine, though I don't think that has much to do with it. Do I need to send the HTTP headers?

Answer

dm03514 picture dm03514 · Jul 24, 2013

If your problem is having difficulty returning a string from your post method, without rendering a template you can use the write method to accomplish that:

self.response.write('')

I believe you can change headers by just modifying self.response.headers