I am trying to display success data after a jQuery ajax function from a Python server (GAE). I am able to make it work with just a single string or number as the success data, but I would like to relay several pieces of info from the server in the ajax call. I was thinking the best way to do this would be to store the data in a Python object and then send the object in the callback. The object is showing up as "", but the object properties are as "undefined".
Any advice you can give is greatly appreciated-
Javascript:
$.ajax({
type: "POST",
url: "/update_cart",
data: {'item1': item1, 'item2': item2, 'item3': item3},
//dataType: 'jsonp',
success: function(data) {
$("#amount").val(data.total); $("#shopping_cart_count").text(data.cart_item_count);
alert(data); //displays "<main.ajaxObject object at 0x042C8890>"
alert(data.cart_item_count); //displays "undefined"
}
});
Python code:
data = ajaxObject()
data.cart_item_count = 5
data.total = 10
logging.info("*****data.cart_item_count %d ******" % data.cart_item_count ) #displays correctly
logging.info("*****data.total %d ******" % data.total ) #displays correctly
self.response.out.write(data); #respond to ajax success with data object
You need to JSON encode the data like Shaunak D described. The error you're getting is telling you that the
json
package doesn't know how encode yourajaxObject
instance into a string.You can use a custom JSON encoder to fix this as detailed at https://docs.python.org/2/library/json.html (section "Extending JSONEncoder")
Alternatively (and more easily), you can just use a dictionary to represent your data:
jQuery's ajax function should automatically decode the JSON string into a Javascript object.