1

i am making a website that needs to change a embedded video when a button is clicked. My html page loads a js script that needs to call a function in the database which was coded with node. The whole thing is running on a mongoDB server with mongoose to back me up. To make things more clear here is some code:

My database (only the relevant functions):

function database(){

    db = mongoose.createConnection(url);
    songModel = db.model('Song',{id : Number ,
        title : String,
        artist : String,
        genre : String,
        rating : Number,
        link : String
    });
    //init freeid
    songModel.count({},function(err, c){
        nextFreeId=c;
    });

};
database.prototype.getNextFreeId = function(){
    return nextFreeId;
};
database.prototype.getSongById=function(id2){


    songModel.findOne({id : id2}, function(err,obj){
        if (err) {
            console.log('Not Found, error: '+err);
            return null;
        } else if (obj) {
            console.log('Found:', obj);
            return obj;
        }
    });
};
module.exports = database;

Now i need to call a script via my html page that is able to call the getSongById(someID). How should i be doing that knowing i can't require(database) because require is node and server based. Also since getSongById(someID) is asynchronous because of the save call how do i make sure the return value is not null? Do i need to timeout a couple of secs?

The script file would need to be something like this and the html page loads getRandomVideo() :

var db=require('./module/database');
function getRandomVideo(){
    console.log('random video method called');
    var numberOfSongs = db.getNextFreeId()-1;
    idToGet=Math.floor(Math.random() * numberOfSongs);
    var song = db.getSongById(idToGet);
    document.getElementById('myVideo').src = song.link;
    console.log('found random song: '+ song);
}

Thanks you for the help!

1
  • I don't find it worthwhile to answer questions like this, so just in short - make your class event driven, eg. using EventEmitter2. Then make it an interface and implement it differently for server and client. So that client calls db.getSongById(666, (result)=>{}) where (result)=>{} is callback that handles the result once it comes from the server. This is how it's properly done. Commented Apr 18, 2016 at 12:59

1 Answer 1

1

Create a route to your getSongById() function in node and then, from your html file make an ajax request to that url.

Let's say, in your app.js, have something like:

app.get('/random-video', function(req, res) {
    console.log('random video method called');
    var numberOfSongs = db.getNextFreeId()-1;
    idToGet=Math.floor(Math.random() * numberOfSongs);
    db.getSongById(idToGet, function(err, song){
       console.log('found random song: '+ song);
       res.send(JSON.stringify(song));
    });    
});

You'll also have to modify your getSongById() function to be async, like:

database.prototype.getSongById=function(id2, cb){


    songModel.findOne({id : id2}, function(err,obj){
        if (err) {
            console.log('Not Found, error: '+err);
            cb(err);
        } else if (obj) {
            console.log('Found:', obj);
            cb(null, obj);
        }
    });
};

Then, in your html page, once you have jQuery loaded, do something like:

<script>
$(document).ready(function(){
   $.ajax({
        url: '/random-video',
        contentType: 'application/json; charset=utf-8',
    }).done(function(song){
       //do stuff with the song
    });
})
</script>
Sign up to request clarification or add additional context in comments.

6 Comments

Thats seems to be the way to go! However i never use ajax, what's the syntax to make a ajax request?
Very weird thing happening i am calling this function from the html page: pastebin.com/BcTXbAXu . Thing is the video displayed on my page suddenly displays the error message i supplied in my app.use () instead of changing it to the link. via the logs i know that responseText is the correct link and if i just call this via html ( pastebin.com/iRbFr5Us ) it works perfectly. Don't kow what to think really
Any ideas? For some reason when i call document.getElementById('myVideo').src it does a get request to the server on something like localhost:8080/%22https://www.youtube.com/embed/BfOdWSiyWoc%22
you should create a separate question for this and provide more context, like for example, how is your HTML looking.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.