0

I have an ajax call, that sends data to an php file, inserts it to the database and returns the id of the last database entry

    $.ajax({
            url: 'php/xyz.php',
            type: 'POST',
            dataType  : 'json',
            data: {'name': 'name',
                   'description': 'description'
                  },
            success: function (data) {
                var prop = 'max(id_b)';
                var i = data[0].prop;
                alert(data.toSource() + " " + i);
            },
            error: function (jqXHR, textStatus, ex) {
                alert("error");
            }
        });    

Returned data:

data.toSource() returns [{"max(id_b)":"162"}]

My usual approach returns an reference error for id_b

data[0].max(id_b);

and this approach does not work either:

var prop = 'max(id_b)'; var i = data[0].prop;

It seems that the parentheses or the underscore is the problem. How can I get the value into a variable?

KLPA
  • 67
  • 1
  • 10

1 Answers1

0
var i = data[0][prop]

Using .prop is searching for the "prop" key. Using square brackets let's you pass in a variable and searches for "max(id_b)" instead (the value of prop).

You can also just use

var i = data[0]["max(id_b)"]

to avoid having to assign prop in the first place.