20i Reseller Hosting

Any Javascript Ninjas ?

Discussion in 'Scripts and Coding' started by dee, Feb 22, 2018.

  1. dee

    dee Well-Known Member Acorn Supporter

    Joined:
    May 2013
    Posts:
    1,266
    Likes Received:
    127
    Hi All,

    I tried to sort this ages ago but never did so getting back to it. Basically.... i'm trying to pass the track name from a soundcloud widget to a php mail script. Now within the html page I know the variable is defined as I can alert it fine and it shows correctly. However, ive tried a few thing to pass to a php mail script (the mailer works fine) but it always comes out as 'undefined' on the mail itself , so its not passing.I'm not a coder at all really so it's all done by search and working out, but i'm guessing it has something to do with scope. I thought if i defined the variable outside a function it makes it global ? But its not working.

    Anyhoo.... here's what i have for the initial load page

    HTML:
    //i frame embed of track
    
    <iframe id="sc-widget" width="100%" height="450" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=track url here"></iframe>
    
    
    // load api from soundcloud
    <script src="https://w.soundcloud.com/player/api.js" type="text/javascript"></script>
    
    <script type="text/javascript">
    
    // define var for sending
    var trackName;
    
    (function(){
        var widgetIframe = document.getElementById('sc-widget'),
            widget       = SC.Widget(widgetIframe);
    
          widget.bind(SC.Widget.Events.READY, function() {
          widget.bind(SC.Widget.Events.PLAY, function() {
             
            // get information about currently playing sound
            widget.getCurrentSound(function(currentSound) {
             trackName=currentSound.title;
                alert(trackName);
            });
    
     });
    The alert works fine. I had then tried passing the variable as a 'post' parameter to the mailer script but comes out as undefined. Any pointer greatly appreciated.
     
  2. Domain Forum

    Acorn Domains Elite Member

    Joined:
    1999
    Messages:
    Many
    Likes Received:
    Lots
     
  3. seemly

    seemly Well-Known Member

    Joined:
    Feb 2011
    Posts:
    1,189
    Likes Received:
    168
    It's going to be worth posting all the relevant code.
     
  4. RobM

    RobM Well-Known Member Exclusive Member

    Joined:
    Mar 2012
    Posts:
    2,073
    Likes Received:
    236
    Need to see all the code. However do you need a global variable? You could just do: return trackname; That would return the trackname whenever the function is called and you can then plug that value into other functions.
     
  5. dee

    dee Well-Known Member Acorn Supporter

    Joined:
    May 2013
    Posts:
    1,266
    Likes Received:
    127
    You are of course right. I should have. Sorry. As i say.... i apologise to any actual coders who read this :)

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <title></title>
        </head>
        <body>
            <iframe id="sc-widget" width="100%" height="450" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=song url here"></iframe>
    
    
    <script src="https://w.soundcloud.com/player/api.js" type="text/javascript"></script>
    
    <script type="text/javascript">
    var trackName;
    
    (function(){
        var widgetIframe = document.getElementById('sc-widget'),
            widget       = SC.Widget(widgetIframe);
    
        widget.bind(SC.Widget.Events.READY, function() {
          widget.bind(SC.Widget.Events.PLAY, function() {
            
        
            // get information about currently playing sound
            widget.getCurrentSound(function(currentSound) {
              var trackName = currentSound.title;
                alert(trackName);
            });
    
     });
    
    //call get request for php mail
    getOutput();
    
    
          // get current level of volume
          widget.getVolume(function(volume) {
            console.log('current volume value is ' + volume);
          });
          // set new volume level
          widget.setVolume(1.0);
          // get the value of the current position
    
        });
    
    
    
    
    
    // handles the play event for link
    function getOutput() {
    
    getRequest(
          'track.php?v='+ trackName, // URL for the PHP file
           drawOutput,  // handle successful request
           drawError    // handle error
      );
      return false;
    } 
    // handles drawing an error message
    function drawError() {
        var container = document.getElementById('output');
        container.innerHTML = 'error!';
    }
    // handles the response, adds the html
    function drawOutput(responseText) {
        var container = document.getElementById('output');
        container.innerHTML = responseText;
    }
    // helper function for cross-browser request object
    function getRequest(url, success, error) {
        var req = false;
        try{
            // most browsers
            req = new XMLHttpRequest();
        } catch (e){
            // IE
            try{
                req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                // try an older version
                try{
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                    return false;
                }
            }
        }
        if (!req) return false;
        if (typeof success != 'function') success = function () {};
        if (typeof error!= 'function') error = function () {};
        req.onreadystatechange = function(){
            if(req.readyState == 4) {
                return req.status === 200 ?
                    success(req.responseText) : error(req.status);
            }
        }
        req.open("GET", url, true);
        req.send(null);
        return req;
    }
    
      }());
    </script>
        </body>
    </html> 
    so get output passes a url parameter to the php mailer (which all seems to work other than trackName (v parameter) comes out as 'undefined' in mail
     
  6. RobM

    RobM Well-Known Member Exclusive Member

    Joined:
    Mar 2012
    Posts:
    2,073
    Likes Received:
    236
    Put
    var trackName;
    below the function declaration.
    (function(){
    ...

    However that variable will cease to exist when that function has finished loading and it doesn't appear anything else is contained within it. *edit* counting the brackets :p
     
  7. dee

    dee Well-Known Member Acorn Supporter

    Joined:
    May 2013
    Posts:
    1,266
    Likes Received:
    127
    This is where my 'cobble' together from seearch ends. I'm trying to learn all this stuff. I was trying to get my head round scope.... obviously didnt work.
     
  8. RobM

    RobM Well-Known Member Exclusive Member

    Joined:
    Mar 2012
    Posts:
    2,073
    Likes Received:
    236
    Yes you can't actually return a variable - I was being too hasty forgot that the
    (function(){
    ...}());
    was actually the declaration that the whole thing should be run as soon as it is created.
     
  9. dee

    dee Well-Known Member Acorn Supporter

    Joined:
    May 2013
    Posts:
    1,266
    Likes Received:
    127
    So i cant pass that var ?
     
  10. dee

    dee Well-Known Member Acorn Supporter

    Joined:
    May 2013
    Posts:
    1,266
    Likes Received:
    127
    See this is were im out of my depth. Even if call getOutput() at the same point as the alert (where I know the variable is set correctly) is comes out as undefined. Thats why i figured it had something to do with the scope of the variable.
     
  11. RobM

    RobM Well-Known Member Exclusive Member

    Joined:
    Mar 2012
    Posts:
    2,073
    Likes Received:
    236
    var trackname is declared outside the whole function so when you call getoutput it doesn't exist.
    You need to either move
    var trackName;
    to inside the function ie after the line
    (function(){

    or, if you are running in strict mode, you will have to actually *pass* the variable into the function:
    ie
    change
    getOutput();
    to
    getOutput(trackname);

    and then change the line
    function getOutput() {
    to
    function getOutput(trackname){
     
  12. RobM

    RobM Well-Known Member Exclusive Member

    Joined:
    Mar 2012
    Posts:
    2,073
    Likes Received:
    236
    Basically trackname is not global and the function getoutput references the local value (ie 'undefined' whilst in the function).
    The above post is the 2 ways around that problem.
     
  13. dee

    dee Well-Known Member Acorn Supporter

    Joined:
    May 2013
    Posts:
    1,266
    Likes Received:
    127
    tried moving var trackName inside the function and didnt work. Ill try the other stuff (is that what a 'callback' ? is )

    thanks for taking the time Rob. Appreciated.
     
  14. RobM

    RobM Well-Known Member Exclusive Member

    Joined:
    Mar 2012
    Posts:
    2,073
    Likes Received:
    236
    Don't copy/paste because I haven't used camel case :p
    ie trackname should actually be trackName
     
  15. dee

    dee Well-Known Member Acorn Supporter

    Joined:
    May 2013
    Posts:
    1,266
    Likes Received:
    127
    @RobM

    I love you and want to have your babies. It worked !!!! Thank you.
     
    • Like Like x 1
    • Funny Funny x 1
  16. dee

    dee Well-Known Member Acorn Supporter

    Joined:
    May 2013
    Posts:
    1,266
    Likes Received:
    127
    Thats brilliant. Thanks Rob. Think I get it aswell. Didn't know you could pass variable to out side a function like that by including in brackets
     
  17. RobM

    RobM Well-Known Member Exclusive Member

    Joined:
    Mar 2012
    Posts:
    2,073
    Likes Received:
    236
    You pass the variable *into* the function:
    eg runMe(value);
    and then inside the function you can use value

    However you return a value *out* of the function:
    eg var ans=runMe();

    function runMe()
    {
    var t='hello';
    return t;
    }

    You can run both together

    eg
    var ans=multiply(2,3);

    function multiply(a,b)
    {
    var c=a*b;
    return c;
    }

    It's actually good practice to consider all variables as being local so they have to be passed into functions and returned out.
    If you use global variables you can run into problems - eg some are running javascript in strict mode and they won't work or they run the risk of getting altered and/or corrupted before being used.
     
    • Like Like x 1
    Last edited: Feb 22, 2018