JavaScript mode and MySQL query

Hi, I have the following question. I have a MySQL database which i work with using PHP. I can use JavaScript and AJAX to retrieve some info from the database, but I would like to then use the this data to draw things.

Is there a way to this? To transfer info from the database to a processing sketch?

Tagged:

Answers

  • I guess this is something, I have to look into, right?

    http://processingjs.org/articles/PomaxGuide.html#more

  • If you know JavaScript, you can try out p5.js instead of pjs (JS Mode) framework.

  • edited June 2015

    Could you please explain how this would be better?

    After having looked through some tutorials. If I use p5.js, I won't need to transfer anything to processing.js, right? I can just write using JavaScript + use the p5 library to draw whatever I want?

  • From my experience you can have pure JavaScript tabs in pjs so that might still be an option.

    Either way just set up a php page that can query your dbase and return the data you want to draw with, in a sensible format (e.g. json). It might even accept parameters to select appropriate data...

    Then write JS in your sketch setup to make an ajax request to the php page, passing any necessary parameters. You'll probably have to add a condition to draw in order to wait for the ajax request to compete before proceeding: nothing worse than trying to use data that isn't there yet! An ajax request usually includes a callback function on success: use this to parse the data into your sketch and then set the sketch running...

    • Both p5.js & pjs are JavaScript frameworks.
    • However pjs can also transpile code written in "Java Mode" into JavaScript, while p5.js can't.
    • Since you're gonna need AJAX & MySQL, you're better off writing everything in JS.
    • p5.js is more web integrated, so it's a better choice. Of course, pjs is as capable as p5.js.
    • And if you need WebGL canvas, currently only pjs has stable support for that at this moment.
    • p5.js's WebGL support is at its infancy right now.
  • Sorry just realised you said you could do the ajax... So the problem is presumably parsing the data. Seeing as I'm likely to need something along these lines using PJS I thought I'd throw together a proof of concept:

    Main sketch - mostly written in 'Java'

    // the type declaration in JS Mode is a bit of a sham:
    // declare this variable to whatever type you like.  From
    //  what I've seen when it's running, the JS will coerce it
    // to do it's bidding...
    Object data; 
    Boolean runSketch = false;
    
    void setup() {
    
      getJson.parseData("https://api.github.com/users/blindfish3/repos", dataIsReturned);
    
    }
    
    void draw() {
      // waiting for ajax request to complete
      if(runSketch) {
       // now ready to do stuff with the data!
      }
      noLoop();
    }
    
    void dataIsReturned(Object inputData) {
       data = inputData;
    
       // Look at what your data returns and access it just as it appears:
       // an array of objects
       console.info(data[1].name);
       // you may occasionally have to use this notation - e.g. in case 
       // of spaces and special characters...
       console.info(data[1]["html_url"]);
       // the full object for reference
       console.info(data); 
    
       runSketch = true;
    }
    

    On a separate tab: getjson.js

    // code modified from:
    // https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
    
    var getJson = (function() {
    
      var httpRequest; 
    
      function makeRequest(url, callback) {
    
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
          httpRequest = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // IE
          try {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
          } 
          catch (e) {
            try {
              httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (e) {}
          }
        }
    
        if (!httpRequest) {
          alert('Giving up: Cannot create an XMLHTTP instance');
          return false;
        }
        httpRequest.onreadystatechange = callback;
        httpRequest.open('GET', url);
        httpRequest.send();
      }
    
      function getData() {
    
        var data ="";
        if (httpRequest.readyState === 4) {
          if (httpRequest.status === 200) {
            data = httpRequest.responseText;
          } else {
            data = 'There was a problem with the request.';
          }
        }
        return data;
      }
    
      function parseData(url, callback) {
    
        makeRequest(url, function() {
    
            var data = getData();
            data = JSON.parse(data);
            callback(data);
        });
    
      }
    
      return {
        parseData : parseData
    
      }
    
    })();
    

    This code is not my proudest moment :\">

    In the past I spent far too much time playing with jQuery and not learning proper JavaScript; so Ajax requests still don't come entirely naturally to me. It can obviously be improved but it serves its purpose here. Hit F12 > console to see the output.

    The key point is that there's a method that returns the parsed JSON data back to the sketch code. You can then pull the data values out as if from an array of objects using array/dot notation. The Java mode doesn't have to know that none of that arduous Class declaration has taken place ;)

    Note that IIRC the .js extension on the tab is the prompt to the parser to treat the code as pure JS and not try and validate it as Java...

    Like I said: this can be improved and there are a couple of errors being thrown that I'm not entirely happy about; but it runs...

  • Thanks for your help, I need some time to look into the code:)

    As for WebGL - I looked it up, and it seems to be an overkill for me, I only need to draw circles and simple shapes at the moment, and it seems, p5.js is capable of that, right?

  • No worries, though as I said the code isn't great: I wouldn't rely on it before I'd refactored it some more. The key method is parseData. Anyway, I'll be revisiting this code some time soon and will post any improvements.

    As for p5.js here's a demo and a description ;)

  • edited June 2015

    Ok, after some consideration, I had to simplify the code ... to the extent that it doesn't seem to work, but still:

    This is how my sketch.js looks like

    var oReq = new XMLHttpRequest();
    var radius = 0;
    
    oReq.open("get", "planetArequest.php", true);
    oReq.send();
    
    oReq.onload = function() {
    
      alert("radius is  " + this.responseText);
      radius = this.responseText;
    };
    
    
    function setup() {
      createCanvas(800, 800);
    }
    
    function draw() {
      { 
        ellipse(100, 200, radius, radius);
      }
    

    The program never gets to function setup ... Which is something I don't get.

  • Ok, rewrote as suggested in the reference:

    var radius;
    function preload() {
      var url = 'http://localhost/planetArequest.php';
      radius = loadJSON(url);
    }
    
    function setup() {
      noLoop();
    }
    
    function draw() {
      background(200);
      // get the humidity value out of the loaded JSON
      textSize(32);
      text(radius, 10, 30);
      fill(0, 102, 153);
    
    
    }
    

    This one works.

  • edited June 2015

    Ok, now I a, stuck again. My php script json_encodes this:

    [{"x":"20","y":"24","name":"NewNovgorod"},{"x":"20","y":"70","name":"Tito"}]
    

    But I can't see how I can extract this information in my p5.js program? Say, I need to use those x, y, name to draw a circle with in the appropriate place with the right name.

    I used loadJSON in the script, and now I have a variable -

    data = loadJSON()

    But how do I get, say, the 'x' component from the JSON?

  • Answer ✓

    First check you're getting parsed data: console.log(data);

    In chrome you should be able to navigate the data structure via the console. If it just outputs a string, try data = JSON.parse(data);

    Now look at the notation of what you output. [square brackets] represents an array, in this case containing two {objects}. So get at each object as you would any item from an array and then get at the object's values as you would get the property from any object. Code helps to clarify here:

    var foo = [{"x":"20","y":"24","name":"NewNovgorod"},{"x":"20","y":"70","name":"Tito"}];
    console.info(foo);
    console.info(foo[0]);
    console.info(foo[0].name, foo[0].x, foo[0].y);
    
  • Thanks, that helped!

  • edited June 2015 Answer ✓

    In order to make things less tiresome, a for...of () loop is very handy: \m/

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

    const myJSON = [ 
      { "x":"20", "y":"24", "name":"Titus" },
      { "x":"20", "y":"70", "name":"Caius" },
      { "x":"30", "y":"65", "name":"Sophia" }
    ];
    
    for (var entry of myJSON)  console.log(entry.name, entry.x, entry.y);
    
  • Answer ✓

    Note that this suggested syntax is not supported by IE... Of course you can loop over the array, but better to use a standard for loop if you plan to put this online for public consumption ;)

Sign In or Register to comment.