dclowd9901
dclowd9901

Reputation: 6826

How does one utilize JSON response data from an AJAX call?

I can't seem to execute any code from an AJAX call or utilize the JSON response. What am I missing? The call is successful, and I can see in Firebug that the script executes fine on the server side, but I can't seem to do anything with the data that comes back.

review.single = {
    id: null,
    ip: null,
    el: null,
    addFlag: function(){
        if(this.id && foo.user_id){
            $.ajax({
                type: 'post',
                url: '/reviews/add_flag/',
                data: ,
                dataType: 'json',
                success: function(data){
                    if(data.success){
                        this.el.text('Flagged');
                        this.el.css({
                            'text-indent': none,
                            backgroundColor: '#c00',
                            color: '#fff'
                        })
                    } else {
                        $('#growl').text(data.message);
                        $('#growl').fadeIn(500).delay(5000).fadeOut(200);
                    }                   
                }
            })
        }
    }   
}

I get this back on one of the calls response types:

{success: false, message: "You have already flagged this item."}

Ideally, I'd like to be able to take the message and throw it into the growl and show it, and use the success property as a check.

UPDATE:

I added an error block; looks like this:

error: function (request, status, error) { 
    alert(request.responseText); 
}

As a result, I get an alert that says:

{success: false, message: "You have already flagged this item."}

Upvotes: 0

Views: 1372

Answers (1)

dclowd9901
dclowd9901

Reputation: 6826

Figured it out.

My JSON was apparently not formatted correctly, and the properties needed to be wrapped in ". This threw an error back to jQuery. Thanks for the help, guys.

Example:

{"success": false, "message": "You have already flagged this item."}

Upvotes: 1

Related Questions