2

I have a .json file (abc.json) and I want to plot graph using jqplot from two columns of this data. My approach is:

  1. Converting json file data into array using jquery
  2. Plotting graph from that array using jqplot
  3. Then showing that graph on browser using html
  4. However I am not able to do so as I am not very proficient in javascript.

My JSON data looks like follows:

[
  {
    "id":1,
    "essid":"\"WiredSSID\"",
    "mac":"08:00:27:b1:3e:4d",
    "ip":"10.0.3.15",
    "ss":-55,
    "lon":-18.5333,
    "lat":65.9667,
    "alt":15.044444,
    "acc":1,
    "res":18058,
    "pub_date":"2015-12-01 22:39:07.700953"
  },
  {
    "id":2,
    "essid":"\"WiredSSID\"",
    "mac":"08:00:27:b1:3e:4d",
    "ip":"10.0.3.15",
    "ss":-55,
    "lon":-18.5333,
    "lat":65.9667,
    "alt":15.044444,
    "acc":1,
    "res":16337,
    "pub_date":"2015-12-01 23:13:52.639206"
  },

However I want my javascript to read the data directly from JSON file and plot the graph for id vs res.

Below is a an incomplete code which I have written for this purpose which is missing some major process.

Can anyone please help me completing this code so that I can complete this academic project of mine. this would be really helpful.

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="jquery.jqplot.css" />


<script src="jqplot.canvasTextRenderer.min.js" type="text/javascript"></script>
<script src="jqplot.canvasAxisLabelRenderer.min.js" type="text/javascript"></script>
<script src="jquery-1.11.3.min.js" type="text/javascript"></script>
<script src="jquery.jqplot.js" type="text/javascript"></script>
<script src="jqplot.dateAxisRenderer.js" type="text/javascript"></script>
<script src="jqplot.categoryAxisRenderer.js" type="text/javascript" ></script>
<script src="jqplot.ohlcRenderer.js" type="text/javascript"></script>
<script src="jqplot.highlighter.js" type="text/javascript"></script>
<script src="jqplot.cursor.js" type="text/javascript"></script>
<script src="jqplot.pointLabels.min.js"  type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {
        // The url for our json data
        var url = 'mc_measurementne_new1.json';

        var ret = null;
        $.ajax({
            // have to use synchronous here, else the function 
            // will return before the data is fetched
            async: false,
            url: url,
            dataType: "json",
            success: function (data) {
                ret = data;
            }
        });

        var ID = [];
        var Delay = [];

        for (i = 0; i < ret.length; i++) {
            // Save the data to the relevant array. Note how date at the zeroth position (i.e. x-axis) is common for both demand and supply arrays.
            ID.push([ret[i].Date, ret[i].id]);
            Delay.push([ret[i].Date, ret[i].res]);
        }

        var plot1 = $.jqplot('chart1', [ID, Delay], {
            title: "Delay",
            axes: {
                xaxis: {
                    renderer: $.jqplot.DateAxisRenderer,
                    tickOptions: {
                        formatString: '%d/%m/%Y'
                    },

                    label: 'Date'
                },
                yaxis: {
                    label: 'Delay'
                },
                y2axis: {
                    label: 'ID'
                }
            },
            series: [
                { yaxis: 'yaxis', label: 'ID' },
                { yaxis: 'y2axis', label: 'Delay' }
            ],
            highlighter: {
                show: true,
                sizeAdjust: 1
            },
            cursor: {
                show: false
            }
        });
    });
</script>

@{
    ViewBag.Title = "jQPlot Demo";
}

<h2>@ViewBag.Title</h2>
<div id="chart1" style="height: 400px; width: 600px;"></div>




<script type="text/javascript" src="jquery.jqplot.min.js"></script>
<script type="text/javascript" src="jqplot.dateAxisRenderer.min.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.canvasTextRenderer.min.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.canvasAxisLabelRenderer.min.js"></script>
<script language="javascript" type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script language="javascript" type="text/javascript" src="jquery.jqplot.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.dateAxisRenderer.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.categoryAxisRenderer.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.ohlcRenderer.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.highlighter.js"></script>
<script language="javascript" type="text/javascript" src="jqplot.cursor.js"></script>

