I have the below data and I would like to find out how many sets I have and how to access each key value pair in javaScript.

response[
{"RECORD_NUM":967,"DATE_FIELD":"1736-01-19","DESCRIPTION":"James Watt, inventor of the steam engine, was born in Scotland."},
{"RECORD_NUM":1002,"DATE_FIELD":"1747-01-19","DESCRIPTION":"Johann Bode founder of \"Bode's Law \" dies"},
{"RECORD_NUM":1111,"DATE_FIELD":"1770-01-19","DESCRIPTION":"Battle of Golden Hill (Lower Manhattan)"},
]

It seems that response.length() gives the value of the number of fields.
And using generates an error

var dataCheck = response.DATE_FIELD[0];

How would I get the value of the second field in the first row of response?

Member Avatar for diafol

Shouldn't that be response[0].DATE_FIELD ?

You have an array of objects - so response[0] = first array item (an object) and DATE_FIELD is the object property or object 'key'.

dataCheck = response[0].DATE_FIELD;
Yes you are correct, the correct syntax is:
Given that, here is the full explanation of my problem.

I used “json_encode” and “echo(ed)” the result to an AJAX call and I get the json object which the PHP manual refers to as “json_encode — Returns the JSON representation of a value”.
Here is a short example of what I get when I console log the variable
console.log("Returned data = RESPONSE: \n" + response + "\n\n");response[{"RECORD_NUM":967,"DATE_FIELD":"1736-01-19","DESCRIPTION":"James Watt, inventor of the steam engine, was born in Scotland."},{"RECORD_NUM":1002,"DATE_FIELD":"1747-01-19","DESCRIPTION":"Johann Bode founder of \"Bode's Law \" dies"},{"RECORD_NUM":1111,"DATE_FIELD":"1770-01-19","DESCRIPTION":"Battle of Golden Hill (Lower Manhattan)"}]
The next step is to parse it with JSON.parse:
“To access the JSON object in JavaScript, parse it with JSON.parse(), and access it via “.” or “[]”. “
If JSON.parse fails as it does in my case I ask the question “How can you cannot access the returned “JSON representation of a value.” ?”
Here is a small text file that works with a javaScript variable but not with a “JSON representation of a value.”
This file works as I expected

`<!DOCTYPE html>
<html>
    <head>
        <title>JSON value</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>TODO write content</div>
        <!--Call a javaScript-->
        <script type="text/javascript" src="js/jquery-2.2.0.min.js"></script>
        <script>
            $("document").ready(function () {
                var response = [
                    {"RECORD_NUM": 967, "DATE_FIELD": "1736-01-19", "DESCRIPTION": "James Watt, inventor of the steam engine, was born in Scotland."},
                    {"RECORD_NUM": 1002, "DATE_FIELD": "1747-01-19", "DESCRIPTION": "Johann Bode founder of \"Bode's Law \" dies"},
                    {"RECORD_NUM": 1111, "DATE_FIELD": "1770-01-19", "DESCRIPTION": "Battle of Golden Hill (Lower Manhattan)"}
                ];
                dataCheck = response[0].DATE_FIELD;
                console.log("dataCheck = " + dataCheck + "\n");
            });
        </script>
    </body>
</html>
Console prints:
dataCheck = 1736-01-19
`

If I use the code above in a AJAX success call I get an error:

            success: function (response) {
                console.log("Returned data = RESPONSE: \n" + response + "\n\n");
                 dataCheck = response[0].DATE_FIELD;
                console.log("dataCheck = " + dataCheck + "\n");

queryDatabase02.js:39 Returned data = RESPONSE: 
[{"RECORD_NUM":967,"DATE_FIELD":"1736-01-19","DESCRIPTION":"James Watt, inventor of the steam engine, was born in Scotland."},
{"RECORD_NUM":1002,"DATE_FIELD":"1747-01-19","DESCRIPTION":"Johann Bode founder of \"Bode's Law \" dies"},
{"RECORD_NUM":1111,"DATE_FIELD":"1770-01-19","DESCRIPTION":"Battle of Golden Hill (Lower Manhattan)"},
        ...
}]

So the question is How can I access the “JSON representation of a value” in javaScript?

Member Avatar for diafol

Show the entire ajax call. You probably need to use $.getJSON (or $.ajax or a variant with dataType: "json"). This way response should be traversable without parsing and fussing with it.

Here is the end of the PHP file, note that the header is commented, it seems to work better, no error on the javaScript end when I try to JSON.parse.

// json_encode — Returns the JSON representation of a value
$jsonVal = json_encode($timeRtr);
$fileHandle = fopen('storage\jsonStorage', "a") or die("Unable to open file!");
fwrite($fileHandle, $jsonVal);
fwrite($fileHandle, "\n");
fclose($fileHandle);

//header('Content-Type: application/json');
echo ($jsonVal);
?>

Here is the full text of the javaScript file :

$("document").ready(function () {
    $("button[name='History']").click(function (e) {
        // so the form does not get submitted
        e.preventDefault();
        var displayStr = "";
        var theQuery = {queryString: "SELECT * FROM time_table WHERE" +
                    " EXTRACT(MONTH FROM DATE_FIELD ) = DATE_FORMAT(NOW()," +
                    " '%c')  AND  EXTRACT(DAY FROM DATE_FIELD ) = DATE_FORMAT(NOW(), '%e')" +
                    " ORDER BY DATE_FIELD]}"};
        console.log("\t THEObject = " + theQuery + "\n");
        $.ajax({
            type: "POST",
            //                   dataType: "json",
            url: "queryDatabase02.php",
            data: theQuery,
            success: function (response) {
                console.log("Returned data = RESPONSE: \n" + response + "\n\n");
                dataCheck = response[0].DATE_FIELD;
                console.log("dataCheck on response " + dataCheck + " \n");


                // How big is response
                responseCnt = response.length;
                console.log("responseCnt = " + responseCnt + "\n");

                // Access the data ...
                displayArray = JSON.parse(response);
                console.log("THIS IS display STRING:\n" + displayArray + "\n");
                dataCheck = displayArray[0].DATE_FIELD;
                console.log("dataCheck Second time = " + dataCheck + "\n");
                console.log("LEAVING .............\n");
            }
        });
        return false;
    });
});
Member Avatar for diafol

PHP file

$jsonVal = json_encode($timeRtr);
//...
echo $jsonVal;

Seems fine - no need for header as you are simply reading this into a js variable. The dataType for JSON is expecting just plain text in json format.

JS code
Your ajax code, I imagine could look like this:

$.ajax({
        type: "POST",
        dataType: "json",
        url: "queryDatabase02.php",
        data: theQuery,
        success: function (response) {
            console.log(response[0].DATE_FIELD);
        }
  });
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.