Echarts, PHP, MySQL, Ajax, JQuery enable front-end data visualization

Source: Internet
Author: User
Tags prepare

      • Echarts
        • Download JS Code
        • Brief analysis of working principle
        • Introducing Echarts in the project
      • Background processing
        • Database-side MySQL
        • PHP side
        • JQuery Ajax Processing
        • Echarts End Processing
        • Front End All code
        • Demo results
      • Summarize

Recently to the background of some data on the database in a visual way to display to the front, find out, found that Baidu developed this set of chart tool library is also good, online search for a related tutorial, but also to achieve a relatively simple demo. So write it down and record it.

Echarts

Echarts is a set of front-end charting tools developed by the Chinese, which is extremely convenient and easy to use (assuming, of course, after understanding how it works).

Here's a quick introduction to how to use Echarts in your project.

Download JS Code

: http://echarts.baidu.com/

Personally, developers download the full version will be a little better. And the official recommendation is to download the full version.

Bloggers here Download the full version, about less than 2M.

Brief analysis of working principle

In fact, think carefully, Echarts's job is to display a special picture on the page. So we need to be aware of the need to give "pictures" a space, so that there will be a chart of the home.

Then there is the space, that is, the land. If you want to build a house, you have to have a frame. This way, add some bricks and mortar to the top to cover up the house. Similarly, echarts is the same principle. But this "skeleton" is called option. As to how this option needs to be set up, the official website has a detailed introduction, bloggers will no longer repeat here to build the wheel. Everyone is interested in the place to show to learn.

Introducing Echarts in the project

Title, this section is about the simple use of this icon library.
Take a look at the following code:

<! DOCTYPE html><html><head><meta charset="UTF-8"><title>Entry</title><script src=".. /static/js/echarts.js "></script><script src=".. /static/js/sleeplib.js "></script></head><body>    <H1>Start testing</H1>    <hr>    <!--first prepare a container for the chart--    <div id=' container ' style= 'width:600px; height:400px; " ></div>    <script>        //Initialize a Echarts instance with the Echarts.init method and generate a simple histogram by setOption method        //Based on the prepared DOM, instantiate the Echarts instance        varMyChart = Echarts.init (document.getElementById ("Container"));//Specify configuration items and data for the chart        varOption1 = {title: {text:' echarts introductory case '}, tooltip: {text:' mouse on the hover after the prompt statement! '}, Legend: {data: [' Sales ']}, Xaxis: {data: [' shirts ',' Sweater ',' Chiffon sweater ',' Pants ',' High heels ',' socks ',' underwear ']}, YAxis: {}, Series: [{name:' Sales ', type:' Bar ', Data: [7, -, $,Ten,Ten, -, -]            } ]        };//Use the configuration item above as a parameter and pass it to Echart to displayMychart.setoption (Option1);</script></body></html>

The key is the last sentence:

Mychart.setoption (Option1);

It's a self-evident function. So, what is the effect? Such as:

Another manual click on the top of the legend for "sales" of the small red rectangle, there will be a surprise yo.

Let's get to the chase today.

Background processing

Background processing involves querying the database using PHP, and then returning it as an array, and then fetching the data by jquery in the form of Ajax and handing it over to the front-end for display.

Database-side MySQL

Data is the core, so building a library is important. This is just for demonstration, so the database is very simple to build, such as:

PHP side

It is important to note that the database side must be returned in JSON type, so that it can be more convenient for AJAX processing.

