8

How to use google app engine with ajax (json)?

Now I have this but I got this error:

raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded


from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import simplejson as json

class AjaxHandler(webapp.RequestHandler):
    def post(self):
        args = json.loads(self.request.body)
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write('Hello, webapp World!')





application = webapp.WSGIApplication(
                                     [('/AJAX', AjaxHandler)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

and javascript + jquery:

var Server = function() {
};
Server.prototype = {
    init: function(ajaxTargetUrl) {
        this.ajaxTargetUrl = ajaxTargetUrl;
    },
    request: function(service, data) {
        $.ajax({
            url: this.ajaxTargetUrl,
            context: document.body,
            success: function(data) {
                $('body').append('<p>'+data+'</p>');
            },
            error: function(){
                $('body').append('<p>error</p>');
            },
            data: data,
            type: 'POST',
            dataType: 'json'
        });
    }
};

var APP = ( function() {
    var server = new Server();
    server.init('http://localhost:9999/AJAX');
    server.request('questions.all', {test:'hey', y:99});
}());

my self.request.body = str: test=hey&y=99

2 Answers 2

8
  1. as long as I know self.request.body wouldn't return anything. There's no argument named 'body' in your query-string, but I might be wrong. So, if it returns something, this something is a STRING. So simplejson.dumps() cannot turn it into a valid JSON.

    If you need a 'list' of all arguments you have sent to the server, use self.request.arguments()

  2. self.response.out.write('Hello, webapp World!') do not send a valid JSON back to client. It sends a string with "application/json" header instead of "plain/text". Try to create a python dictionary. For example:

    my_response = {'ajax_resp':'Hello, webapp World!'}
    json = json.dumps(my_resposne)

    and then

    self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
    self.response.out.write(json)

  3. On the client side I would suggest you to use console.log() (debugging tool) for testing your responses.

    you can just try:

    $.ajax({
       type: 'GET',
       url: '/AJAX', // or your absolute-path
       data : name=totty&age=20,
       dataType : 'json',
       success : function(resp) 
                 {
                 console.info("Ajax Response is there.....");
                 console.log(resp);
                 }
       });

6
  • xD totty@20 xDD thanks man! now I get it, but when I serialize back data from gae to js i got some problems at datetime variables. I have models in gae that i need to send to the client, how do i do? best practice
    – Totty.js
    Feb 24, 2011 at 23:15
  • If my post helped you, you can accept the answer. Yes! reputation is everything! That's way i have suggested to use console.log() on client-side. If gae returns an error you can see it as response text of an ajax call. Not the best practice, I know, but it works. Anyway, you should post the errors (datetime) u get for further help.
    – V-Light
    Feb 24, 2011 at 23:43
  • 3
    "self.request.body" in App Engine its not a parameter in the request (that would be "self.request.get('body')" ). It refers to the body of the HTTP request.
    – Robert
    Dec 16, 2011 at 11:52
  • 1
    is the self.response.headers.add_header('content-type', 'application/json', charset='utf-8') required?
    – Jimmy Kane
    Dec 31, 2012 at 23:28
  • 1
    @JimmyKane : simplejson.loads(self.request.body) is correct. It takes the http request body, assume that is formatted as json, and transform it to a json object. What I was trying to say is that 'body' in this case is the request http body and not an arbitrary parameter in the request..
    – Robert
    Jan 3, 2013 at 13:18
3

Your JavaScript is not sending JSON data to App Engine (test=hey&y=99 is a urlencoded string). Your App Engine page is not returning JSON data (Hello, webapp World! will just be received as a naked string).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.