views:

51

answers:

2

I'm developing in Google App Engine (python sdk) and I want to use jQuery to send an Ajax request to store an answer to a question.

What is the best way to send this data to the server? Currently I have:

function storeItem(question_id) {
        var answerInputControl = ".input_answer_"+question_id;
        var answer_text = $(answerInputControl).text();
        $.ajax({
            type: "POST",
            url: "store_answer.html",
            data: "question="+question_id,
            success: function(responseText){
                alert("Retrieved: " + responseText);
            }
        });
    }

This takes a question Id and provides it to the server via the query string. But on the server-side, I'm unable to access the content of the answer control which I want to store. Without Ajax, I'm able to perform this operation with the following:

class StoreAnswers(webapp.RequestHandler):
def post(self):
    question_id = self.request.get("question_id")
    answer_text = self.request.get("input_answer" + question_id)

But when doing this call through Ajax, my answer_text is empty.

  • Do I need to send the contents of this control as part of the data with the Ajax request?
  • Do I add the control itself to the query string? Its contents? Does it matter that the content might be a few hundred characters long? Is this the most-recommended practice?
  • If sending it as a query string, what's the best way to escape the content so that a malicious user doesn't harm the system?
+2  A: 

The data in your ajax call must include all the data you want to send -- posting a few hundred characters is absolutely no problem and it's most definitely the recommended approach.

Do not use a GET in lieu of POST -- that (which I suspect is what you mean by "send as a query string") would only buy you trouble of all sorts, and is a violation of the semantics of GET (which should be limited to "read-only" queries, ones with no side effects).

Alex Martelli
I mentioned a query string because I thought this line in the ajax call "data: "question="+question_id" was building a query string, but I guess I was wrong in this. What's a good way to escape the content before sending it through the ajax call?
Cuga
+1  A: 

Your data is incorrectly formatted:

data: {
    question_id: question_id,
    input_answer: $(answerInputControl).text()
}
Khnle
The ajax request in the example isn't sending over the answerInputControl's text. Part of the question was if I had to, or if I could just access the controls from python (self.request.get('input_answer_questionID')), which works without ajax. Thanks for giving a better way of sending the data though.
Cuga