<?phpheader ("Content-type=text/json;charset=utf-8"); $conn = mysql_connect ("localhost","Root","MySQL") or Die ("The process of connecting to the database failed!" "); mysql_query ("Set names Utf-8"); mysql_select_db ("Test"); $resultset = mysql_query ("SELECT name, age from Echartsuser", $conn);/////////////////////////// /// /// /// /// /// /// ///Prepare data for reload  $data = Array ();/////////////////////////// /// /// /// /// /// ///   ///entity classClass user{ Public$username; Public$age;}/////////////////////////// /// /// /// /// /// ///   ///Processing while($row = mysql_fetch_array ($resultset, MYSQL_ASSOC)) {$user =NewUser (); $user->username = $row [' name ']; $user->age = $row [' age ']; $data [] = $user;} $conn. Close ();//Return JSON-type dataecho Json_encode ($data);

So verifying that the returned data type is not JSON, we just need to do the next interface test. Bloggers Use the Chrome browser, a JSON plug-in, so it can be easily detected. Such as:

JQuery & Ajax Processing

jquery is really a difficult function tool library, so using jquery to handle AJAX requests can reduce the complexity of coding, and the underlying will automatically handle compatibility issues. It's geek.

In this example, the purpose is to obtain the data in the data interface just now. So the code is simple, as follows:

//Initialize two arrays to get the data from the database    varnames = [], ages = [];//Call Ajax to implement asynchronous loading data     function getusers() {$.ajax ({type:"POST", Async:falseUrl:".. /app/getuser.php ", data: {}, DataType:"JSON", Success: function(Result){                if(Result) { for(vari =0; i < result.length;                        i++) {Names.push (result[i].username);                    Ages.push (Result[i].age); }}}, Error: function(errmsg) {Alert"Ajax get Server Data Error!" "+ errmsg); }        });returnNames, ages; }//Execute asynchronous requestGetusers ();
Echarts End Processing

Now "Everything is ready, only the East wind", the data are already there, the rest is how to display them. According to the first blogger's theory of building a house, let's put the skeleton up here.

//Initialize the chart object        varMyChart=Echarts.Init (document.getElementById ("Container"));//To set up related items, that is, the so-called lap skeleton, easy to wait Ajax asynchronous data filling        varOption={title: {text:' name Age Distribution chart '}, tooltip: {show:true}, Legend: {Data:[ ' age ' ]}, Xaxis:[{Data: Names}], YAxis:[{type:' value '}], Series:[{"Name":"Age","Type":"Bar","Data": Ages}]        }; Assigns a configuration item to the chart object to display the associated data mychart.setoption (option);

Note Xaxis: The inside of the names, and series inside the ages is the previous jquery using AJAX to obtain the data.

Front End All code

Personally feel that there is a complete code will give a lot of inspiration, then here is the front-end interaction of the code bar, but also convenient for everyone to view.

<! DOCTYPE html><html><head><meta charset="UTF-8"><title>JQuery Ajax Test</title><script src=".. /static/js/echarts.js "></script><script src=".. /static/js/jquery-1.11.1.min.js "></script></head><body>    <H1>PHP Ajax ecahrts Test</H1>    <hr>    <div id="container" style="width:600px; height:400px; " ></div>    <script>    //Initialize two arrays to get the data from the database    varnames = [], ages = [];//Call Ajax to implement asynchronous loading data     function getusers() {$.ajax ({type:"POST", Async:falseUrl:".. /app/getuser.php ", data: {}, DataType:"JSON", Success: function(Result){                if(Result) { for(vari =0; i < result.length;                        i++) {Names.push (result[i].name);                    Ages.push (Result[i].age); }}}, Error: function(errmsg) {Alert"Ajax get Server Data Error!" "+ errmsg); }        });returnNames, ages; }//Execute asynchronous requestGetusers ();//Initialize the chart object        varMyChart = Echarts.init (document.getElementById ("Container"));//To set up related items, that is, the so-called lap skeleton, easy to wait Ajax asynchronous data filling        varoption = {title: {text:' name Age Distribution chart '}, tooltip: {show:true}, Legend: {data: [' age ']}, Xaxis: [{data:names}], YAxis: [{t ype:' value '}], series: [{"Name":"Age","Type":"Bar","Data": Ages}]};//Assign a configuration item to the chart object to display the relevant datamychart.setoption (option);</script><marquee>Sure we can get here.</marquee></body></html>
Demo results

At this point, the encoding task is completed. So can't wait to see the effect.

Then, slightly modify the data, and then to see what the results will be, after the refresh, such as:

Summarize

Finally, to review the harvest of this experiment. In fact, it is a comparison of echarts "full stack" (Please allow me to use a less appropriate word o (∩_∩) o). A simple process for visualizing the data at the backend and front end.

The technology used is also very popular, and then the end can not only be done by PHP, Java,python,golang and so on can be, just use php more convenient. As long as you can obtain the desired data based on this interface.

Echarts, PHP, MySQL, Ajax, JQuery enable front-end data visualization

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.