Enjoy unlimited access to all forum features for FREE! Optional upgrade available for extra perks.

Any Javascript Ninjas ?

dee

Joined
May 8, 2013
Posts
2,594
Reaction score
906
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.
 
It's going to be worth posting all the relevant code.
 
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.
 
It's going to be worth posting all the relevant code.

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
 
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
 
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.

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.
 
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.
 
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.

So i cant pass that var ?
 
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.
 
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){
 
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.
 
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){

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.
 
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
 
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.
 
Last edited:

The Rule #1

Do not insult any other member. Be polite and do business. Thank you!

Featured Services

Sedo - it.com Premiums

Sponsors

IT.com

Premium Members

AucDom
UKBackorder
Be a Squirrel

Sponsors

Acorn Domains Merch
MariaBuy Marketplace

Shiny Nuts

Perfect
Service
Laskos
URL Shortener
*the exceptional businesses of our esteemed moderators
Top Bottom