How to call json data with ajax from the database (php / mysql)


I have an table and charts here is demo: and Code:

I use curently this data:

// Prepare the data
        var data = google.visualization.arrayToDataTable([
          ['Name', 'Gender', 'Age', 'Donuts eaten'],
          ['Michael' , 'Male', 12, 5],
          ['Elisa', 'Female', 20, 7],
          ['Robert', 'Male', 7, 3],
          ['John', 'Male', 54, 2],
          ['Jessica', 'Female', 22, 6],
          ['Aaron', 'Male', 3, 1],
          ['Margareth', 'Female', 42, 8],
          ['Miranda', 'Female', 33, 6]

but I want to call data from mysql database:

CREATE TABLE table_name
    ID varchar(255),
    Name varchar(255),
    Gender varchar(255),
    Age varchar(255),
    Donuts_eaten varchar(255)

INSERT INTO table_name VALUES ('1', 'Mike', 'Male', '23', '5')
INSERT INTO table_name VALUES ('2', 'Annne', 'Female', '44', '7')
INSERT INTO table_name VALUES ('3', 'John', 'Male', '32', '10')

So I need to fetch table with php to get json output like this:

[{"ID": "1", "Name": "Mike", "Gender": "Male", "Age": "23", "Donuts eaten": "5"}, {"ID": "2", "Name": "Annne", "Gender": "Female", "Age": "44", "Donuts eaten": "7"}, {"ID": "3", "Name": "John", "Gender": "Male", "Age": "32", "Donuts eaten": "10"}]

and the finnaly I need to put JSON data from database to variable data ? How I can do this? What php file needs to looks like? How to change my curent data with data frm database?

In PHP you can simply connect to your Database and fetch the Results. I Assume you know how to connect to Databases, but there are many tutorials how to connect and work with MYSQL Databases online in case.

What you want to do now, is getting for each Dataset the informations you want and put them into an Array. array( 'key1' => 'value1', 'key2' => 'value2'); Iterating trough a set of Results is done with a foreach loop.

Once you have an array with each Information you want, you do return this: json_encode($myArray, true);

Make sure that you set the header of the Returning Site to json format.