user3331391
user3331391

Reputation:

Parse JSON in Ajax

This is my JS code

function process_file(file_name) {
    $.ajax({
        type: "POST",
        url: "process_file.php?file_name="+file_name,
        datatype : "json",
        cache: true,
        success: function(data) {
            console.log(data);
            //alert(data);

            var error_flag = data[0]["error_flag"];
            var database_insert = data[0]["database_insert"];
            var mysql_message = data[0]["mysql_message"];
            var excel_read_message = data[0]["excel_read_message"];

            alert(mysql_message);

            $("#error_flag").html(error_flag);
            $("#database_insert").html(database_insert);
            $("#mysql_message").html(mysql_message);
            $("#excel_read_message").html(excel_read_message);

        }
    });
}

Console log that is displayed:

[{"error_flag":true,"database_insert":true,"mysql_message":"Data Inserted Successfully","excel_read_message":null}]

I want to extract each variable in js code. I have tried various but not getting what is desired.

Upvotes: 1

Views: 72

Answers (2)

Fizer Khan
Fizer Khan

Reputation: 92725

I think, the data comes as a string, thats why you cannot access the members. Change datatype to dataType

function process_file(file_name) {
    $.ajax({
        type: "POST",
        url: "process_file.php?file_name="+file_name,
        dataType : "json",
        cache: true,
        success: function(data) {
            console.log(data);
            //alert(data);

            var error_flag = data[0]["error_flag"];
            var database_insert = data[0]["database_insert"];
            var mysql_message = data[0]["mysql_message"];
            var excel_read_message = data[0]["excel_read_message"];

            alert(mysql_message);

            $("#error_flag").html(error_flag);
            $("#database_insert").html(database_insert);
            $("#mysql_message").html(mysql_message);
            $("#excel_read_message").html(excel_read_message);

        }
    });

Upvotes: 1

Pramod S. Nikam
Pramod S. Nikam

Reputation: 4541

Problem here is the way you are accessing json attribute is not correct. as your json under curley bracket is not array.

You'll have to do like below:

var error_flag = data[0].error_flag;
// repeat it for other vars

Upvotes: 0

Related Questions