mkyong
mkyong

Reputation: 12947

Automatically Creating Objects Pulled From Database in Javascript

Here's what I'm trying to do. I'm trying to pull data from a database and create a new user and continue to check every second for new users and changes in previous users' location (I'm tracking GPS using an Android app). I need to be able to create a new instance each time a new user is added to the DB, but I'm not sure how to do this. I've seen examples like below, but the objects are defined within the program and aren't created 'automatically.'

function cat(name) {
this.name = name;
this.talk = function() {
    alert( this.name + " say meeow!" )
    }
} 

cat1 = new cat("felix")
cat1.talk() //alerts "felix says meeow!"

cat2 = new cat("ginger")
cat2.talk() //alerts "ginger says meeow!"

Let's say I wanted to pull the cat's name from a database and check for new ones each second. I would have a php program that pulls and returns it to this JS program as JSON, but how do I instantiate a new 'cat' by using a function? Any help would be greatly appreciated. Thanks!

Upvotes: 0

Views: 224

Answers (2)

nnnnnn
nnnnnn

Reputation: 150080

I'm not going to overcomplicate this with long-polling or anything - for the sake of getting you started I'll just assume you can use setTimeout() to check for new users every thirty seconds or something. Sticking with your existing cats() constructor you could do something like this:

var cats = [];

function checkForNewCats() {
   $.ajax({
      url: "getcats.php",
      data : { lastCat : (cats.length == 0 ? "" : cats[cats.length-1].name) }
   })
   .done(function(data) {
      $.each(data, function(i, val) {
         cats.push(new cat(val.name));
      });
   })
   .fail(function() {
      alert("Something went horribly wrong");
   })
   .always(function() {
      setTimeout(checkForNewCats, 30000);
   });   
}

checkForNewCats();

So that includes an array cats to hold all the objects, and then a function that repeatedly makes an ajax request a couple of times a minute to check for new cats and add them to the array.

This assumes that the JSON returned by the PHP is an array of cat objects something like:

[
  { "name" : "fluffy" },
  { "name" : "sneezy" },
  { "name" : "ned" }
]

Where obviously you can add extra properties for each cat. Presumably your real world application would have some sort of user id, a name, and the GPS location(s) you mentioned.

The data attribute that I set for the ajax request:

data : { lastCat : (cats.length == 0 ? "" : cats[cats.length-1].name) }

Is basically passing through the name of the last cat and leaving it to the PHP to then return only the names of cats added since that one. Obviously in a real world app you would use a user id or record timestamp for that purpose.

EDIT: Old syntax for jQuery Ajax -

function checkForNewCats() {
   $.ajax({
      url: "getcats.php",
      data : { lastCat : (cats.length == 0 ? "" : cats[cats.length-1].name) },
      success : function(data) {
         $.each(data, function(i, val) {
            cats.push(new cat(val.name));
         });
         setTimeout(checkForNewCats, 30000);
      }
   });   
}

Upvotes: 1

davidethell
davidethell

Reputation: 12018

Something like this I would think:

$.getJSON('http://yourserver.com/somefunction/path', function(data){
    $.each(data, function (key, value) {
        var anotherCat = new cat(value);
        anotherCat.talk();
    });
});

Upvotes: 0

Related Questions