Search code examples
jquerypythonjsontornado

Server not sending back JSON Object


On the client side I'm creating a JSON object storing emails and email types from user inputted data in input fields. I then use ajax to send it as a JSON to my server.

$(function () { 
$(document).on('click', '.send', function (e) {
    var dataToSend = [];
    $('.form-group1').each(function () {
        var data = {};
        $(this).find(':input[data-name]').each(function () {
            data[$(this).data('name')] = $(this).val();
        });
        dataToSend.push(data);
    });

    $.ajax({
       url: '/pers1',
       type: 'POST',
       contentType:'application/json',
       data: JSON.stringify(dataToSend),
       dataType:'json',
     });        
    console.log(JSON.stringify(dataToSend))
 });
});

The server then stores this into the database as a JSON object:

class PersonalInfoHandler1(BaseHandler):
@tornado.web.authenticated
def post(self):
    global piData

    receipt = tornado.escape.json_decode(self.request.body)
    print receipt

    piData={                            
            'emails': receipt,
            }      

    self.settings['db'].userInfo.update({'PiUsername':self.current_user},{"$set":piData})
    print 'from pers1'                 
    self.redirect('/pers')

When the page is reloaded the data is sent back in another Handler as:

class PersonalInfoHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
    self.render("personal.html", user=self.current_user, ,emails=user['emails'])

The client gets this back and I try to iterate over the key:value's like this:

var emails = '{{emails}}';
emails = emails.replace(/u'/g,"");
emails = emails.replace(/'/g,"");

emaildata=JSON.stringify(emails)

$.each(emaildata, function(key, value) { 
      alert(key + ': ' + value); 
    });

Instead I get the error in Chrome console:

Uncaught TypeError: Cannot use 'in' operator to search for '28' in "[{emailAdd: , emailDesc: }]" jquery.min.js:2  jquery.min.js:2 m.extend.each jquery.min.js:2 (anonymous function)

So I cannot iterate over the keys and/or values. Is the problem with the actual JSON or code?


Solution

  • $.each(emaildata, ...) isn't iterating an Array or Object. It's trying to iterate a String value character-by-character.

    console.log(typeof emaildata, emaildata);
    // string '"[{emailAdd: , emailDesc: }]"'
    

    It is also the stringified form of yet another string.

    var emails = '[{emailAdd: , emailDesc: }]';
    

    The value of emails in JavaScript would at least need to be valid JSON, which needs encoding from Python, so it can be parsed:

    var emails = '{% raw json_encode(emails) %}';
    var emaildata = JSON.parse(emails);
    
    $.each(emaildata, function (key, value) {
        // ...
    });
    

    Though, since JSON's syntax came from JavaScript, you can output JSON as an expression for JavaScript to parse directly as Array and Object initializers (note the removal of the quotes):

    var emails = {% raw json_encode(emails) %};
    
    $.each(emails, function (key, value) {
        // ...
    });