Ayan
Ayan

Reputation: 2918

JSON response received in AJAX success but not parsing

I have the following AJAX function below. The problem is that I get the correct response headers in the success function of AJAX but when I parse the response I get undefined.

The JSON data that I receive is like following:

[{"responseCode":1,"msg":"Successfully done!"}]

JS

// Renaming am item
    filelist.on('click', '.btn-rename', function(){
        var that = this; //Save the scope of the button that was clicked
        var id = $(this).data('id');
        var name = $(this).data('filename');
        var jc = $.confirm({
            theme: 'black',
            type: 'dark',
            typeAnimated: true,
            title: 'Rename this file?',
            icon: 'fa fa-pencil-square-o',
            content: '<input id="newName" type="text" value="'+name+'"/><span id="response"></span>',
            onOpen: function() {
                var element = $('#newName');
                element.focus();
                element.select();
            },
            buttons: {
                save: {
                    text: 'Rename',
                    btnClass: 'btn-dark',
                    action: function() {

                        this === jc;

                        var inputName = $('#newName').val();
                        if(inputName == '') {
                            $('#response').html('Please enter a new name..').addClass('responseAlert');
                            return false;
                        }
                        else
                        if(inputName == name) {
                            $('#response').html('&nbsp;C&#39;mon! Don&#39;t be silly..').addClass('responseWarning');
                            return false;
                        }

                        //Send request to update the name
                        $.ajax({
                            type:"POST",
                            url:"rename.php",
                            data: {
                                fileId: id,
                                newName: inputName
                            },
                            beforeSend: function() {
                                $('#response').html('<i class="fa fa-spinner fa-spin" aria-hidden="true"></i> Working on it...').addClass('responseProcessing');
                            },
                            success: function(data){
                                var obj = JSON.parse(data);
                                var status = obj.responseCode;
                                alert(obj.responseCode);
                                if(status == 1) {
                                    jc.close();
                                    $.alert({
                                        theme: 'black',
                                        icon: 'fa fa-check',
                                        title: 'Success',
                                        type: 'green',
                                        typeAnimated: true,
                                        content : response.msg
                                    });
                                }
                                else {
                                    $('#response').html(response.msg).addClass('responseAlert');
                                }
                            }
                        });
                        return false;
                    }
                },
                cancel: {
                }
            }
        });
        return false;
    });

Upvotes: 1

Views: 1582

Answers (2)

Daniele Cruciani
Daniele Cruciani

Reputation: 623

If you specify dataType:"text", then the response Will ne not parsed. The problem with tour expectation is that you try to access property of an array:

var data = "[{"responseCode":1,"msg":"Successfully done!"}]"
var obj = JSON.parse(data)
// and then:
console.log(obj[0]. responseCode)

obj is an array! (Or remove e Square brakets!)

Upvotes: 1

Adam Azad
Adam Azad

Reputation: 11297

When the response is parsed, it converted to JSON Array with that object indexed as the first element. Note the brackets [] are causing this.

var a = JSON.parse('[{"responseCode":1,"msg":"Successfully done!"}]');
console.log(a); // [Object] 
console.log(a[0]); // {"responseCode":1,"msg":"Successfully done!"}

var a = JSON.parse('[{"responseCode":1,"msg":"Successfully done!"}]');
console.log(a); // [Object] 
console.log(a[0]); // {"responseCode":1,"msg":"Successfully done!"}

Whereas parsing a string without brackets results in desired object

var a = JSON.parse('{"responseCode":1,"msg":"Successfully done!"}');
console.log(a); // {"responseCode":1,"msg":"Successfully done!"} 

var a = JSON.parse('{"responseCode":1,"msg":"Successfully done!"}');
console.log(a); // {"responseCode":1,"msg":"Successfully done!"} 

You need to have to remove those brackets from your back-end.

Upvotes: 3

Related Questions