Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Javascript help needed (returning the value from MySQL in a function)
New on LowEndTalk? Please Register and read our Community Rules.

All new Registrations are manually reviewed and approved, so a short delay after registration may occur before your account becomes active.

Javascript help needed (returning the value from MySQL in a function)

KuJoeKuJoe Member, Host Rep

So I'm in the process of coding something in Node.js and I've hit a wall when it comes to MySQL and functions... I am unable to get the function to return a value other than "undefined".

Here's the function: https://gist.github.com/anonymous/c0f09428a4d1832f67738f83606949e6

Here's the code I'm using to call the function:

var msg = getQuote(); console.log(msg);

And here's the output to console:

3 undefined 4 <correct value>

I added console.logs 1-4 to see where the "undefined" error was occuring and I left the 3 and 4 outputs for my own reference. I tried using JSON.stringify with no luck. I can get the script to output the correct value within the function but I cannot get it to return the value to the code calling the function. Thoughts on where I'm going wrong? Any insight is appreciated since I am a complete Javascript newb and Google is failing me.

«134

Comments

  • Is that var declared only in your local scope?

  • KuJoeKuJoe Member, Host Rep

    @WSS said:
    Is that var declared only in your local scope?

    I understood some of those words. :D That variable is only declared within that function.

  • OK. console.log(getQuote()) works?

  • KuJoeKuJoe Member, Host Rep

    @WSS said:
    OK. console.log(getQuote()) works?

    Negative.

  • You're mixing synchronous and asynchronous code. The query is asynchronous, so you can't just return the value: you'd need to do that as a callback.

    Thanked by 1WSS
  • How are you returning from getQuote()?

  • @fusl is proficient in node I believe

  • KuJoeKuJoe Member, Host Rep

    @Detruire said:
    You're mixing synchronous and asynchronous code. The query is asynchronous, so you can't just return the value: you'd need to do that as a callback.

    No clue what this means. Can you give me an example or point me to some documentation I can read?

    WSS said: How are you returning from getQuote()?

    I'm trying to use the "return ;" function like in PHP, according to the Google it should also work. :D

  • KuJoeKuJoe Member, Host Rep

    Detruire said: The query is asynchronous

    Also how would I make it synchronous?

  • WSSWSS Member
    edited September 2017

    You're going to want to callback(msg) within your function getQuote(), but I strongly suggest renaming it.

    @KuJoe said:
    I'm trying to use the "return ;" function like in PHP, according to the Google it should also work. :D

    Depends on what and how. I had assumed you were just returning an array of data but Detruire nailed it while I was still looking for something silly.

  • It is not possible to directly query mysql with javascript.

    Either you need to use a node module that supports this https://github.com/mysqljs/mysql plus tutorial https://www.sitepoint.com/using-node-mysql-javascript-client/.

    Remember if you go this route you need to transpile this using babel since it is es6 otherwise it may not work properly.

    Your other option is use ajax.

  • @KuJoe Node is very different from PHP. The concepts of asynchronous code (callbacks, promises, async/await) and scope (closures) are extremely important for JavaScript development.

    Thanked by 1Sven
  • @Farish said:
    It is not possible to directly query mysql with javascript.

    Either you need to use a node module that supports this https://github.com/mysqljs/mysql plus tutorial https://www.sitepoint.com/using-node-mysql-javascript-client/.

    Remember if you go this route you need to transpile this using babel since it is es6 otherwise it may not work properly.

    Your other option is use ajax.

    I'm guessing that you only read the title.

  • raindog308raindog308 Administrator, Veteran

    Farish said: It is not possible to directly query mysql with javascript.

    Either you need to use a node module that supports this https://github.com/mysqljs/mysql plus tutorial https://www.sitepoint.com/using-node-mysql-javascript-client/.

    I think this is implied in the '...' at the start of the excerpt.

  • KuJoeKuJoe Member, Host Rep

    Farish said: It is not possible to directly query mysql with javascript.

    The MySQL part itself is working fine, it's the function return that is not.

    Detruire said: Node is very different from PHP.

    I agree 100%. :)

  • KuJoeKuJoe Member, Host Rep
    edited September 2017

    WSS said: You're going to want to callback(msg) within your function getQuote(), but I strongly suggest renaming it.

    The function has been renamed. I tried replacing "return msg.quotes;" with "callback(msg.quotes);" but I get:

    ReferenceError: callback is not defined

  • I didn't literally mean to call callback() as it stands. You're going to need to set it up to pass back through your function. This should help you: http://callbackhell.com/

  • JonchunJonchun Member
    edited September 2017

    You want to use promises for synchronous js:

    https://developers.google.com/web/fundamentals/getting-started/primers/promises
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

    What @WSS means with callbacks is to setup a callback function. In your case:

    instead of:

    var msg = getQuote();
    console.log(msg);
    

    You want something like this instead:

    function getQuote( cb ) {
        ...
        // return msg.quotes;
        cb( msg.quotes );
    }
    
    function getQuoteCB( msg ) {
      console.log( msg );
    }
    
    getQuote( getQuoteCB );
    
  • @doghouch said:

    @Farish said:
    It is not possible to directly query mysql with javascript.

    Either you need to use a node module that supports this https://github.com/mysqljs/mysql plus tutorial https://www.sitepoint.com/using-node-mysql-javascript-client/.

    Remember if you go this route you need to transpile this using babel since it is es6 otherwise it may not work properly.

    Your other option is use ajax.

    I'm guessing that you only read the title.

    I had read this from the op

    So I'm in the process of coding something in Node.js and I've hit a wall when it comes to MySQL and functions... I am unable to get the function to return a value other than "undefined".

    The gist gives very limited information. It basically says here is my function assume everything is setup correctly. The error could be as simple as the mysql driver not being setup.

    It is also possible this is happening because the function is returning the value before it gets the data from the server. This is why for these situations an asynchronous function is used such as a promise. It will not return the data until it gets it from the server first.

    I am use to doing api calls not a direct query with mysql so I am not sure if this is the proper setup. I am just using what the gist is giving me and my limited knowledge in mysql queries.

      function getQuote() {
      return new Promise(function(resolve, reject) {
    
        var con = mysql.createConnection({
          host: cfg.host,
          user: cfg.user,
          password: cfg.password,
          database: cfg.database
        });
    
        var query_string =
          "SELECT quote, " + "FROM quotess " + "Order BY RAND() " + "LIMIT 1 ";
    
        con.query(query_string, function(err, rows, fields) {
          if (err) {
            return reject(err);
          }
          resolve(rows);
        });
      });
    }
    
    getQuote()
      .then(function(rows) {
        console.log(rows);
      })
      .catch(err => {
        console.log(err);
      });
    
  • KuJoeKuJoe Member, Host Rep

    Farish said: The gist gives very limited information. It basically says here is my function assume everything is setup correctly.

    Yes, everything else is setup correctly. I excluded all of the other code because it was not relevant to the problem I was having and I didn't want to confuse anybody with unnecessary code. My goal of this thread was to make things as easy as possible for the people willing to help me so I kept it as brief as possible. Hopefully that makes sense. :)

  • CConnerCConner Member, Host Rep

    @Farish the promise is a bit unnecessary in this case, but that should work.

  • @CConner said:
    @Farish the promise is a bit unnecessary in this case, but that should work.

    Promises makes code more cleaner and debuggable. Promises are way better than callback hell

    @KuJoe : I hope you know the difference between synchronous and asynchronous code. Will try to explain it anyway

    Consider you are preparing Cake and you don't have milk and Sugar.

    Visiting store and getting them yourself and then preparing Cake is synchronous. You do it one after the other.

    Instead you remember that you have help (MySQL in your case). Now begin asynchronous
    1. You ask Helper to get Milk and Sugar
    2. Helper leaves your home
    3. You are waiting for Helper to return
    4. Helper returns with items(data) and say do ne
    5. You resume cooking

    What you are doing is trying to use data before Helper has returned and hence getting undefined. And getting proper data after Helper has returned.

    Hope this helps.

  • @KuJoe said:

    @Detruire said:
    You're mixing synchronous and asynchronous code. The query is asynchronous, so you can't just return the value: you'd need to do that as a callback.

    No clue what this means. Can you give me an example or point me to some documentation I can read?

    WSS said: How are you returning from getQuote()?

    I'm trying to use the "return ;" function like in PHP, according to the Google it should also work. :D

    it means unlike php, the script wont wait getQuote() function to complete. it immediately execute the next script, which is console.log(msg)

    if getQuote() is an async function, you need to execute the console.log(msg) after the getQuote() script finished using callback. I believe node.js is based on heavily async functions. Almost every function has a callback.

  • KuJoeKuJoe Member, Host Rep

    Thanks all but it looks like I'll just abandon this for now. I'm not able to wrap my head around this so I'll look at writing my project in another language more beginner friendly. It's a shame to because everything else up to this point has been extremely easy but adding a database into the mix is just to advanced for my brain right now. :(

  • Use ajax

  • KuJoeKuJoe Member, Host Rep

    @LTniger said:
    Use ajax

    This might be a good suggestion for others, just not for me.

  • jackbjackb Member, Host Rep

    @LTniger said:
    Use ajax

    This is node (serverside); not trying to load database results from client side.

  • Developing in Node requires a paradigm shift for someone who's used to writing PHP. It definitely takes some getting used to.

    As a general rule, IO is asynchronous with JavaScript... but most other things are not. This means that your code context switches and runs something else while waiting for the response.

    If you've ever used $.ajax() with jQuery, you should have encountered this concept before: make the request, wait for the response, then run a function. It just seems to make more sense with a slow (internet) HTTP request than with a fast (local) database request.

  • Yea I also went from PHP to Node and found things like this extremely complicated, to the point where I gave up as well.

  • hostnoob said: extremely complicated

    Try Cobol, Go. Then you will know what is complicated. Every new programming language requires a time investment to learn. Node.js is not complicated, it just needs that you forget PHP and actual learn node from "Hello world". Do not compare it.

Sign In or Register to comment.