1

I have been having problems with getting AJAX to post JSON correctly. The application is intended to be hosted on Google App Engine. But what I have does not post data.

Python

 mainPage = """
    <html>
    html is included in my python file.
    </html>
    """ 

    class JSONInterface(webapp2.RequestHandler):
    def post(self):
        name =self.request.get('name')
        nickname =self.request.get('nickname')

        callback = self.request.get('callback')
        if len(name) > 0 and len(nickname) >0:
            newmsg = Entry(name=name, nickname=nickname)
            newmsg.put()
        if len(name)>0:
            self.response.out.write(getJSONMessages(callback))
        else:
            self.response.out.write("something didnt work")

    def get(self):
        callback = self.request.get('callback')
        self.response.out.write(getJSONMessages(callback))

This handler is meant to handle the Ajax calls from the web app. I am unsure if I need javascript to be associated with my main page in order to do so, as I haven't found information on it yet with my searches.

Javascript

$(document).ready( function() {

    $("#post").bind('click', function(event){
           var name = $("#name").val();
           var nickname = $("#nickname").val();

            postData = {name: name, nickname: nickname, callback: "newMessage"};

        $.ajax({
            type: "POST",
            url: "http://localhost:27080/json",
            data: postData,
            dataType: "json",
            done: function() {
                // Clear out the posted message...
                $("#nickname").val('');
            },
            fail: function(e) {
                confirm("Error", e.message);
            }
        });
        // prevent default posting of form (since we're making an Ajax call)...
        event.preventDefault();
    });

The Javascript for the post

Can someone advise me on how I could resolve the problem I am having. Thanks for the time and help.

OasisTea
  • 67
  • 1
  • 7
  • I would maybe try adding contentType: "application/json", – mconlin May 10 '13 at 21:40
  • I have on my mainpage handler. def get(self): self.response.headers['Content-Type'] = 'text/html' self.response.out.write(mainPage) Which is just used to return the page. – OasisTea May 10 '13 at 21:45
  • Are your route handlers in the python file configured correctly? ALso, you are using jQuery? The leading $ is omitted. Should be $(document).ready(). But make sure your handler points ('/json', JSONInterface). – rGil May 10 '13 at 21:45
  • Yes I am using Jquery, and I made a mistake on my copy and paste. $ is part of it. Thank you for pointing it out in my post. – OasisTea May 10 '13 at 21:46
  • I assumed was copy/paste issue :) – rGil May 10 '13 at 21:49
  • I was thinking contentType: "application/json" should be added to list of params in your jQuery $.ajax({ call – mconlin May 10 '13 at 23:05

2 Answers2

3

Did you ask the same question yesterday and then delete it? I swear I just answered the same question.

You're not sending your data as a JSON string. If you want to send as JSON, you need to encode data as a JSON string, or else you're just sending it as a query string.

data: JSON.stringify(postdata),

HOWERVER, your request handler is actually processing the request properly as query string instead of JSON, so you probably don't want to do that.

dragonx
  • 14,963
  • 27
  • 44
  • Apologies, I thought I had figured out the problem myself and deleted the thread to save people from answering. Would you recommend me to change the way my handler processes the string to use data: JSON.stringify(postdata),? – OasisTea May 11 '13 at 03:47
  • You can access the data on the server without encoding it. It is interpreted as key:value. If you json encode it, you will need to import a json lib on your server-side and call json.loads() on your data. – rGil May 11 '13 at 14:57
  • The parameters you are passing are pretty straightforward, and using JSON wouldn't really be necessary. JSON is much more useful for structured data. And as for having this question answered, you should accept the answer from rGil (click on the checkbox beside the question) instead of deleting it. – dragonx May 11 '13 at 15:31
0

For starters, the ajax call is pretty close. The full path

"http:://localhost:27080/json"

is not necessary, the relative path will work, but that is not the problem.

Your callback, as it stands, will work as 'success':

success: function(response) {
            alert(response);

            // Clear out the posted message...
            $("#nickname").val('');
        }

However, this callback is being phased out in favor of other methods. 'Done' should be chained like so:

 $.ajax({
        type: "POST",
        url: "/json",
        data: postData,
        dataType: "json"            
    }).done(function(data){
        console.log(data);
    });

Also, there might be problems on the server. If you use some logging, you will see that the data is indeed being sent to the server.

import json ## we'll get to this below
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
    name = self.request.get('name')
    logging.info(name) ## will print the value of 'name'

Unless your python function getJSONMessages(callback) is returning a json object, your callback will not be called, even after you add the response parameter. In your python code:

import json
import logging
class JSONInterface(webapp2.RequestHandler):
    def post(self):
        callback = self.request.get('callback')
        logging.info(callback) # will print correctly
        self.response.out.write(json.dumps(callback)) 

Using the json.dumps method encodes the passing object to json, which is what your ajax object is looking for.

Community
  • 1
  • 1
rGil
  • 3,719
  • 1
  • 22
  • 30
  • I'm not sure what asJSONString() is, but it throws an error for me:AttributeError: 'unicode' object has no attribute 'asJSONstring. json.dumps(yourData) is what you need – rGil May 11 '13 at 01:37
  • I have amended my code to your recommendations but I cannot see the logging.info. Are you able to tell me if the SDK console and GAE logs is where I am meant to be checking? Sorry for asking such an obvious question. I can't seem to find the information to check out logfiles. – OasisTea May 11 '13 at 01:51
  • SO - incorporate json.dumps() into your code. Also, the 'done' method needs to be chained to the end of your ajax function. If you keep it the way you have it now, change 'done' to 'success'. I'll update my answer to reflect that change. – rGil May 11 '13 at 01:52
  • My logs only look to contain INFO 2013-05-11 02:50:42,128 server.py:561] default: "GET / HTTP/1.1" 200 2725 INFO 2013-05-11 02:50:45,555 server.py:561] default: "POST / HTTP/1.1" 405 188 INFO 2013-05-11 02:50:50,378 server.py:561] default: "POST / HTTP/1.1" 405 188 INFO 2013-05-11 02:54:16,631 server.py:561] default: "GET / HTTP/1.1" 200 2725 INFO 2013-05-11 02:54:16,690 server.py:561] default: "GET /js.js HTTP/1.1" 404 154 With majority being get favicon ico. Does this mean there are more problems with my python. – OasisTea May 11 '13 at 02:00
  • Also, remove the self.request... that I added - as those were just examples before I saw your code. – rGil May 11 '13 at 02:05
  • One more piece of advice - isolate your code as you are testing it. While you are trying to get POST to work, do not call the method to update the db. Just try and get the communication to work between javascript and server. Once that is going, call the database update method, make sure that is working... Isolate your code. – rGil May 11 '13 at 02:10
  • Thanks for the advice. From what have you seen can you tell me if the code is in the right direction? I am very new to pythin and js. Also I am getting '/json 200 54ms 0kb Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31 86.139.133.41' Does this mean json is being posted up? Thanks for all the help. – OasisTea May 11 '13 at 02:15
  • 200 status code means your request was successful. That's a good thing. Your code is definitely in the right direction. – rGil May 11 '13 at 02:51