0

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!

2 Answers 2

1

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);
      }
   });   
}
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, this is starting to make sense. I implemented your code, but I keep getting errors saying "Uncaught TypeError: Object #<XMLHttpRequest> has no method 'fail'" It seems to not understand the .success, .fail, or .always methods. Should these be within the $.ajax method?
My apologies, I gave you a jQuery Ajax solution even though there was no mention of jQuery in your question, and I think the Ajax syntax I included with .done(), .fail() and .always() only works from about version 1.5 onwards - it uses the newer deferred object style. I've edited my question to show how it would look with the old style success handler too. (Sorry, but I don't have time to give a non-jQuery Ajax solution.) There may be a syntax error there somewhere though - I can't actually test it since I don't have the server-side part of the solution...
Well, I figured out how to implement it a different way, but this definitely help me understand it better. Thanks for your help!
0

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();
    });
});

Comments

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.