Login

Json Data string from database records

We will be sending data back to the main page by using Json formatted strings. These strings will contain number of Jason data value pairs taken from database table along with some other data.

Json string carries data to the parent application which we will display using JavaScript objects. To generate json string we will use php function json_encode. We have our student table which has four fields ( id, name, class , mark). By using this we will develop some sample scripts to generate json string and then get back the data after parsing the string using JSON.parse.

Getting a single record

Let us first try by collecting and returning a single record from our student table. For better security we have used PDO to connect to MySQL data base and getting the records. We have not discussed the mysql data collection part here, only the data formatting is shown.

str = str + "</table>" ;

document.getElementById("display").innerHTML=str;

Watch the first line in above code. We have used JSON.parse to create JavaScript object. We can also use eval like this

var myObject = eval('(' + httpxml.responseText + ')');

It is not a good idea to use eval as it can execute any JavaScript script so it is a security problem. However JSON.parse is not yet supported by all the advance browsers. So if it is not supported then we can keep another external JavaScript file json2.js downloaded from https://github.com/douglascrockford/JSON-js

Along with single data row we will also try to send few more data . We are sending two arrays of data here. There are two members one is data and other one is value. Each member contains two arrays containing some objects.

Receiving data

In above code we have kept one array of data ( array name is data ) and some single data. Now we will learn how to receive these data and display them.
Inside your Ajax function first let us try to collect the whole bunch of data.

var myObject = JSON.parse(httpxml.responseText);

We know the array name is data. So we will loop through the array to display each row of record of the array.