</body>
</html>
Govind
  • 87
  • 2
  • 12

1 Answers1

1

Here is a working example. https://jsfiddle.net/9jk0jyvt/1/

I commented out the ajax request and replaced it with the json response you have provided above.

One thing to note is that you had the incorrect key for date. I switched it to pub_date.

I also swapped your axis labels to be correct.

$(document).ready(function() {
// The url for our json data
var url = 'mc_measurementne_new1.json';

data = [{
  "id": 1,
  "essid": "\"WiredSSID\"",
  "mac": "08:00:27:b1:3e:4d",
  "ip": "10.0.3.15",
  "ss": -55,
  "lon": -18.5333,
  "lat": 65.9667,
  "alt": 15.044444,
  "acc": 1,
  "res": 18058,
  "pub_date": "2015-12-01 22:39:07.700953"
}, {
  "id": 2,
  "essid": "\"WiredSSID\"",
  "mac": "08:00:27:b1:3e:4d",
  "ip": "10.0.3.15",
  "ss": -55,
  "lon": -18.5333,
  "lat": 65.9667,
  "alt": 15.044444,
  "acc": 1,
  "res": 16337,
  "pub_date": "2015-12-01 23:13:52.639206"
}];
populateGraph(data);
/*
$.ajax({
  url: url,
  dataType: "json",
  success: function (data) {
    populateGraph(data);
  }
});
*/

function populateGraph(ret) {
  var ID = [];
  var Delay = [];

  for (i = 0; i < ret.length; i++) {
    // Save the data to the relevant array. Note how date at the zeroth  position (i.e. x-axis) is common for both demand and supply arrays.
    ID.push([ret[i].pub_date, ret[i].id]);
    Delay.push([ret[i].pub_date, ret[i].res]);
  }

  var plot1 = $.jqplot('chart1', [ID, Delay], {
    title: "Delay",
    axes: {
      xaxis: {
        renderer: $.jqplot.DateAxisRenderer,
        tickOptions: {
          formatString: '%d/%m/%Y'
        },
        label: 'Date'
      },
      yaxis: {
        label: 'Delay'
      },
      y2axis: {
        label: 'ID'
      }
    },
    series: [{
        yaxis: 'yaxis',
        label: 'ID'
      }, {
        yaxis: 'y2axis',
        label: 'Delay'
    }],
    highlighter: {
      show: true,
      sizeAdjust: 1
    },
    cursor: {
      show: false
    }
  });
};
});
Fraser Crosbie
  • 1,672
  • 1
  • 12
  • 21
  • I tried your code however this is also not working and I am getting the same result. I am using eclipse and placed my json file and all plugins in the project directory. Can you please point out why your code is not working in my environment. Also, I just noticed that my TomCat server is not running on eclipse and giving error. As I am not very much famillier, this question can be very basi but I really need to finish it. Please suggest... – Govind Dec 12 '15 at 05:00
  • 1
    @Govind adding working code now. Check back in a couple minutes. – Fraser Crosbie Dec 12 '15 at 05:05
  • @Govind The date will still need to be formatted correctly. – Fraser Crosbie Dec 12 '15 at 05:18
  • Thanks......first time I saw the graph feeling very good, however I provided the data just for the reference....can we directly fetch the data from the JSON file and plot the graph for two columns id and res.......... regarding the date, we can just remove it and plot the graph for id and res only (id on x axis and res on y axis)......Please help me on this – Govind Dec 12 '15 at 05:23
  • Can you please modify the code to fetch the data directly from JSON file and plot the graph only for ID vs Res.........Thanks a lot in advance – Govind Dec 12 '15 at 05:41
  • https://jsfiddle.net/9jk0jyvt/6/. I don't have access to the url for the ajax. I have left notes on what to comment and uncomment. – Fraser Crosbie Dec 12 '15 at 05:47
  • I am just close, I did what you sujested, however I am getting one error: "invalid location of tag(div)"......where should I put my div. currently I have put it at the end after the script ends. – Govind Dec 12 '15 at 06:00
  • You are missing your tags before the

    . Also, you have the scripts doubled up. You can delete the ones at the bottom of the page.

    – Fraser Crosbie Dec 12 '15 at 06:07
  • Also, I removed that error of misplacement and I am not yet able to plot the graph from my json file...........Could you please identify the issue. As I already referred that I am using eclipse and placed my json file and all plugins in the project directory. Can you please point out why your code is not working in my environment. Also, I just noticed that my TomCat server is not running on eclipse and giving error. Please suggest.... – Govind Dec 12 '15 at 06:09
  • I already added the tags and now I am not getting the error however I am still not getting the graph. – Govind Dec 12 '15 at 06:10
  • Sorry, I have no idea. You might want to ask a more specific question in another area related to TomCat and Eclipse. – Fraser Crosbie Dec 12 '15 at 06:11
  • Also when I tried to follow your notes on jsfiddle, I am not getting the graph as well.......... – Govind Dec 12 '15 at 06:12
  • Sorry, I am not asking about Tom Cat or eclipse......I am just worried why my json file is not being read by the script, so was speculating........please suggest in case I am missing something – Govind Dec 12 '15 at 06:13
  • Do you get the graph locally, with my working code in jsfiddle? Without using the ajax? – Fraser Crosbie Dec 12 '15 at 06:13
  • Yes..........I am getting the graph for data inserted in the code which you pasted earlier – Govind Dec 12 '15 at 06:17
  • Ok that is good. Your issue is now related to server stuff. Please mark this questions as answered and open a new, specific question about serving json data from an ajax request in TomCat. I do not have any knowledge with that. Good luck! http://stackoverflow.com/questions/20065126/big-json-data-to-java-restful-service-with-tomcat – Fraser Crosbie Dec 12 '15 at 06:20
  • did you try the last code with a remote json file on your machine? – Govind Dec 12 '15 at 06:22
  • I do not have a restful web service running on my machine. – Fraser Crosbie Dec 12 '15 at 06:24
  • I am just being worried whether my script reads the json file – Govind Dec 12 '15 at 06:31
  • Yes, it will work if you had a working restful web service to connect to. You can't load a .json file locally. Please read this and please mark this question as answered. http://stackoverflow.com/questions/18637418/trying-to-load-local-json-file-to-show-data-in-a-html-page-using-jquery – Fraser Crosbie Dec 12 '15 at 06:35
  • One last question, if I have a real server with some IP then can I test this and of yes the what url I should put – Govind Dec 12 '15 at 16:44
  • If you provide me with a working url I can get this working for you. – Fraser Crosbie Dec 12 '15 at 16:49
  • my server IP is 172.26.50.253 and I have kept the json file at say /var/log/mc_measurementnew1.json...........the server is in a VPN so you cant access it but can you please suggest what changes I should make..... – Govind Dec 12 '15 at 17:10
  • my working url is: "http://http://172.26.50.232/mc_measurement_new1.json" and I can get the data from browser but this is not working when I try this in the code. The server is on a VPN.....any insights please – Govind Dec 12 '15 at 20:48
  • I could not get the URL to work. I do not think it is open outside of your network. – Fraser Crosbie Dec 12 '15 at 21:31
  • you are right sir, its a server in the vpn which I can only access if I am connected to internal network via VPN...........can you please look into the below ajax code to make sure I am doing it right: $(document).ready(function() { $.ajax({ url: "http://172.26.50.232/mc_measurement_new1.json", type: "GET" dataType: "jsonp", crossDomain:true, contentType:'application/json; charset=utf-8', success: function (data) { populateGraph(data); } }); – Govind Dec 12 '15 at 21:41
  • What does your console say when you load the data? Any errors? If you put a breakpoint in the success function does you application every hit it? Also add an error method to your Ajax method so you can output errors – Fraser Crosbie Dec 12 '15 at 21:58
  • The console doesn't output any error and neither I am getting any success or error – Govind Dec 12 '15 at 22:17
  • Also, when I tried this url from my eclipse browser, i can get the data.....so definitely our Ajax method is not working properly.........can you please suggest – Govind Dec 12 '15 at 22:22
  • I think your going to have to get some help from someone in person. – Fraser Crosbie Dec 12 '15 at 22:37
  • Not possible, as no one around me knows how to code in javascript and also as I am from a different background I even can't do much in coding....thats why was seeking help..........I think we are very close but we are missing something very important......... – Govind Dec 12 '15 at 22:40
  • So if you use this full url. You don't get into the success or error functions? http://jsonplaceholder.typicode.com/posts – Fraser Crosbie Dec 12 '15 at 22:44
  • Also try replacing your Ajax code with this: var root = 'http://jsonplaceholder.typicode.com'; $.ajax({ url: root + '/posts/1', method: 'GET' }).then(function(data) { console.log(data); }); – Fraser Crosbie Dec 12 '15 at 22:50
  • my updated Ajax method is: $.ajax({ async: false, url: 'http://jsonplaceholder.typicode.com/posts', type: "GET" dataType: "jsonp", contentType:'application/json; charset=utf-8', success: function (data) { alert("Local success callback."); }, error: function (err) { alert("Local error callback."); }, complete: function (status) { alert("Local completion callback."); } // populateGraph(data); } }); I am not getting any thing out of it...........am I doing something wrong//// – Govind Dec 12 '15 at 22:53
  • I don't know whether I am right but when I closely observer my json data, it does not mention "data=" as you have mentioned when you directly pasted the data in the code (data=...)........and we are mentioning data in our success function............my json file directly starts with: [ { "id":1, "essid":"\"WiredSSID\"", "mac":"08:00:27:b1:3e:4d", "ip":"10.0.3.15", "ss":-55, "lon":-18.5333, "lat":65.9667, "alt":15.044444, "acc":1, "res":18058, "pub_date":"2015-12-01 22:39:07.700953" }, No "data=" is there.............is it the right way? – Govind Dec 12 '15 at 23:06
  • Simplify your Ajax call to be exactly what I gave you above. You json is correct. The data = is just for assigning it to a variable. Your probably have a CORS issue with your server. But you should have no issue loading data from the url above. – Fraser Crosbie Dec 12 '15 at 23:10
  • You are using Chrome with the developer tools open, correct? – Fraser Crosbie Dec 12 '15 at 23:14
  • tried you suggestion of replacing my Ajax with new one but that didn't work either........also, I read at "http://techblog.constantcontact.com/software-development/using-cors-for-cross-domain-ajax-requests/", Ajax avoids the CORS or we can say JSONP passes the security test and avoids CORS. Isn't it right....... – Govind Dec 12 '15 at 23:22
  • I am executing my code in eclipse.........running my html file in eclipse browser – Govind Dec 12 '15 at 23:24
  • You need to use chrome with the developer tools open. That is your only hope debugging any JavaScript issues you have – Fraser Crosbie Dec 12 '15 at 23:25
  • I am getting "Failed to load resource: net::ERR_NAME_NOT_RESOLVED" and "GET http://new%2030/ net::ERR_NAME_NOT_RESOLVED".........these are the two error I am getting when debugging my script in developers tools of chrome. – Govind Dec 13 '15 at 00:00
  • @Govind http://superuser.com/questions/719559/why-cant-chrome-load-a-web-page-err-name-not-resolved – Fraser Crosbie Dec 13 '15 at 00:02
  • Finally I managed to do it somehow, Just started my tomcat in eclipse and placed the json file on my project directory and checked the indentations (I dont know whether this made any difference) and then ran my script and it worked. Thanks a lot for your patience and support.....I learnt a lot while working with you on this project..........5 stars for your.............. – Govind Dec 13 '15 at 01:18
  • Thanks, now I just want to make a drop down list which signifies the list of areas for example area 1 and area 2 etc and each area will refer to a some latitude and longitude pairs and then I want to plot my graph for each area for res vs pub_date so that we come to know the trend of res in a particular area......any idea how to do that? – Govind Dec 13 '15 at 04:30
  • I need a small help from you on this old issue. I am facing issues while parsing the value of pub_date in my jquery. Much appreciated in advance – Govind Nov 22 '16 at 08:34